# SegGPT

## 개요

SegGPT 모델은 Xinlong Wang, Xiaosong Zhang, Yue Cao, Wen Wang, Chunhua Shen, Tiejun Huang이 발표한 [SegGPT: Segmenting Everything In Context](https://huggingface.co/papers/2304.03284) 논문에서 제안되었습니다. SegGPT는 입력 이미지, 프롬프트 이미지 및 해당 프롬프트 마스크가 주어지면 분할 마스크를 생성할 수 있는 decoder-only Transformer를 사용합니다. 이 모델은 COCO-20에서 56.1 mIoU, FSS-1000에서 85.6 mIoU를 기록하며 뛰어난 one-shot 성능을 달성했습니다.

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

*SegGPT는 컨텍스트 내의 모든 것을 분할하는 범용 모델입니다. 다양한 분할 작업을 동일한 형식의 이미지로 변환하여 서로 다른 종류의 분할 데이터를 수용하는 범용 인컨텍스트 학습 프레임워크로 통합했습니다. SegGPT의 학습은 각 데이터 샘플에 대해 무작위 색상 매핑을 적용하는 인컨텍스트 컬러링 문제로 정의됩니다. 목표는 특정 색상에 의존하기보다 컨텍스트에 따라 다양한 작업을 수행하는 것입니다. 학습이 완료된 후, SegGPT는 객체 인스턴스, 스텍, 부분, 윤곽, 텍스트와 같은 인컨텍스트 추론을 통해 이미지나 비디오에서 임의의 분할 작업을 수행할 수 있습니다. SegGPT는 소수 샘플 시맨틱 분할, 비디오 객체 분할, 시맨틱 분할, 팬옵틱 분할을 포함한 광범위한 작업에서 평가되었습니다. 우리의 결과는 도메인 내 및 도메인 외 분할에서 강력한*

팁:

- [SegGptImageProcessor](/docs/transformers/main/ko/model_doc/seggpt#transformers.SegGptImageProcessor)를 사용하여 모델에 전달할 이미지 입력, 프롬프트, 마스크를 준비할 수 있습니다.
- 세그멘테이션 맵 또는 RGB 이미지를 프롬프트 마스크로 사용할 수 있습니다. 후자를 사용하는 경우 `preprocess` 메서드에서 `do_convert_rgb=False`를 설정해야 합니다.
- `segmentation_maps`를 사용하는 경우(배경 제외) [SegGptImageProcessor](/docs/transformers/main/ko/model_doc/seggpt#transformers.SegGptImageProcessor)로 전처리 및 후처리를 수행할 때 `num_labels`를 전달하는 것이 매우 권장됩니다.
- [SegGptForImageSegmentation](/docs/transformers/main/ko/model_doc/seggpt#transformers.SegGptForImageSegmentation)로 추론을 수행할 때 `batch_size`가 1보다 크면, forward 메서드에 `feature_ensemble=True`를 전달하여 이미지 간 feature ensemble을 사용할 수 있습니다.

…

```python
import torch
from datasets import load_dataset

from transformers import SegGptForImageSegmentation, SegGptImageProcessor

checkpoint = "BAAI/seggpt-vit-large"
image_processor = SegGptImageProcessor.from_pretrained(checkpoint)
model = SegGptForImageSegmentation.from_pretrained(checkpoint, device_map="auto")

dataset_id = "EduardoPacheco/FoodSeg103"
ds = load_dataset(dataset_id, split="train")
# Number of labels in FoodSeg103 (not including background)
num_labels = 103

image_input = ds[4]["image"]
ground_truth = ds[4]["label"]
image_prompt = ds[29]["image"]
mask_prompt = ds[29]["label"]

inputs = image_processor(
    images=image_input,
    prompt_images=image_prompt,
    segmentation_maps=mask_prompt,
    num_labels=num_labels,
    return_tensors="pt"
)

with torch.no_grad():
    outputs = model(**inputs)

target_sizes = [image_input.size[::-1]]
mask = image_processor.post_process_semantic_segmentation(outputs, target_sizes, num_labels=num_labels)[0]
```

이 모델은 [EduardoPacheco](https://huggingface.co/EduardoPacheco)님이 기여했습니다. 원본 코드는 [여기](https://github.com/baaivision/Painter/tree/main)에서 찾을 수 있습니다.

## SegGptConfig[[transformers.SegGptConfig]]

#### transformers.SegGptConfig[[transformers.SegGptConfig]]

```python
transformers.SegGptConfig(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 = 1024, num_hidden_layers: int = 24, num_attention_heads: int = 16, hidden_act: str = 'gelu', hidden_dropout_prob: float | int = 0.0, initializer_range: float = 0.02, layer_norm_eps: float = 1e-06, image_size: int | list[int] | tuple[int, ...] = (896, 448), patch_size: int | list[int] | tuple[int, int] = 16, num_channels: int = 3, qkv_bias: bool = True, mlp_dim: int | None = None, drop_path_rate: float | int = 0.1, pretrain_image_size: int | list[int] | tuple[int, int] = 224, decoder_hidden_size: int = 64, use_relative_position_embeddings: bool = True, merge_index: int = 2, intermediate_hidden_state_indices: list[int] | tuple[int, ...] = (5, 11, 17, 23), beta: float = 0.01)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/seggpt/configuration_seggpt.py#L24)

**매개변수:**

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

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

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

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

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

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

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

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

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

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

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

mlp_dim (`int`, *선택 사항*) : Transformer 인코더의 MLP 레이어 차원입니다. 설정하지 않으면 기본값은 `hidden_size` * 4입니다.

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

pretrain_image_size (`int`, *선택 사항*, 기본값 224) : 절대 위치 임베딩의 사전 학습된 크기입니다.

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

use_relative_position_embeddings (`bool`, *선택 사항*, 기본값 `True`) : attention 레이어에서 상대 위치 임베딩을 사용할지 여부.

merge_index (`int`, *선택 사항*, 기본값 2) : 임베딩을 병합할 인코더 레이어의 인덱스입니다.

intermediate_hidden_state_indices (`list[int]`, *선택 사항*, 기본값 `[5, 11, 17, 23]`) : 디코더의 특징으로 저장할 인코더 레이어의 인덱스입니다.

beta (`float`, *선택 사항*, 기본값 0.01) : SegGptLoss(smooth-l1 loss)의 정규화 계수.

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

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 SegGptConfig, SegGptModel

>>> # Initializing a SegGPT seggpt-vit-large style configuration
>>> configuration = SegGptConfig()

>>> # Initializing a model (with random weights) from the seggpt-vit-large style configuration
>>> model = SegGptModel(configuration)

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

## SegGptImageProcessor[[transformers.SegGptImageProcessor]]

#### transformers.SegGptImageProcessor[[transformers.SegGptImageProcessor]]

```python
transformers.SegGptImageProcessor(**kwargs: *<class 'transformers.models.seggpt.image_processing_seggpt.SegGptImageProcessorKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/seggpt/image_processing_seggpt.py#L74)

**매개변수:**

do_convert_rgb (`bool`, *kwargs*, *선택 사항*, 기본값 `True`) : 이미지를 RGB로 변환할지 여부.

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

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

default_to_square (`bool`, *kwargs*, *선택 사항*, 기본값 `True`) : 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*, 기본값 `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.485, 0.456, 0.406]`) : 정규화에 사용할 이미지 평균입니다. `do_normalize`가 `True`로 설정된 경우에만 효과가 있습니다.

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *선택 사항*, 기본값은 `[0.229, 0.224, 0.225]`) : 정규화에 사용할 이미지 표준 편차입니다. `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*, *선택*) : 입력의 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.

num_labels (`int`, *kwargs*, *선택 사항*) : 세그멘테이션 작업의 클래스 수(배경 제외). 지정된 경우, class_idx 0을 배경으로 가정하여 평범한 세그멘테이션 맵에서 프롬프트 마스크를 3채널 RGB 이미지로 매핑하기 위한 팔레트가 생성됩니다. 이 값을 지정하지 않으면 `do_convert_rgb`가 `True`일 때 프롬프트 마스크가 채널 차원 방향으로 복제됩니다.

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

#### preprocess[[transformers.SegGptImageProcessor.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'], NoneType] = None, prompt_images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, prompt_masks: 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.seggpt.image_processing_seggpt.SegGptImageProcessorKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/seggpt/image_processing_seggpt.py#L135)

**매개변수:**

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

prompt_images (`ImageInput`, *선택 사항*) : 전처리할 프롬프트 이미지. 픽셀 값이 0에서 255 범위로 이루어진 단일 이미지 또는 배치 이미지를 기대합니다.

prompt_masks (`ImageInput`, *선택 사항*) : 전처리할 프롬프트 마스크입니다. 세그멘테이션 맵(채널 없음) 또는 RGB 이미지 형식일 수 있습니다. RGB 이미지 형식인 경우 `do_convert_rgb`를 `False`로 설정해야 합니다. 세그멘테이션 맵 형식인 경우, 단일 채널의 프롬프트 마스크를 3채널 RGB로 매핑하기 위한 팔레트를 구성하려면 `num_labels`를 지정하는 것이 권장됩니다. `num_labels`가 지정되지 않으면, 프롬프트 마스크는 채널 차원 전체에 복제됩니다.

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*, *선택*) : 입력의 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.

num_labels (`int`, *kwargs*, *선택 사항*) : 세그멘테이션 작업의 클래스 수(배경 제외). 지정된 경우, class_idx 0을 배경으로 가정하여 평범한 세그멘테이션 맵에서 프롬프트 마스크를 3채널 RGB 이미지로 매핑하기 위한 팔레트가 생성됩니다. 이 값을 지정하지 않으면 `do_convert_rgb`가 `True`일 때 프롬프트 마스크가 채널 차원 방향으로 복제됩니다.

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

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

#### post_process_semantic_segmentation[[transformers.SegGptImageProcessor.post_process_semantic_segmentation]]

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

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/seggpt/image_processing_seggpt.py#L256)

**매개변수:**

outputs (`SegGptImageSegmentationOutput`) : 모델의 원시 출력

target_sizes (`list[tuple[int, int]]`, *선택 사항*) : 길이가 `batch_size`인 리스트로, 각 항목은 각 예측의 요청된 최종 크기 `(height, width)`에 해당합니다. `None`으로 두면 예측이 리사이즈되지 않습니다.

num_labels (`int`, *선택 사항*) : 세그멘테이션 작업의 클래스 수(배경 제외). 지정되면 예측 마스크의 RGB 값을 클래스 인덱스로 다시 매핑하기 위한 팔레트가 생성됩니다. 전처리 시 사용된 값과 일치해야 합니다.

return_segmentation_scores (`bool`, *선택 사항*, 기본값 `False`) : 세그멘테이션 맵과 함께 세그멘테이션 점수를 반환할지 여부입니다. `True`인 경우, 반환된 리스트의 각 요소는 `segmentation` 필드(클래스 ID, shape `(height, width)`)와 `segmentation_scores` 필드(각 팔레트 색상까지의 음의 제곱 L2 거리, shape `(num_labels+1, height, width)`. `num_labels`가 제공되지 않으면 `None`)를 가진 `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_labels+1, height, width)` 모양) 필드를 가진 `SemanticSegmentationPostProcessorOutput` 리스트를 반환합니다. 두 경우 모두 `(height, width)`는 `target_sizes`가 지정된 경우 해당 대상 크기를 나타냅니다.

`SegGptImageSegmentationOutput`의 출력을 세그멘테이션 맵으로 변환합니다. PyTorch만 지원합니다.

## SegGptImageProcessorPil[[transformers.SegGptImageProcessorPil]]

#### transformers.SegGptImageProcessorPil[[transformers.SegGptImageProcessorPil]]

```python
transformers.SegGptImageProcessorPil(**kwargs: *<class 'transformers.models.seggpt.image_processing_pil_seggpt.SegGptImageProcessorKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/seggpt/image_processing_pil_seggpt.py#L75)

**매개변수:**

do_convert_rgb (`bool`, *kwargs*, *선택 사항*, 기본값 `True`) : 이미지를 RGB로 변환할지 여부.

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

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

default_to_square (`bool`, *kwargs*, *선택 사항*, 기본값 `True`) : 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*, 기본값 `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.485, 0.456, 0.406]`) : 정규화에 사용할 이미지 평균입니다. `do_normalize`가 `True`로 설정된 경우에만 효과가 있습니다.

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *선택 사항*, 기본값은 `[0.229, 0.224, 0.225]`) : 정규화에 사용할 이미지 표준 편차입니다. `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*, *선택*) : 입력의 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.

num_labels (`int`, *kwargs*, *선택 사항*) : 세그멘테이션 작업의 클래스 수(배경 제외). 지정된 경우, class_idx 0을 배경으로 가정하여 평범한 세그멘테이션 맵에서 프롬프트 마스크를 3채널 RGB 이미지로 매핑하기 위한 팔레트가 생성됩니다. 이 값을 지정하지 않으면 `do_convert_rgb`가 `True`일 때 프롬프트 마스크가 채널 차원 방향으로 복제됩니다.

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

#### preprocess[[transformers.SegGptImageProcessorPil.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'], NoneType] = None, prompt_images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, prompt_masks: 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.seggpt.image_processing_pil_seggpt.SegGptImageProcessorKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/seggpt/image_processing_pil_seggpt.py#L136)

**매개변수:**

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

prompt_images (`ImageInput`, *선택 사항*) : 전처리할 프롬프트 이미지. 픽셀 값이 0에서 255 범위로 이루어진 단일 이미지 또는 배치 이미지를 기대합니다.

prompt_masks (`ImageInput`, *선택 사항*) : 전처리할 프롬프트 마스크입니다. 세그멘테이션 맵(채널 없음) 또는 RGB 이미지 형식일 수 있습니다. RGB 이미지 형식인 경우 `do_convert_rgb`를 `False`로 설정해야 합니다. 세그멘테이션 맵 형식인 경우, 단일 채널의 프롬프트 마스크를 3채널 RGB로 매핑하기 위한 팔레트를 구성하려면 `num_labels`를 지정하는 것이 권장됩니다. `num_labels`가 지정되지 않으면, 프롬프트 마스크는 채널 차원 전체에 복제됩니다.

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*, *선택*) : 입력의 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.

num_labels (`int`, *kwargs*, *선택 사항*) : 세그멘테이션 작업의 클래스 수(배경 제외). 지정된 경우, class_idx 0을 배경으로 가정하여 평범한 세그멘테이션 맵에서 프롬프트 마스크를 3채널 RGB 이미지로 매핑하기 위한 팔레트가 생성됩니다. 이 값을 지정하지 않으면 `do_convert_rgb`가 `True`일 때 프롬프트 마스크가 채널 차원 방향으로 복제됩니다.

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

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

#### post_process_semantic_segmentation[[transformers.SegGptImageProcessorPil.post_process_semantic_segmentation]]

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

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/seggpt/image_processing_pil_seggpt.py#L238)

**매개변수:**

outputs (`SegGptImageSegmentationOutput`) : 모델의 원시 출력

target_sizes (`list[tuple[int, int]]`, *선택 사항*) : 길이가 `batch_size`인 리스트로, 각 항목은 각 예측의 요청된 최종 크기 `(height, width)`에 해당합니다. `None`으로 두면 예측이 리사이즈되지 않습니다.

num_labels (`int`, *선택 사항*) : 세그멘테이션 작업의 클래스 수(배경 제외). 지정되면 예측 마스크의 RGB 값을 클래스 인덱스로 다시 매핑하기 위한 팔레트가 생성됩니다. 전처리 시 사용된 값과 일치해야 합니다.

return_segmentation_scores (`bool`, *선택 사항*, 기본값 `False`) : 세그멘테이션 맵과 함께 세그멘테이션 점수를 반환할지 여부입니다. `True`인 경우, 반환된 리스트의 각 요소는 `segmentation` 필드(클래스 ID, shape `(height, width)`)와 `segmentation_scores` 필드(각 팔레트 색상까지의 음의 제곱 L2 거리, shape `(num_labels+1, height, width)`. `num_labels`가 제공되지 않으면 `None`)를 가진 `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_labels+1, height, width)` 모양) 필드를 가진 `SemanticSegmentationPostProcessorOutput` 리스트를 반환합니다. 두 경우 모두 `(height, width)`는 `target_sizes`가 지정된 경우 해당 대상 크기를 나타냅니다.

`SegGptImageSegmentationOutput`의 출력을 세그멘테이션 맵으로 변환합니다. PyTorch만 지원합니다.

## SegGptModel[[transformers.SegGptModel]]

#### transformers.SegGptModel[[transformers.SegGptModel]]

```python
transformers.SegGptModel(config: SegGptConfig)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/seggpt/modeling_seggpt.py#L613)

**매개변수:**

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

특정 헤드가 위에 없는 상태의 Seggpt 모델은 원시 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.SegGptModel.forward]]

```python
forward(pixel_values: Tensor, prompt_pixel_values: Tensor, prompt_masks: Tensor, bool_masked_pos: typing.Optional[torch.BoolTensor] = None, feature_ensemble: bool | None = None, embedding_type: str | None = None, labels: typing.Optional[torch.Tensor] = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, **kwargs)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/seggpt/modeling_seggpt.py#L627)

**매개변수:**

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

prompt_pixel_values (`torch.Tensor`, shape `(batch_size, num_channels, height, width)`) : 프롬프트 픽셀 값. [AutoImageProcessor](/docs/transformers/main/ko/model_doc/auto#transformers.AutoImageProcessor)를 사용하여 프롬프트 픽셀 값을 얻을 수 있습니다. 자세한 내용은 [SegGptImageProcessor.__call__()](/docs/transformers/main/ko/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)를 참조하세요.

prompt_masks (`torch.Tensor`, shape `(batch_size, num_channels, height, width)`) : 프롬프트 마스크. [AutoImageProcessor](/docs/transformers/main/ko/model_doc/auto#transformers.AutoImageProcessor)를 사용하여 프롬프트 마스크를 얻을 수 있습니다. 자세한 내용은 [SegGptImageProcessor.__call__()](/docs/transformers/main/ko/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)를 참조하세요.

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

feature_ensemble (`bool`, *선택 사항*) : feature ensemble을 사용할지 여부를 나타내는 부울 값입니다. `True`인 경우, 프롬프트가 최소 두 개 이상이면 모델은 feature ensemble을 사용합니다. `False`인 경우, 모델은 feature ensemble을 사용하지 않습니다. 이 인수는 동일한 입력 이미지에 대해 프롬프트가 하나 이상인 few-shot 추론을 수행할 때 고려해야 합니다.

embedding_type (`str`, *선택 사항*) : 임베딩 유형. 프롬프트가 의미론적 임베딩인지 인스턴스 임베딩인지 나타냅니다. instance 또는 semantic 중 하나여야 합니다.

labels (`torch.Tensor`, shape `(batch_size, num_channels, height, width)`, `optional`) : 입력 이미지의 ground truth mask입니다.

output_attentions (`bool`, *선택 사항*) : 모든 어텐션 레이어의 어텐션 텐서를 반환할지 여부. 자세한 내용은 반환 텐서 섹션의 `attentions`를 참조하세요.

output_hidden_states (`bool`, *선택 사항*) : 모든 레이어의 hidden states를 반환할지 여부. 자세한 내용은 반환되는 텐서 중 `hidden_states` 항목을 참조하세요.

return_dict (`bool`, *선택 사항*) : 일반 튜플 대신 [ModelOutput](/docs/transformers/main/ko/main_classes/output#transformers.utils.ModelOutput)를 반환할지 여부.

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

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

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

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

- **last_hidden_state** (`torch.Tensor`, shape `(batch_size, patch_height, patch_width, hidden_size)`) -- 모델의 마지막 레이어 출력에서 생성된 hidden-state 시퀀스입니다.
- **hidden_states** (`tuple[torch.Tensor]`, `optional`, `config.output_hidden_states=True`일 때 반환됨) -- `torch.Tensor`의 튜플(임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은 `(batch_size, patch_height, patch_width, hidden_size)`입니다.
- **attentions** (`tuple[torch.Tensor]`, `optional`, `config.output_attentions=True`일 때 반환됨) -- `(batch_size, num_heads, seq_len, seq_len)` 모양의 *torch.Tensor* 튜플(각 레이어마다 하나).
- **intermediate_hidden_states** (`tuple[torch.Tensor]`, *선택 사항*, `config.intermediate_hidden_state_indices`가 설정된 경우 반환됨) -- `(batch_size, patch_height, patch_width, hidden_size)` 모양의 `torch.Tensor` 튜플입니다. 튜플의 각 요소는 `config.intermediate_hidden_state_indices`에 지정된 레이어의 출력에 해당합니다. 또한, 각 특징은 LayerNorm을 통과합니다.

예:

```python
>>> from transformers import SegGptImageProcessor, SegGptModel
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> image_input_url = "https://raw.githubusercontent.com/baaivision/Painter/main/SegGPT/SegGPT_inference/examples/hmbb_2.jpg"
>>> image_prompt_url = "https://raw.githubusercontent.com/baaivision/Painter/main/SegGPT/SegGPT_inference/examples/hmbb_1.jpg"
>>> mask_prompt_url = "https://raw.githubusercontent.com/baaivision/Painter/main/SegGPT/SegGPT_inference/examples/hmbb_1_target.png"

>>> with httpx.stream("GET", image_input_url) as response:
...     image_input = Image.open(BytesIO(response.read()))

>>> with httpx.stream("GET", image_prompt_url) as response:
...     image_prompt = Image.open(BytesIO(response.read()))

>>> with httpx.stream("GET", mask_prompt_url) as response:
...     mask_prompt = Image.open(BytesIO(response.read())).convert("L")

>>> checkpoint = "BAAI/seggpt-vit-large"
>>> model = SegGptModel.from_pretrained(checkpoint)
>>> image_processor = SegGptImageProcessor.from_pretrained(checkpoint)

>>> inputs = image_processor(images=image_input, prompt_images=image_prompt, prompt_masks=mask_prompt, return_tensors="pt")

>>> outputs = model(**inputs)
>>> list(outputs.last_hidden_state.shape)
[1, 56, 28, 1024]
```

## SegGptForImageSegmentation[[transformers.SegGptForImageSegmentation]]

#### transformers.SegGptForImageSegmentation[[transformers.SegGptForImageSegmentation]]

```python
transformers.SegGptForImageSegmentation(config: SegGptConfig)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/seggpt/modeling_seggpt.py#L819)

**매개변수:**

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

원샷 이미지 분할을 위해 상단에 디코더가 있는 SegGpt 모델.

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

```python
forward(pixel_values: Tensor, prompt_pixel_values: Tensor, prompt_masks: Tensor, bool_masked_pos: typing.Optional[torch.BoolTensor] = None, feature_ensemble: bool | None = None, embedding_type: str | None = None, labels: typing.Optional[torch.Tensor] = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, **kwargs)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/seggpt/modeling_seggpt.py#L830)

**매개변수:**

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

prompt_pixel_values (`torch.Tensor`, shape `(batch_size, num_channels, height, width)`) : 프롬프트 픽셀 값. [AutoImageProcessor](/docs/transformers/main/ko/model_doc/auto#transformers.AutoImageProcessor)를 사용하여 프롬프트 픽셀 값을 얻을 수 있습니다. 자세한 내용은 [SegGptImageProcessor.__call__()](/docs/transformers/main/ko/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)를 참조하세요.

prompt_masks (`torch.Tensor`, shape `(batch_size, num_channels, height, width)`) : 프롬프트 마스크. [AutoImageProcessor](/docs/transformers/main/ko/model_doc/auto#transformers.AutoImageProcessor)를 사용하여 프롬프트 마스크를 얻을 수 있습니다. 자세한 내용은 [SegGptImageProcessor.__call__()](/docs/transformers/main/ko/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)를 참조하세요.

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

feature_ensemble (`bool`, *선택 사항*) : feature ensemble을 사용할지 여부를 나타내는 부울 값입니다. `True`인 경우, 프롬프트가 최소 두 개 이상이면 모델은 feature ensemble을 사용합니다. `False`인 경우, 모델은 feature ensemble을 사용하지 않습니다. 이 인수는 동일한 입력 이미지에 대해 프롬프트가 하나 이상인 few-shot 추론을 수행할 때 고려해야 합니다.

embedding_type (`str`, *선택 사항*) : 임베딩 유형. 프롬프트가 의미론적 임베딩인지 인스턴스 임베딩인지 나타냅니다. instance 또는 semantic 중 하나여야 합니다.

labels (`torch.Tensor`, shape `(batch_size, num_channels, height, width)`, `optional`) : 입력 이미지의 ground truth mask입니다.

output_attentions (`bool`, *선택 사항*) : 모든 어텐션 레이어의 어텐션 텐서를 반환할지 여부. 자세한 내용은 반환 텐서 섹션의 `attentions`를 참조하세요.

output_hidden_states (`bool`, *선택 사항*) : 모든 레이어의 hidden states를 반환할지 여부. 자세한 내용은 반환되는 텐서 중 `hidden_states` 항목을 참조하세요.

return_dict (`bool`, *선택 사항*) : 일반 튜플 대신 [ModelOutput](/docs/transformers/main/ko/main_classes/output#transformers.utils.ModelOutput)를 반환할지 여부.

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

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

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

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

- **loss** (`torch.Tensor`, *선택 사항*, `labels`이 제공될 때 반환됨) -- 손실 값입니다.
- **pred_masks** (`torch.Tensor`, shape `(batch_size, num_channels, height, width)`) -- 예측된 마스크입니다.
- **hidden_states** (`tuple[torch.Tensor]`, `optional`, `config.output_hidden_states=True`일 때 반환됨) -- `torch.Tensor`의 튜플(임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은 `(batch_size, patch_height, patch_width, hidden_size)`입니다.
- **attentions** (`tuple[torch.Tensor]`, `optional`, `config.output_attentions=True`일 때 반환됨) -- 각 레이어마다 하나씩 포함된 `torch.Tensor`의 튜플로, 모양은 `(batch_size, num_heads, seq_len, seq_len)`입니다.

예:

```python
>>> from transformers import SegGptImageProcessor, SegGptForImageSegmentation
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> image_input_url = "https://raw.githubusercontent.com/baaivision/Painter/main/SegGPT/SegGPT_inference/examples/hmbb_2.jpg"
>>> image_prompt_url = "https://raw.githubusercontent.com/baaivision/Painter/main/SegGPT/SegGPT_inference/examples/hmbb_1.jpg"
>>> mask_prompt_url = "https://raw.githubusercontent.com/baaivision/Painter/main/SegGPT/SegGPT_inference/examples/hmbb_1_target.png"

>>> with httpx.stream("GET", image_input_url) as response:
...     image_input = Image.open(BytesIO(response.read()))

>>> with httpx.stream("GET", image_prompt_url) as response:
...     image_prompt = Image.open(BytesIO(response.read()))

>>> with httpx.stream("GET", mask_prompt_url) as response:
...     mask_prompt = Image.open(BytesIO(response.read())).convert("L")

>>> checkpoint = "BAAI/seggpt-vit-large"
>>> model = SegGptForImageSegmentation.from_pretrained(checkpoint)
>>> image_processor = SegGptImageProcessor.from_pretrained(checkpoint)

>>> inputs = image_processor(images=image_input, prompt_images=image_prompt, prompt_masks=mask_prompt, return_tensors="pt")
>>> outputs = model(**inputs)
>>> result = image_processor.post_process_semantic_segmentation(outputs, target_sizes=[(image_input.height, image_input.width)])[0]
>>> print(list(result.shape))
[170, 297]
```

