# Sapiens2

    
        
        
    

## 개요

Sapiens2 모델은 Rawal Khirodkar, He Wen, Julieta Martinez, Yuan Dong, Zhaoen Su, Shunsuke Saito가 [Sapiens2](https://huggingface.co/papers/2604.21681)에서 제안했습니다. Sapiens2는 약 10억 개의 큐레이션된 인간 이미지로 사전 학습된 고해상도 비전 트랜스포머 모델군으로, 자세 추정, 신체 부위 분할, 표면 법선 추정, 포인트맵 추정을 포함한 인간 중심 컴퓨터 비전 작업을 위해 설계되었습니다.

모든 원본 Sapiens2 체크포인트는 [Sapiens2](https://huggingface.co/collections/facebook/sapiens2) 컬렉션에서 찾을 수 있습니다.

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

*Sapiens2를 소개합니다. Sapiens2는 일반화, 다용도성, 고충실도 출력을 중심으로 한 인간 중심 비전용 고해상도 transformer 계열입니다. 개선된 작업 주석이 포함된 약 10억 장의 고품질 인간 이미지로 사전 학습을 수행하고, masked image reconstruction과 self-distilled contrastive objectives를 결합하여 저수준 및 의미론적 특징을 모두 학습합니다. 모델은 0.4B에서 5B 파라미터로 확장되며, 네이티브 1K 해상도로 학습되고, 확장된 공간 추론을 위한 계층적 4K 변형이 제공됩니다. Sapiens2는 이전 모델 대비 상당한 성능 향상을 달성했습니다: pose estimation에서 +4 mAP, body-part segmentation에서 +24.3 mIoU, normal estimation에서 45.6%의 오류 감소, 그리고 pointmap 및 albedo estimation과 같은 새로운 작업으로의 확장. 코드는 공개되어 있습니다.*

팁:

- Sapiens2는 Rotary Position Embeddings(RoPE)를 사용하며 임의의 입력 해상도를 지원합니다. 기본 이미지 프로세서는 이미지를 1024×768(높이×너비)로 리사이즈합니다.
- 모델은 중간 레이어에 Grouped Query Attention(GQA)을 사용하고, 처음 8개와 마지막 8개 레이어에는 완전한 multi-head attention을 사용합니다.
- 기본값인 8개의 Register tokens는 패치 토큰의 고노름(high-norm) 아티팩트를 줄여 더 깔끔한 어텐션 맵을 생성하고, 밀집 예측(dense prediction) 작업에서 더 나은 성능을 제공합니다.

이 모델은 [guarin](https://huggingface.co/guarin)이(가) 기여했습니다. 원본 코드는 [여기](https://github.com/facebookresearch/sapiens2)에서 찾을 수 있습니다.

## 사용 예시

아래 예제는 [Sapiens2Model](/docs/transformers/v5.23.0/ko/model_doc/sapiens2#transformers.Sapiens2Model)로 CLS 토큰(전체 이미지 임베딩)을 가져오는 방법을 보여줍니다.

```python
import torch
from transformers import AutoImageProcessor, AutoModel
from transformers.image_utils import load_image

image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")

image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-pretrain-0.4b")
model = AutoModel.from_pretrained("facebook/sapiens2-pretrain-0.4b", device_map="auto")

inputs = image_processor(images=image, return_tensors="pt").to(model.device)
with torch.inference_mode():
    outputs = model(**inputs)

# outputs.pooler_output is the CLS token (whole-image embedding)
cls_token = outputs.pooler_output
print("CLS token shape:", cls_token.shape)  # [1, 1024]
```

[Sapiens2Backbone](/docs/transformers/v5.23.0/ko/model_doc/sapiens2#transformers.Sapiens2Backbone)는 출력 객체에 공간 차원으로 이미 리사이즈된 패치 토큰과 CLS 토큰을 직접 노출합니다.

```python
import torch
from transformers import AutoBackbone, AutoImageProcessor
from transformers.image_utils import load_image

image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")

image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-pretrain-0.4b")
model = AutoBackbone.from_pretrained("facebook/sapiens2-pretrain-0.4b", device_map="auto")

inputs = image_processor(images=image, return_tensors="pt").to(model.device)
with torch.inference_mode():
    outputs = model(**inputs, return_class_token=True)

# Patch tokens shaped (batch, height, width, channels)
patch_features = outputs.feature_maps[0]
cls_token = outputs.cls_tokens[0]
print("CLS token shape:", cls_token.shape)           # [1, 1024]
print("Patch features shape:", patch_features.shape) # [1, 64, 48, 1024]
```

아래 예제는 [Sapiens2ForNormalEstimation](/docs/transformers/v5.23.0/ko/model_doc/sapiens2#transformers.Sapiens2ForNormalEstimation)를 사용하여 표면 법선(surface normals)을 추정하는 방법을 보여줍니다. 출력되는 법선은 정규화되지 않은 원시(raw) 값입니다. `post_process_normal_estimation`를 사용하여 크기를 조정하고 L2 정규화를 수행하세요.

```python
import torch
from transformers import AutoImageProcessor, AutoModelForNormalEstimation
from transformers.image_utils import load_image

image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")

image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-normal-0.4b")
model = AutoModelForNormalEstimation.from_pretrained("facebook/sapiens2-normal-0.4b", device_map="auto")

inputs = image_processor(image, return_tensors="pt").to(model.device)
with torch.inference_mode():
    outputs = model(**inputs)

# outputs.normals shape: (batch_size, 3, height, width) — raw, unnormalized XYZ normals
print("Normals shape:", outputs.normals.shape)  # [1, 3, 1024, 768]

# Remove preprocessing padding, resize to original size, and L2-normalize to unit vectors in [-1, 1]
original_size = (image.height, image.width)
result = image_processor.post_process_normal_estimation(
    outputs, source_sizes=[original_size], target_sizes=[original_size]
)
normals = result[0]["normals"]
print("Normals shape:", normals.shape)   # [3, original_height, original_width]

### Example code for visualization

# Convert L2-normalized normals in [-1, 1] to RGB in [0, 255]
normals_rgb = ((normals + 1.0) / 2.0 * 255.0).clamp(0, 255).to(torch.uint8)

# Apply background removal using the segmentation model output.
# `segmentation` is the output of `post_process_semantic_segmentation` — a (H, W) tensor
# of per-pixel class IDs, where class 0 is background.
background_mask = segmentation == 0
normals_rgb[:, background_mask] = 0
print("Normals RGB shape:", normals_rgb.shape)   # [3, original_height, original_width]
```

아래 예제는 [Sapiens2ForPointmapEstimation](/docs/transformers/v5.23.0/ko/model_doc/sapiens2#transformers.Sapiens2ForPointmapEstimation)를 사용하여 픽셀별 3D 좌표를 추정하는 방법을 보여줍니다. `post_process_pointmap_estimation`을 사용하여 전처리 패딩을 제거하고, 원래 이미지 크기로 리사이즈하며, 예측된 초점 거리 스케일을 적용합니다.

```python
import torch
from transformers import AutoImageProcessor, AutoModelForPointmapEstimation
from transformers.image_utils import load_image

image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")

image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-pointmap-0.4b")
model = AutoModelForPointmapEstimation.from_pretrained("facebook/sapiens2-pointmap-0.4b", device_map="auto")

inputs = image_processor(image, return_tensors="pt").to(model.device)
with torch.inference_mode():
    outputs = model(**inputs)

# outputs.pointmaps shape: (batch_size, 3, height, width) — raw XYZ in canonical camera space
print("Pointmaps shape:", outputs.pointmaps.shape)  # [1, 3, 1024, 768]

# Remove preprocessing padding, resize to original size, and apply focal-length scale
original_size = (image.height, image.width)
result = image_processor.post_process_pointmap_estimation(
    outputs, source_sizes=[original_size], target_sizes=[original_size]
)
pointmap = result[0]["pointmap"]
print("Pointmap shape:", pointmap.shape)  # [3, original_height, original_width]

### Example code for visualization

# Visualize the pointmap as an RGB image using inverse-depth and the turbo colormap.
import matplotlib.pyplot as plt

# `segmentation` is the output of `post_process_semantic_segmentation` — a (H, W) tensor
# of per-pixel class IDs, where class 0 is background.
foreground_mask = segmentation != 0
depth = pointmap[2]  # Z channel: depth in camera space, shape (H, W)
pointmap_rgb = torch.zeros(3, *depth.shape, dtype=torch.uint8)
foreground_depth = depth[foreground_mask]
if foreground_depth.numel() > 0:
    depth_low, depth_high = torch.quantile(foreground_depth, torch.tensor([0.01, 0.99]))
    inverse_depth = 1.0 / foreground_depth.clamp(min=1e-6)
    inverse_depth_low = 1.0 / depth_high.clamp(min=1e-6)
    inverse_depth_high = 1.0 / depth_low.clamp(min=1e-6)
    inverse_depth_normalized = ((inverse_depth - inverse_depth_low) / (inverse_depth_high - inverse_depth_low + 1e-8)).clamp(0, 1)
    turbo = plt.get_cmap("turbo")
    foreground_colors = torch.from_numpy(turbo(inverse_depth_normalized.cpu().numpy())[..., :3] * 255).to(torch.uint8)  # (N, 3)
    pointmap_rgb[:, foreground_mask] = foreground_colors.T
print("Pointmap RGB shape:", pointmap_rgb.shape)  # [3, original_height, original_width]
```

아래 예제는 [Sapiens2ForPoseEstimation](/docs/transformers/v5.23.0/ko/model_doc/sapiens2#transformers.Sapiens2ForPoseEstimation)로 포즈 추정을 실행하는 방법을 보여줍니다. 모델은 키포인트별 히트맵을 예측하며, `post_process_pose_estimation`를 사용하여 이를 이미지 공간의 키포인트 좌표로 복원합니다. `opencv-python`가 필요합니다(`pip install opencv-python`).

```python
import torch
from transformers import AutoImageProcessor, AutoModelForPoseEstimation
from transformers.image_utils import load_image

image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")

image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-pose-0.4b")
model = AutoModelForPoseEstimation.from_pretrained("facebook/sapiens2-pose-0.4b", device_map="auto")

# Provide bounding boxes in COCO format (x, y, width, height) for each person
boxes = [[[270.8, 0.6, 294.1, 379.5]]]
inputs = image_processor(image, boxes=boxes, return_tensors="pt").to(model.device)
with torch.inference_mode():
    outputs = model(**inputs)

# outputs.heatmaps shape: (num_persons, num_keypoints, heatmap_height, heatmap_width)
print("Heatmaps shape:", outputs.heatmaps.shape)  # [1, 308, 256, 192]

# Decode heatmaps to image-space keypoint coordinates
results = image_processor.post_process_pose_estimation(outputs, boxes=boxes)[0]
keypoints = results[0]["keypoints"]   # (num_keypoints, 2) — x/y in image coordinates
scores = results[0]["scores"]         # (num_keypoints,) — per-keypoint confidence
print("Keypoints shape:", keypoints.shape)
```

수평 플립 증강(추론 시 증강)은 원본 이미지와 거울 반전된 이미지의 예측을 평균화하여 키포인트 정확도를 향상시킵니다. 두 번째 포워드 패스에 `flip_pairs`를 전달하세요. `flip_pairs`는 `[left_keypoint, right_keypoint]` 쌍으로 구성된 텐서입니다. 모델은 반환하기 전에 히트맵을 원래 방향의 히트맵으로 되돌리므로, 두 출력을 직접 평균화할 수 있습니다.

```python
import torch
from transformers import AutoImageProcessor, AutoModelForPoseEstimation
from transformers.image_utils import load_image

image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")

image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-pose-0.4b")
model = AutoModelForPoseEstimation.from_pretrained("facebook/sapiens2-pose-0.4b", device_map="auto")

boxes = [[[270.8, 0.6, 294.1, 379.5]]]
inputs = image_processor(image, boxes=boxes, return_tensors="pt").to(model.device)
pixel_values = inputs["pixel_values"]

flip_pairs = torch.tensor(model.config.flip_pairs, device=model.device)

with torch.inference_mode():
    outputs = model(pixel_values)
    outputs_flipped = model(pixel_values.flip(-1), flip_pairs=flip_pairs)

results = image_processor.post_process_pose_estimation(outputs, outputs_flipped=outputs_flipped, boxes=boxes)[0]
keypoints = results[0]["keypoints"]
scores = results[0]["scores"]
```

아래 예제는 `labels`와 선택적 `label_weights`를 전달하여 [Sapiens2ForPoseEstimation](/docs/transformers/v5.23.0/ko/model_doc/sapiens2#transformers.Sapiens2ForPoseEstimation)로 supervised Masked Mean Squared Error (MSE) loss를 계산하는 방법을 보여줍니다. 이는 `Trainer` API를 활용한 fine-tuning에 유용합니다.

```python
import torch
from transformers import AutoImageProcessor, AutoModelForPoseEstimation
from transformers.image_utils import load_image

image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")

image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-pose-0.4b")
model = AutoModelForPoseEstimation.from_pretrained("facebook/sapiens2-pose-0.4b", device_map="auto")

# Provide bounding boxes in COCO format (x, y, width, height) for each person
boxes = [[[270.8, 0.6, 294.1, 379.5]]]
inputs = image_processor(image, boxes=boxes, return_tensors="pt").to(model.device)

# Create dummy labels (heatmaps) and visibility weights to simulate ground truth
# 1.0 for visible keypoints, 0.0 for occluded/invisible keypoints
batch_size, num_keypoints = 1, 308
heatmap_height, heatmap_width = 1024, 768
labels = torch.randn(batch_size, num_keypoints, heatmap_height, heatmap_width, device=model.device)
label_weights = torch.ones(batch_size, num_keypoints, 1, 1, device=model.device)

# Forward pass with loss calculation
outputs = model(**inputs, labels=labels, label_weights=label_weights)

print("Loss:", outputs.loss.item())
```

아래 예제는 [Sapiens2ForSemanticSegmentation](/docs/transformers/v5.23.0/ko/model_doc/sapiens2#transformers.Sapiens2ForSemanticSegmentation)를 사용하여 신체 부위 분할을 수행하는 방법을 보여줍니다.

```python
import torch
from transformers import AutoImageProcessor, AutoModelForSemanticSegmentation
from transformers.image_utils import load_image

image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")

image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-seg-0.4b")
model = AutoModelForSemanticSegmentation.from_pretrained("facebook/sapiens2-seg-0.4b", device_map="auto")

inputs = image_processor(image, return_tensors="pt").to(model.device)
with torch.inference_mode():
    outputs = model(**inputs)

# outputs.logits shape: (batch_size, num_labels, height, width)
print("Logits shape:", outputs.logits.shape)  # [1, 29, 1024, 768]

# Get per-pixel class predictions, optionally resized to the original image size
original_size = (image.height, image.width)
segmentation = image_processor.post_process_semantic_segmentation(
    outputs, target_sizes=[original_size]
)[0]
print("Segmentation map shape:", segmentation.shape)  # [original_height, original_width]
```

아래 예제는 [Sapiens2ForImageMatting](/docs/transformers/v5.23.0/ko/model_doc/sapiens2#transformers.Sapiens2ForImageMatting)로 이미지 매팅을 실행하는 방법을 보여줍니다. 출력은 시그모이드 활성화가 적용되어 이미 `[0, 1]` 범위에 있으며, `post_process_image_matting`를 사용해 크기를 조정하고 `alphas`, `foregrounds`, 그리고 선택적인 `composite` 이미지로 분리합니다. composite 이미지는 다음 수식으로 배경 위에 포그라운드가 겹쳐진 모습을 보여줍니다: `composite = foreground * (1 - alpha) * background`.

```python
import torch
from transformers import AutoImageProcessor, AutoModelForImageMatting
from transformers.image_utils import load_image

image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")

image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-matting-1b")
model = AutoModelForImageMatting.from_pretrained("facebook/sapiens2-matting-1b", device_map="auto")

inputs = image_processor(image, return_tensors="pt").to(model.device)
with torch.inference_mode():
    outputs = model(**inputs)

# outputs.foregrounds: (1, 3, H, W), outputs.alphas: (1, 1, H, W) — both in [0, 1]
original_size = (image.height, image.width)

# Pass an optional background to composite the foreground over it.
# A (3, 1, 1) tensor broadcasts as a uniform color; PIL images and numpy arrays are also accepted.
background = torch.tensor([0, 177, 64], dtype=torch.uint8).view(3, 1, 1)  # chroma green in RGB
result = image_processor.post_process_image_matting(
    outputs, target_sizes=[original_size], backgrounds=background
)[0]
print("Alpha shape:", result["alpha"].shape)        # [1, original_height, original_width]
print("Foreground shape:", result["foreground"].shape)  # [3, original_height, original_width]
print("Composite shape:", result["composite"].shape)    # [3, original_height, original_width] — uint8 [0, 255]
```

## Sapiens2Config[[transformers.Sapiens2Config]]

#### transformers.Sapiens2Config[[transformers.Sapiens2Config]]

```python
transformers.Sapiens2Config(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, patch_size: int | list[int] | tuple[int, int] = 16, hidden_size: int = 1024, intermediate_size: int = 4096, num_hidden_layers: int = 24, num_attention_heads: int = 16, hidden_act: str = 'silu', attention_dropout: float | int = 0.0, initializer_range: float = 0.02, rope_theta: float = 100.0, image_size: int | list[int] | tuple[int, int] = 224, num_channels: int = 3, query_bias: bool = True, key_bias: bool = True, value_bias: bool = True, proj_bias: bool = True, mlp_bias: bool = True, layerscale_value: float = 1.0, drop_path_rate: float | int = 0.0, use_gated_mlp: bool = True, num_register_tokens: int = 8, pos_embed_shift: float | None = None, pos_embed_jitter: float | None = None, pos_embed_rescale: float | None = 2.0, _out_features: list[str] | None = None, _out_indices: list[int] | None = None, reshape_hidden_states: bool = True, use_mask_token: bool = False, rms_norm_eps: float = 1e-06, normalize_backbone_outputs: bool = True, use_qk_norm: bool = True, num_key_value_heads_per_layer: list[int] | None = None, num_key_value_attention_heads: int = 8, num_first_full_attention_layers: int = 8, num_last_full_attention_layers: int = 8, semantic_loss_ignore_index: int = 255, flip_pairs: list[list[int]] | None = None, head_config: transformers.models.sapiens2.configuration_sapiens2.Sapiens2HeadConfig | dict | None = None)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sapiens2/configuration_sapiens2.py#L116)

**매개변수:**

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

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

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

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

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

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

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

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

rope_theta (`float`, *선택 사항*, 기본값 100.0) : RoPE 임베딩의 기본 주기입니다.

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

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

query_bias (`bool`, *선택 사항*, 기본값 `True`) : 쿼리 투영에 바이어스를 추가할지 여부.

key_bias (`bool`, *선택 사항*, 기본값 `False`) : 키 투영에 바이어스를 추가할지 여부.

value_bias (`bool`, *선택 사항*, 기본값 `True`) : value projection에 bias를 추가할지 여부.

proj_bias (`bool`, *선택 사항*, 기본값 `True`) : 출력 투영에 바이어스를 추가할지 여부.

mlp_bias (`bool`, *선택 사항*, 기본값 `True`) : MLP 레이어의 up_proj, down_proj 및 gate_proj 레이어에 bias를 사용할지 여부.

layerscale_value (`float`, *선택 사항*, 기본값 1.0) : layer scale에 사용할 초기 값입니다.

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

use_gated_mlp (`bool`, *선택 사항*, 기본값 `False`) : SwiGLU 피드포워드 신경망을 사용할지 여부.

num_register_tokens (`int`, *선택 사항*, 기본값 0) : 레지스터 토큰의 수입니다.

pos_embed_shift (`float`, *선택 사항*) : 학습 모드에서만 `None`이 아닌 경우, [-shift, shift] 범위 내에서 위치 임베딩 좌표를 무작위로 이동할 양.

pos_embed_jitter (`float`, *선택 사항*) : 학습 모드에서만 `None`이 아닌 경우 적용되며, [1/jitter, jitter] 범위의 로그 균등 값으로 위치 임베딩 좌표를 무작위로 jitter하는 양.

pos_embed_rescale (`float`, *선택 사항*, 기본값 2.0) : 학습 모드에서 `None`이 아닌 경우에만 적용되며, [1/rescale, rescale] 범위의 로그 균등 값으로 위치 임베딩 좌표를 무작위로 재조정하는 양입니다.

reshape_hidden_states (`bool`, *선택 사항*, 기본값 `True`) : backbone으로 사용될 때 hidden states를 공간 차원으로 reshape할지 여부입니다.

use_mask_token (`bool`, *선택 사항*, 기본값 `False`) : 임베딩에 마스크 토큰을 사용할지 여부(마스크 이미지 모델링 사전 학습에 필요).

rms_norm_eps (`float`, *선택 사항*, 기본값 1e-6) : RMS 정규화 레이어에 사용되는 Epsilon 값입니다.

normalize_backbone_outputs (`bool`, *선택 사항*, 기본값 `True`) : forward pass에서 backbone의 `feature_maps` 및 `cls_tokens` 출력을 반환하기 전에 RMSNorm을 적용할지 여부. 모델이 backbone으로 사용될 때만 적용됩니다.

use_qk_norm (`bool`, *선택 사항*, 기본값 `True`) : attention 레이어에서 RoPE 적용 전에 query와 key에 RMSNorm을 적용할지 여부.

num_key_value_heads_per_layer (`list[int]`, *선택 사항*) : 각 transformer 레이어의 key/value 헤드 수. 레이어의 값을 `num_attention_heads`와 동일하게 설정하면 완전한 multi-head attention을, 더 작은 값을 설정하면 grouped-query attention을 제공합니다. 기본값은 처음 `num_first_full_attention_layers`개와 마지막 `num_last_full_attention_layers`개 레이어에 대해 `num_attention_heads`, 나머지 모든 레이어에 대해 `num_key_value_attention_heads`입니다.

num_key_value_attention_heads (`int`, *선택 사항*, 기본값 `8`) : `num_key_value_heads_per_layer`이 설정되지 않은 경우, grouped-query attention을 사용하는 레이어의 key/value 헤드 수입니다. `num_key_value_heads_per_layer`가 설정된 경우 무시됩니다.

num_first_full_attention_layers (`int`, *선택 사항*, 기본값 8) : 전체 멀티헤드 어텐션을 사용하는 앞부분 트랜스포머 레이어의 수입니다. `num_key_value_heads_per_layer`가 `None`인 경우에만 사용됩니다.

num_last_full_attention_layers (`int`, *선택 사항*, 기본값 8) : 전체 멀티헤드 어텐션을 사용하는 후방 transformer 레이어의 수입니다. `num_key_value_heads_per_layer`가 `None`인 경우에만 사용됩니다.

semantic_loss_ignore_index (`int`, *선택 사항*, 기본값 255) : 분할 손실을 계산할 때 무시되는 라벨 인덱스.

flip_pairs (`list[list[int]]`, *선택 사항*) : 수평으로 거울처럼 대응되는 키포인트 인덱스 쌍(예: 왼쪽 귀 ↔ 오른쪽 귀)입니다. 각 쌍은 두 요소의 리스트 `[left_index, right_index]`입니다. 자세 추정에서 테스트 시 수평 플립 증강에 사용됩니다: 모델이 반환하기 전에 히트맵을 원래대로 되돌리도록 이 쌍을 두 번째 forward 호출에 전달합니다.

head_config (`Sapiens2HeadConfig`, *선택 사항*) : 디코딩 헤드의 설정입니다. 사용 가능한 옵션은 [Sapiens2HeadConfig](/docs/transformers/v5.23.0/ko/model_doc/sapiens2#transformers.Sapiens2HeadConfig)를 참조하세요.

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

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

## Sapiens2HeadConfig[[transformers.Sapiens2HeadConfig]]

#### transformers.Sapiens2HeadConfig[[transformers.Sapiens2HeadConfig]]

```python
transformers.Sapiens2HeadConfig(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, upsample_out_channels: list[int] | None = None, upsample_kernel_sizes: list[int] | None = None, upsample_kernel_size: int = 4, use_pixel_shuffle: bool | None = None, conv_out_channels: list[int] | None = None, conv_kernel_sizes: list[int] | None = None, conv_kernel_size: int = 1, scale_conv_out_channels: list[int] | None = None, scale_conv_kernel_sizes: list[int] | None = None, scale_conv_kernel_size: int = 1, scale_final_input_size: int | None = None, scale_final_hidden_sizes: list[int] | None = None)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sapiens2/configuration_sapiens2.py#L28)

**매개변수:**

upsample_out_channels (`list[int]`, *선택 사항*) : 각 업샘플 블록의 출력 채널 수입니다. 첫 번째 블록은 `hidden_size` 채널을 입력으로 사용하며, 이후 블록은 이전 블록의 출력을 사용합니다.

upsample_kernel_sizes (`list[int]`, *선택 사항*) : 각 업샘플 블록의 커널 크기. `upsample_out_channels`가 설정되어 있고 이 값이 `None`인 경우 `[4, ...]`로 자동 채워집니다. `upsample_out_channels`와 동일한 길이를 가져야 합니다.

upsample_kernel_size (`int`, 기본값 4) : `upsample_kernel_sizes`가 설정되지 않은 경우 업샘플 블록의 기본 커널 크기입니다.

use_pixel_shuffle (`bool`, *선택 사항*) : 업샘플링 헤드가 전치 컨볼루션 대신 픽셀 셔플 업샘플링을 사용하는지 여부입니다. `None`(기본값)인 경우, 헤드는 전치 컨볼루션을 사용합니다.

conv_out_channels (`list[int]`, *선택 사항*) : 업샘플 블록 뒤에 오는 리파인먼트 컨볼루션 레이어의 출력 채널 수입니다.

conv_kernel_sizes (`list[int]`, *선택 사항*) : 각 refinement conv 레이어의 커널 크기. `conv_out_channels`가 설정되어 있고 이 값이 `None`인 경우 `[1, ...]`로 자동 입력됩니다. `conv_out_channels`와 동일한 길이를 가져야 합니다.

conv_kernel_size (`int`, 기본값 1) : `conv_kernel_sizes`가 설정되지 않은 경우 conv 레이어의 기본 커널 크기입니다.

scale_conv_out_channels (`list[int]`, *선택 사항*) : 초점 거리 스케일을 예측하는 데 사용되는 스트라이드 2 컨볼루션 레이어의 출력 채널 수입니다. `None`(기본값)인 경우 스케일 브랜치가 생성되지 않습니다.

scale_conv_kernel_sizes (`list[int]`, *선택 사항*) : 각 scale conv 레이어의 커널 크기. `scale_conv_out_channels`가 설정되어 있고 이 값이 `None`인 경우 `[1, ...]`로 자동 입력됩니다. `scale_conv_out_channels`와 동일한 길이를 가져야 합니다.

scale_conv_kernel_size (`int`, 기본값 1) : `scale_conv_kernel_sizes`가 설정되지 않은 경우 scale conv 레이어의 기본 커널 크기입니다.

scale_final_input_size (`int`, *선택 사항*) : scale MLP에 전달되는 평탄화된 특징 크기. `None`(기본값)인 경우, 상위 [Sapiens2Config](/docs/transformers/v5.23.0/ko/model_doc/sapiens2#transformers.Sapiens2Config)의 `image_size`와 `patch_size`에서 자동으로 추론됩니다.

scale_final_hidden_sizes (`list[int]`, *선택 사항*) : 평탄화된 스케일 특징을 스칼라 스케일 출력으로 매핑하는 MLP의 은닉층 크기입니다. `None`(기본값)인 경우 스케일 분기가 생성되지 않습니다.

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

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

## Sapiens2ImageProcessor[[transformers.Sapiens2ImageProcessor]]

#### transformers.Sapiens2ImageProcessor[[transformers.Sapiens2ImageProcessor]]

```python
transformers.Sapiens2ImageProcessor(**kwargs: *<class 'transformers.models.sapiens2.image_processing_sapiens2.Sapiens2ImageProcessorKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sapiens2/image_processing_sapiens2.py#L407)

**매개변수:**

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' : 1024, 'width': 768}`): 모델에 입력되는 최대 차원을 설명합니다.

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*, 기본값 `2`) : 이미지를 리사이즈할 때 사용할 리샘플링 필터입니다. 이는 `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*, *선택 사항*, 기본값 `False`) : 이미지를 패딩할지 여부입니다. 패딩은 배치 내 가장 큰 크기로 수행하거나 이미지마다 고정된 정사각형 크기로 수행합니다. 정확한 패딩 전략은 모델에 따라 달라집니다.

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로 대체됩니다.

keypoint_heatmap_downscale_factor (`int`, *kwargs*, *선택 사항*, 기본값 4) : 모델 입력 크기에 대한 목표 히트맵 크기의 다운스케일 팩터입니다.

keypoint_heatmap_sigma (`float`, *kwargs*, *선택 사항*, 기본값 6.0) : 히트맵 생성에 사용되는 2D 가우시안 분포의 표준편차(sigma)입니다.

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

#### preprocess[[transformers.Sapiens2ImageProcessor.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, boxes: list[list[list[float]]] | None = None, keypoints: list[list[list[list[float]]]] | None = None, **kwargs: *<class 'transformers.models.sapiens2.image_processing_sapiens2.Sapiens2ImageProcessorKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sapiens2/image_processing_sapiens2.py#L430)

**매개변수:**

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`, *선택 사항*) : 전처리할 분할 맵.

boxes (`list[list[list[float]]]` 또는 `np.ndarray`, *선택 사항*) : 각 이미지의 바운딩 박스 목록 또는 배열입니다. 각 박스는 COCO 형식의 바운딩 박스 좌표(top_left_x, top_left_y, width, height)를 나타내는 4개의 float로 구성된 목록이어야 합니다. 값이 제공되면 전체 이미지를 리사이즈하는 대신 각 인물 크롭이 모델 입력 크기로 아핀 변환됩니다.

keypoints (`list[list[list[list[float]]]]`, *선택 사항*) : 각 이미지의 각 사람에 대한 키포인트 목록. 예상 형식은 COCO 스타일의 `[x, y, visibility]`입니다. `x`와 `y` 값은 절대 이미지 픽셀 좌표로 예상됩니다. 형식은 `[images -> persons -> keypoints -> [x, y, visibility]]`입니다. 자세 추정 미세 조정 시 ground-truth 히트맵과 가시성 가중치를 생성하는 데 사용됩니다.

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로 대체됩니다.

keypoint_heatmap_downscale_factor (`int`, *kwargs*, *선택 사항*, 기본값 4) : 모델 입력 크기에 대한 목표 히트맵 크기의 다운스케일 팩터입니다.

keypoint_heatmap_sigma (`float`, *kwargs*, *선택 사항*, 기본값 6.0) : 히트맵 생성에 사용되는 2D 가우시안 분포의 표준편차(sigma)입니다.

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

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

#### post_process_image_matting[[transformers.Sapiens2ImageProcessor.post_process_image_matting]]

```python
post_process_image_matting(outputs, target_sizes: transformers.utils.generic.TensorType | list[tuple[int, int]] | None = None, backgrounds: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sapiens2/image_processing_sapiens2.py#L891)

**매개변수:**

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

target_sizes (`torch.Tensor` 또는 길이가 `batch_size`인 `list[tuple[int, int]]`, *선택 사항*) : 각 예측에 대해 요청하는 최종 `(height, width)`. 이차 보간(bilinear interpolation)으로 리사이즈됩니다. 설정되지 않으면 예측 결과가 모델 출력 해상도로 반환됩니다.

backgrounds (`ImageInput`, *선택*) : 합성할 배경 이미지입니다. 단일 이미지(배치의 모든 항목에 적용) 또는 배치 항목당 하나의 이미지로 구성된 이미지 목록일 수 있습니다. PIL 이미지, numpy 배열, 또는 모든 dtype의 torch 텐서를 지원합니다. 정수 타입(예: uint8)은 자동으로 `[0, 1]`로 스케일링됩니다. 값이 제공되면, 각 결과 딕셔너리에 합성된 이미지를 `[0, 255]` 범위의 uint8 텐서로 포함하는 `"composite"` 키가 추가됩니다.

**반환값:** `list[dict]`이며 길이는 `batch_size`입니다. 각 dict에는

- `"alpha"` (`torch.Tensor`, shape `(1, height, width)`): `[0, 1]` 범위의 alpha 값.
- `"foreground"` (`torch.Tensor`, shape `(3, height, width)`): `[0, 1]` 범위의 pre-multiplied RGB.
- `"composite"` (`torch.Tensor`, shape `(3, height, width)` 또는 `None`): `backgrounds` 위에 foreground가 합성된 `[0, 255]` 범위의 uint8 텐서; `backgrounds`가 제공되지 않으면 `None`.

[Sapiens2ForImageMatting](/docs/transformers/v5.23.0/ko/model_doc/sapiens2#transformers.Sapiens2ForImageMatting)의 출력을 알파 매트와 포그라운드 맵으로 변환합니다.

#### post_process_normal_estimation[[transformers.Sapiens2ImageProcessor.post_process_normal_estimation]]

```python
post_process_normal_estimation(outputs, source_sizes: transformers.utils.generic.TensorType | list[tuple[int, int]] | None = None, target_sizes: transformers.utils.generic.TensorType | list[tuple[int, int]] | None = None, do_remove_padding: bool | None = None)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sapiens2/image_processing_sapiens2.py#L818)

**매개변수:**

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

source_sizes (`torch.Tensor` 또는 길이가 `batch_size`인 `list[tuple[int, int]]`, *선택 사항*) : 전처리 이전 각 이미지의 원래 `(height, width)`. 제공되면 전처리 과정에서 추가된 패딩이 제거되고 예측 결과가 원래 이미지 크기로 다시 조정됩니다(`target_sizes`가 최종 크기를 재정의하지 않는 한).

target_sizes (`torch.Tensor` 또는 길이가 `batch_size`인 `list[tuple[int, int]]`, *선택 사항*) : 각 예측에 대해 요청하는 최종 `(height, width)`입니다. 지정된 경우, `source_sizes` 대신 리사이즈 대상으로 사용됩니다. L2 정규화 이후에 이선형 보간으로 리사이즈됩니다.

do_remove_padding (`bool`, *선택 사항*) : 리사이즈 전에 전처리 과정에서 추가된 제로 패딩을 잘라낼지 여부입니다. `source_sizes`가 제공되면 기본값은 `True`, 그렇지 않으면 `False`입니다.

**반환값:**

`batch_size` 길이의 `list[dict[str, torch.Tensor]]`. 각 dict에는 `"normals"` 키가 있으며, 이는 채널당 `[-1, 1]` 범위의 L2 정규화 단위 벡터(XYZ 표면 법선)를 포함하는 `(3, height, width)` 형태의 텐서로 매핑됩니다.

[Sapiens2ForNormalEstimation](/docs/transformers/v5.23.0/ko/model_doc/sapiens2#transformers.Sapiens2ForNormalEstimation)의 출력을 L2 정규화된 표면 법선 맵으로 변환합니다.

#### post_process_pointmap_estimation[[transformers.Sapiens2ImageProcessor.post_process_pointmap_estimation]]

```python
post_process_pointmap_estimation(outputs, source_sizes: transformers.utils.generic.TensorType | list[tuple[int, int]] | None = None, target_sizes: transformers.utils.generic.TensorType | list[tuple[int, int]] | None = None, do_remove_padding: bool | None = None)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sapiens2/image_processing_sapiens2.py#L854)

**매개변수:**

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

source_sizes (`torch.Tensor` 또는 길이가 `batch_size`인 `list[tuple[int, int]]`, *선택 사항*) : 전처리 이전 각 이미지의 원래 `(height, width)`. 제공되면 전처리 과정에서 추가된 패딩이 제거되고 예측 결과가 원래 이미지 크기로 다시 조정됩니다(`target_sizes`가 최종 크기를 재정의하지 않는 한).

target_sizes (`torch.Tensor` 또는 길이가 `batch_size`인 `list[tuple[int, int]]`, *선택 사항*) : 각 예측에 대해 요청하는 최종 `(height, width)`. `source_sizes`를 재조정(resize) 대상으로 덮어씁니다.

do_remove_padding (`bool`, *선택 사항*) : 리사이즈 전에 전처리 과정에서 추가된 제로 패딩을 잘라낼지 여부입니다. `source_sizes`가 제공되면 기본값은 `True`, 그렇지 않으면 `False`입니다.

**반환값:**

`batch_size` 길이의 `list[dict[str, torch.Tensor]]`입니다. 각 dict에는 `"pointmap"` 키가 있으며, 이는 정규화된 카메라 공간에서 픽셀별 3D XYZ 좌표를 포함하는 `(3, height, width)` 형태의 텐서에 매핑됩니다. 필요에 따라 `outputs.scales`로 나누어 미터 단위 좌표로 변환할 수 있습니다.

[Sapiens2ForPointmapEstimation](/docs/transformers/v5.23.0/ko/model_doc/sapiens2#transformers.Sapiens2ForPointmapEstimation)의 출력을 이미지 공간의 pointmap 텐서로 변환합니다.

#### post_process_pose_estimation[[transformers.Sapiens2ImageProcessor.post_process_pose_estimation]]

```python
post_process_pose_estimation(outputs, boxes: list[list[list[float]]], outputs_flipped = None, kernel_size: int = 11, threshold: float | None = None, source_sizes: transformers.utils.generic.TensorType | list[tuple[int, int]] | None = None, target_sizes: transformers.utils.generic.TensorType | list[tuple[int, int]] | None = None)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sapiens2/image_processing_sapiens2.py#L676)

**매개변수:**

outputs (`Sapiens2PoseEstimatorOutput`) : 모델의 원시 출력. `outputs.heatmaps`의 shape은 `(N_total, num_keypoints, heatmap_height, heatmap_width)`여야 하며, 여기서 `N_total = sum(len(b) for b in boxes)`입니다.

boxes (`list[list[list[float]]]` 또는 `np.ndarray`) : 절대 픽셀 좌표로 각 이미지의 바운딩 박스를 나타내는 리스트 또는 배열입니다. 각 박스는 COCO 형식의 바운딩 박스 좌표(top_left_x, top_left_y, width, height)를 나타내는 4개의 float로 구성된 리스트여야 합니다. `preprocess`에 전달된 `boxes` 인수와 일치해야 합니다.

outputs_flipped (`Sapiens2PoseEstimatorOutput`, *선택 사항*) : 수평으로 뒤집힌 입력에 대해 모델을 실행한 결과입니다. 제공되면, 정확도를 높이기 위해 키포인트 추출 전에 `outputs`와 히트맵을 평균화합니다: `avg_heatmaps = (outputs.heatmaps + outputs_flipped.heatmaps) / 2`.

kernel_size (`int`, *선택 사항*, 기본값 11) : UDP Dark Pose 정제에 사용되는 가우시안 블러의 커널 크기입니다.

threshold (`float`, *선택 사항*) : 점수 임계값. 이 값 이하의 점수를 가진 키포인트는 결과 사전에서 필터링됩니다.

source_sizes (`torch.Tensor` 또는 길이가 `batch_size`인 `list[tuple[int, int]]`, *선택 사항*) : 픽셀 단위로 각 이미지의 원래 `(height, width)`. `target_sizes`가 제공될 때 필수이며, 키포인트와 바운딩 박스를 스케일링하기 위한 소스 좌표 공간으로 사용됩니다.

target_sizes (`torch.Tensor` 또는 길이가 `batch_size`인 `list[tuple[int, int]]`, *선택 사항*) : 각 이미지에 대한 원하는 출력 `(height, width)` 좌표 공간. `source_sizes`와 함께 제공되면, 키포인트 좌표와 바운딩 박스가 소스 공간에서 대상 공간으로 스케일링됩니다.

**반환값:** `list[list[dict]]`

Outer 리스트는 이미지, inner 리스트는 인물에 대한 반복입니다. 각 dict에는 다음이 포함됩니다:
- `keypoints` (`torch.Tensor`, shape `(num_keypoints, 2)`): 소스 이미지 공간의 절대 x/y 좌표이며, `target_sizes`가 제공된 경우 대상 공간의 좌표입니다.
- `scores` (`torch.Tensor`, shape `(num_keypoints,)`): 각 keypoint의 신뢰도.
- `labels` (`torch.LongTensor`, shape `(num_keypoints,)`): keypoint 인덱스.
- `bbox` (`torch.Tensor`, shape `(4,)`): 절대 좌표 (x_min, y_min, x_max, y_max) 형식의 바운딩 박스이며, `keypoints`와 동일한 좌표 공간에 있습니다.

[Sapiens2ForPoseEstimation](/docs/transformers/v5.23.0/ko/model_doc/sapiens2#transformers.Sapiens2ForPoseEstimation)의 출력을 이미지 공간의 키포인트 예측으로 변환합니다.

#### post_process_semantic_segmentation[[transformers.Sapiens2ImageProcessor.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/v5.23.0/src/transformers/models/sapiens2/image_processing_sapiens2.py#L610)

**매개변수:**

outputs ([Sapiens2ForSemanticSegmentation](/docs/transformers/v5.23.0/ko/model_doc/sapiens2#transformers.Sapiens2ForSemanticSegmentation)) : 모델의 원시 출력

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`가 지정된 경우)에 해당합니다.

[Sapiens2ForSemanticSegmentation](/docs/transformers/v5.23.0/ko/model_doc/sapiens2#transformers.Sapiens2ForSemanticSegmentation)의 출력을 의미 분할 맵으로 변환합니다.

## Sapiens2Model[[transformers.Sapiens2Model]]

#### transformers.Sapiens2Model[[transformers.Sapiens2Model]]

```python
transformers.Sapiens2Model(config: Sapiens2Config)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sapiens2/modeling_sapiens2.py#L867)

**매개변수:**

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

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

이 모델은 [PreTrainedModel](/docs/transformers/v5.23.0/ko/main_classes/model#transformers.PreTrainedModel)에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대해서는 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법과 동작에 관한 모든 사항은 PyTorch 문서를 참조하세요.

#### forward[[transformers.Sapiens2Model.forward]]

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

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sapiens2/modeling_sapiens2.py#L880)

**매개변수:**

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

bool_masked_pos (`torch.BoolTensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : Boolean 마스크 위치. 어떤 패치가 마스킹되었는지(1), 그렇지 않은지(0)를 나타냅니다. 사전 학습에만 관련이 있습니다.

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

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

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

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

- **last_hidden_state** (`torch.Tensor`, shape `(batch_size, sequence_length, hidden_size)`) -- 모델의 마지막 레이어 출력에서 생성된 hidden-state 시퀀스입니다.
- **pooler_output** (`torch.Tensor`, shape `(batch_size, hidden_size)`) -- 시퀀스의 첫 번째 토큰(분류 토큰)의 마지막 레이어 hidden-state입니다. 보조 사전학습 작업을 위해 사용되는 레이어들을 통해 추가 처리된 값입니다. 예를 들어 BERT 계열 모델의 경우, 선형 레이어와 tanh 활성화 함수를 통해 처리된 분류 토큰을 반환합니다. 선형 레이어의 가중치는 사전학습 단계에서 다음 문장 예측(분류) 목적 함수를 통해 학습됩니다.
- **hidden_states** (`tuple(torch.Tensor)`, *선택 사항*, `output_hidden_states=True`가 전달되었거나 `config.output_hidden_states=True`인 경우 반환됨) -- `torch.Tensor`의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 형태는 `(batch_size, sequence_length, hidden_size)`입니다.

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

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

예:

```python
>>> from transformers import AutoImageProcessor, AutoModel
>>> from transformers.image_utils import load_image
>>> import torch

>>> image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-pretrain-0.4b")
>>> model = AutoModel.from_pretrained("facebook/sapiens2-pretrain-0.4b")

>>> inputs = image_processor(images=image, return_tensors="pt")
>>> with torch.inference_mode():
...     outputs = model(**inputs)

>>> cls_token = outputs.pooler_output
>>> cls_token.shape
torch.Size([1, 1024])
```

## Sapiens2Backbone[[transformers.Sapiens2Backbone]]

#### transformers.Sapiens2Backbone[[transformers.Sapiens2Backbone]]

```python
transformers.Sapiens2Backbone(config: Sapiens2Config)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sapiens2/modeling_sapiens2.py#L929)

**매개변수:**

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

Sapiens2 백본.

이 모델은 [PreTrainedModel](/docs/transformers/v5.23.0/ko/main_classes/model#transformers.PreTrainedModel)에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대해서는 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법과 동작에 관한 모든 사항은 PyTorch 문서를 참조하세요.

#### forward[[transformers.Sapiens2Backbone.forward]]

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

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sapiens2/modeling_sapiens2.py#L942)

**매개변수:**

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

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

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

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

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

- **feature_maps** (`tuple(torch.Tensor)`, shape `(batch_size, num_channels, height, width)`) -- 각 단계의 feature maps.
- **hidden_states** (`tuple(torch.Tensor)`, *선택*, `output_hidden_states=True`가 전달되거나 `config.output_hidden_states=True`인 경우 반환) -- 백본에 따라 shape가 `(batch_size, sequence_length, hidden_size)` 또는 `(batch_size, num_channels, height, width)`인 `torch.Tensor` 튜플 (임베딩 출력 1개 + 각 레이어 출력 1개)

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

  self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치입니다.
- **cls_tokens** (`tuple(torch.Tensor)`, *선택 사항*) -- 각 선택된 feature stage의 CLS token으로, 각 shape은 `(batch_size, hidden_size)`입니다. `config.return_class_token=True`일 때만 반환됩니다.

예:

```python
>>> from transformers import AutoBackbone, AutoImageProcessor
>>> from transformers.image_utils import load_image
>>> import torch

>>> image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-pretrain-0.4b")
>>> model = AutoBackbone.from_pretrained("facebook/sapiens2-pretrain-0.4b")

>>> inputs = image_processor(images=image, return_tensors="pt")
>>> with torch.inference_mode():
...     outputs = model(**inputs, return_class_token=True)

>>> outputs.feature_maps[0].shape
torch.Size([1, 1024, 64, 48])
>>> outputs.cls_tokens[0].shape
torch.Size([1, 1024])
```

## Sapiens2ForImageMatting[[transformers.Sapiens2ForImageMatting]]

#### transformers.Sapiens2ForImageMatting[[transformers.Sapiens2ForImageMatting]]

```python
transformers.Sapiens2ForImageMatting(config: Sapiens2Config)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sapiens2/modeling_sapiens2.py#L1365)

**매개변수:**

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

matting head가 위에 있는 Sapiens2 모델 (pre-multiplied RGB foreground와 alpha matte를 예측하는 PixelShuffle 기반 decoder).

이 모델은 [PreTrainedModel](/docs/transformers/v5.23.0/ko/main_classes/model#transformers.PreTrainedModel)에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대해서는 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법과 동작에 관한 모든 사항은 PyTorch 문서를 참조하세요.

#### forward[[transformers.Sapiens2ForImageMatting.forward]]

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

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sapiens2/modeling_sapiens2.py#L1372)

**매개변수:**

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

labels (`torch.Tensor`, shape `(batch_size, 4, height, width)`, *선택 사항*) : 손실을 계산하기 위한 ground-truth matting target입니다.

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

`Sapiens2ImageMattingOutput` 또는 `torch.Tensor`의 튜플(`return_dict=False`가 전달되거나 `config.return_dict=False`인 경우). 구성([Sapiens2Config](/docs/transformers/v5.23.0/ko/model_doc/sapiens2#transformers.Sapiens2Config)) 및 입력에 따라 다양한 요소를 포함합니다.

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

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

- **loss** (`torch.Tensor`, shape `(1,)`, *선택 사항*, `labels`이 제공될 때 반환됨) -- 손실.
- **alphas** (`torch.Tensor`, shape `(batch_size, 1, height, width)`) -- 추정된 alpha 값.
- **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`인 경우 반환됨) -- 각 레이어마다 하나씩 포함된 `torch.Tensor`의 튜플로, 모양은 `(batch_size, num_heads, sequence_length, sequence_length)`입니다.

  self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치입니다.
- **foregrounds** (`torch.Tensor`, shape `(batch_size, 3, height, width)`) -- `[0, 1]` 범위의 사전 곱셈(pre-multiplied) RGB foreground 예측값 (sigmoid 활성화 적용).

예:

```python
>>> from transformers import AutoImageProcessor, AutoModel
>>> from transformers.image_utils import load_image
>>> import torch

>>> image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-matting-1b")
>>> model = AutoModel.from_pretrained("facebook/sapiens2-matting-1b")

>>> inputs = image_processor(image, return_tensors="pt")
>>> with torch.inference_mode():
...     outputs = model(**inputs)

>>> outputs.alphas.shape
torch.Size([1, 1, 1024, 768])
>>> outputs.foregrounds.shape
torch.Size([1, 3, 1024, 768])
```

## Sapiens2ForNormalEstimation[[transformers.Sapiens2ForNormalEstimation]]

#### transformers.Sapiens2ForNormalEstimation[[transformers.Sapiens2ForNormalEstimation]]

```python
transformers.Sapiens2ForNormalEstimation(config: Sapiens2Config)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sapiens2/modeling_sapiens2.py#L1215)

**매개변수:**

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

정상 추정 헤드가 위에 있는 Sapiens2 모델(표면 정상 맵을 예측하는 PixelShuffle 기반 디코더).

이 모델은 [PreTrainedModel](/docs/transformers/v5.23.0/ko/main_classes/model#transformers.PreTrainedModel)에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대해서는 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법과 동작에 관한 모든 사항은 PyTorch 문서를 참조하세요.

#### forward[[transformers.Sapiens2ForNormalEstimation.forward]]

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

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sapiens2/modeling_sapiens2.py#L1223)

**매개변수:**

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

labels (`torch.Tensor`, shape `(batch_size, num_labels, height, width)`, *선택 사항*) : 손실을 계산하기 위한 ground-truth surface normal maps입니다.

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

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

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

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

- **loss** (`torch.Tensor`, shape `(1,)`, *선택 사항*, `labels`이 제공될 때 반환됨) -- 정규 추정 손실.
- **normals** (`torch.Tensor`, shape `(batch_size, num_labels, height, width)`) -- 모델이 출력한 원본 노멀 맵 예측값(정규화되지 않음).
- **hidden_states** (`tuple(torch.Tensor)`, *선택 사항*, `output_hidden_states=True`가 전달되었거나 `config.output_hidden_states=True`인 경우 반환됨) -- `torch.Tensor`의 튜플(임베딩 출력 1개 + 각 단계의 출력 1개)로, 모양은 `(batch_size, sequence_length, hidden_size)`입니다. 각 레이어 출력에서의 모델 히든 스테이트와 초기 임베딩 출력을 포함합니다.
- **attentions** (`tuple(torch.Tensor)`, *선택 사항*, `output_attentions=True`가 전달되거나 `config.output_attentions=True`인 경우 반환됨) -- `torch.Tensor`의 튜플(레이어당 하나)로, 모양은 `(batch_size, num_heads, sequence_length, sequence_length)`입니다. 어텐션 softmax 이후의 어텐션 가중치입니다.

예:

```python
>>> from transformers import AutoImageProcessor, AutoModel
>>> from transformers.image_utils import load_image
>>> import torch

>>> image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-normal-0.4b")
>>> model = AutoModel.from_pretrained("facebook/sapiens2-normal-0.4b")

>>> inputs = image_processor(image, return_tensors="pt")
>>> with torch.inference_mode():
...     outputs = model(**inputs)

>>> outputs.normals.shape
torch.Size([1, 3, 1024, 768])
```

## Sapiens2ForPointmapEstimation[[transformers.Sapiens2ForPointmapEstimation]]

#### transformers.Sapiens2ForPointmapEstimation[[transformers.Sapiens2ForPointmapEstimation]]

```python
transformers.Sapiens2ForPointmapEstimation(config: Sapiens2Config)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sapiens2/modeling_sapiens2.py#L1287)

**매개변수:**

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

점맵 헤드(픽셀당 3D XYZ 좌표를 예측하는 PixelShuffle 기반 디코더와 초점 길이 정규화를 위한 선택적 스케일 브랜치)가 위에 있는 Sapiens2 모델입니다.

이 모델은 [PreTrainedModel](/docs/transformers/v5.23.0/ko/main_classes/model#transformers.PreTrainedModel)에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대해서는 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법과 동작에 관한 모든 사항은 PyTorch 문서를 참조하세요.

#### forward[[transformers.Sapiens2ForPointmapEstimation.forward]]

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

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sapiens2/modeling_sapiens2.py#L1299)

**매개변수:**

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

labels (`torch.Tensor`, shape `(batch_size, 3, height, width)`, *선택 사항*) : 손실을 계산하기 위한 ground-truth pointmap입니다.

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

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

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

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

- **loss** (`torch.Tensor`, shape `(1,)`, *선택 사항*, `labels`가 제공될 때 반환됨) -- Pointmap 추정 손실.
- **pointmaps** (`torch.Tensor`, shape `(batch_size, 3, height, width)`) -- 정규화된 카메라 공간에서의 픽셀별 3D XYZ 좌표 예측값.
- **scales** (`torch.Tensor`, shape `(batch_size, 1)`, *선택 사항*) -- 표준 초점 거리 / 실제 초점 거리 비율. 스케일 브랜치가 구성되지 않은 경우 `None`.
- **hidden_states** (`tuple(torch.Tensor)`, *선택 사항*, `output_hidden_states=True`가 전달되었거나 `config.output_hidden_states=True`인 경우 반환됨) -- `torch.Tensor`의 튜플(임베딩 출력 1개 + 각 단계의 출력 1개)로, 모양은 `(batch_size, sequence_length, hidden_size)`입니다. 각 레이어 출력에서의 모델 히든 스테이트와 초기 임베딩 출력을 포함합니다.
- **attentions** (`tuple(torch.Tensor)`, *선택 사항*, `output_attentions=True`가 전달되거나 `config.output_attentions=True`인 경우 반환됨) -- `torch.Tensor`의 튜플(레이어당 하나)로, 모양은 `(batch_size, num_heads, sequence_length, sequence_length)`입니다. 어텐션 softmax 이후의 어텐션 가중치입니다.

예:

```python
>>> from transformers import AutoImageProcessor, AutoModel
>>> from transformers.image_utils import load_image
>>> import torch

>>> image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-pointmap-0.4b")
>>> model = AutoModel.from_pretrained("facebook/sapiens2-pointmap-0.4b")

>>> inputs = image_processor(image, return_tensors="pt")
>>> with torch.inference_mode():
...     outputs = model(**inputs)

>>> outputs.pointmaps.shape
torch.Size([1, 3, 1024, 768])
```

## Sapiens2ForPoseEstimation[[transformers.Sapiens2ForPoseEstimation]]

#### transformers.Sapiens2ForPoseEstimation[[transformers.Sapiens2ForPoseEstimation]]

```python
transformers.Sapiens2ForPoseEstimation(config: Sapiens2Config)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sapiens2/modeling_sapiens2.py#L1132)

**매개변수:**

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

pose estimation 헤드가 위에 있는 Sapiens2 모델(숨겨진 상태 출력 위에 있는 heatmap 예측기 세트).

이 모델은 [PreTrainedModel](/docs/transformers/v5.23.0/ko/main_classes/model#transformers.PreTrainedModel)에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대해서는 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법과 동작에 관한 모든 사항은 PyTorch 문서를 참조하세요.

#### forward[[transformers.Sapiens2ForPoseEstimation.forward]]

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

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sapiens2/modeling_sapiens2.py#L1140)

**매개변수:**

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

flip_pairs (`torch.Tensor`, shape `(num_pairs, 2)`, *선택 사항*) : 거울 대칭으로 짝을 이루는 키포인트 쌍(예: 왼쪽 귀 -- 오른쪽 귀)입니다. 테스트 시점 플립 증강에 사용됩니다. 이 값이 제공되면 모델은 `pixel_values`에 수평으로 플립된 이미지가 포함되어 있다고 가정하고, 원래 방향을 복원하기 위해 출력 히트맵에 `flip_back`을 호출합니다.

labels (`torch.Tensor`, shape `(batch_size, num_keypoints, height, width)`, *선택 사항*) : 손실을 계산하기 위한 Heatmap ground truth입니다.

label_weights (`torch.Tensor`, shape `(batch_size, num_labels, 1, 1)` 또는 `(batch_size, num_labels, height, width)`, *선택 사항*) : 각 keypoint에 대한 가시성 가중치. `labels`의 shape으로 broadcast 가능해야 합니다.

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

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

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

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

- **loss** (`torch.Tensor`, shape `(1,)`, *선택 사항*, `labels`이 제공될 때 반환됨) -- 자세 추정 손실.
- **heatmaps** (`torch.Tensor`, shape `(batch_size, num_keypoints, height, width)`) -- 모델이 예측한 히트맵.
- **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`인 경우 반환) -- 각 레이어마다 하나씩 포함된 `torch.Tensor` 튜플로, shape는 `(batch_size, num_heads, sequence_length, sequence_length)`입니다.

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

예:

```python
>>> from transformers import AutoImageProcessor, AutoModel
>>> from transformers.image_utils import load_image
>>> import torch

>>> image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-pose-0.4b")
>>> model = AutoModel.from_pretrained("facebook/sapiens2-pose-0.4b")

>>> boxes = [[[270.8, 0.6, 294.1, 379.5]]]
>>> inputs = image_processor(image, boxes=boxes, return_tensors="pt")
>>> with torch.inference_mode():
...     outputs = model(**inputs)

>>> outputs.heatmaps.shape
torch.Size([1, 308, 256, 192])
```

## Sapiens2ForSemanticSegmentation[[transformers.Sapiens2ForSemanticSegmentation]]

#### transformers.Sapiens2ForSemanticSegmentation[[transformers.Sapiens2ForSemanticSegmentation]]

```python
transformers.Sapiens2ForSemanticSegmentation(config: Sapiens2Config)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sapiens2/modeling_sapiens2.py#L1019)

**매개변수:**

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

semantic segmentation 헤드가 위에 있는 Sapiens2 모델, 예: ADE20K, CityScapes.

이 모델은 [PreTrainedModel](/docs/transformers/v5.23.0/ko/main_classes/model#transformers.PreTrainedModel)에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대해서는 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법과 동작에 관한 모든 사항은 PyTorch 문서를 참조하세요.

#### forward[[transformers.Sapiens2ForSemanticSegmentation.forward]]

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

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sapiens2/modeling_sapiens2.py#L1027)

**매개변수:**

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

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

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

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

[Sapiens2ForSemanticSegmentation](/docs/transformers/v5.23.0/ko/model_doc/sapiens2#transformers.Sapiens2ForSemanticSegmentation)의 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`인 경우 반환) -- 각 레이어당 하나씩, shape가 `(batch_size, num_heads, patch_size, sequence_length)`인 `torch.Tensor`의 튜플.

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

예:

```python
>>> from transformers import AutoImageProcessor, AutoModel
>>> from transformers.image_utils import load_image
>>> import torch

>>> image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-seg-0.4b")
>>> model = AutoModel.from_pretrained("facebook/sapiens2-seg-0.4b")

>>> inputs = image_processor(image, return_tensors="pt")
>>> with torch.inference_mode():
...     outputs = model(**inputs)

>>> outputs.logits.shape
torch.Size([1, 29, 1024, 768])
```

