# Pixio

[Pixio]()는 [ViT](./vit)를 특징 추출기로 사용하여 깊이 추정, 의미론적 분할, 피드포워드 3D 재구성, 로봇공학, 이미지 분류와 같은 다양한 다운스트림 작업을 수행하는 비전 파운데이션 모델입니다. Masked Autoencoder(MAE) 사전 학습 프레임워크를 기반으로 하며, 다음과 같은 4가지 최소하지만 핵심적인 업데이트가 적용되었습니다: 1) 더 깊은 디코더, 2) 더 큰 마스킹 그라놀라리티, 3) 더 많은 클래스 토큰, 4) 웹 규모로 큐레이션된 학습 데이터.

모든 원본 Pixio 체크포인트는 [Pixio]() 컬렉션에서 찾을 수 있습니다.

아래 예제는 [AutoModel](/docs/transformers/main/ko/model_doc/auto#transformers.AutoModel) 클래스를 사용하여 이미지 임베딩을 얻는 방법을 보여줍니다.

```python
import requests
from PIL import Image

from transformers import AutoImageProcessor, AutoModel

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

processor = AutoImageProcessor.from_pretrained("facebook/pixio-vith16")
model = AutoModel.from_pretrained("facebook/pixio-vith16", device_map="auto")

inputs = processor(images=image, return_tensors="pt").to(model.device)
outputs = model(**inputs)
features_norm = outputs.last_hidden_state # class tokens + patch tokens after last LayerNorm
features = outputs.hidden_states[-1] # class tokens + patch tokens before last LayerNorm
```

## The input is a single word "Notes".

참고

- 아래 예제는 출력 텐서를 다음과 같이 분할하는 방법을 보여줍니다.
  - 이미지 전체에 대한 전역 임베딩의 집합으로, 일반적으로 `CLS` 토큰이라고 불리며 분류 및 검색에 유용합니다. 평균을 내는 것(권장) 또는 채널 차원을 따라 연결하는 것 중 하나를 선택할 수 있습니다.
  - 입력 이미지의 각 `16x16` 패치에 해당하는 로컬 임베딩의 집합으로, 깊이 추정 및 의미론적 분할과 같은 밀집(dense) 작업에 유용합니다.

  ```py
  from transformers import AutoImageProcessor, AutoModel
  from PIL import Image
  import requests

  url = 'http://images.cocodataset.org/val2017/000000039769.jpg'
  image = Image.open(requests.get(url, stream=True).raw)
  print(image.height, image.width)  # [480, 640]

  processor = AutoImageProcessor.from_pretrained('facebook/pixio-vith16')
  model = AutoModel.from_pretrained('facebook/pixio-vith16', device_map="auto")
  patch_size = model.config.patch_size

  inputs = processor(images=image, return_tensors="pt").to(model.device)
  print(inputs.pixel_values.shape)  # [1, 3, 256, 256]
  batch_size, rgb, img_height, img_width = inputs.pixel_values.shape
  num_patches_height, num_patches_width = img_height // patch_size, img_width // patch_size
  num_patches_flat = num_patches_height * num_patches_width

  outputs = model(**inputs)
  last_hidden_states = outputs.last_hidden_state
  print(last_hidden_states.shape)  # [1, 8 + 256, 1280]
  assert last_hidden_states.shape == (batch_size, model.config.n_cls_tokens + num_patches_flat, model.config.hidden_size)

  cls_tokens = last_hidden_states[:, :model.config.n_cls_tokens, :]
  patch_features = last_hidden_states[:, model.config.n_cls_tokens:, :].unflatten(1, (num_patches_height, num_patches_width))
  ```

- [torch.compile](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html)를 사용하여 추론 속도를 높입니다.

  ```py
  import torch
  from transformers import AutoImageProcessor, AutoModel
  from PIL import Image
  import requests

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

  processor = AutoImageProcessor.from_pretrained('facebook/pixio-vith16')
  model = AutoModel.from_pretrained('facebook/pixio-vith16', device_map="auto")

  compiled_model = torch.compile(model)

  inputs = processor(images=image, return_tensors="pt").to(model.device)
  outputs = compiled_model(**inputs)
  last_hidden_states = outputs.last_hidden_state
  ```

## PixioConfig[[transformers.PixioConfig]]

#### transformers.PixioConfig[[transformers.PixioConfig]]

```python
transformers.PixioConfig(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 = 1280, num_hidden_layers: int = 32, num_attention_heads: int = 16, mlp_ratio: int = 4, hidden_act: str = 'gelu', hidden_dropout_prob: float | int = 0.0, attention_probs_dropout_prob: float | int = 0.0, initializer_range: float = 0.02, layer_norm_eps: float = 1e-06, image_size: int | list[int] | tuple[int, int] = 256, patch_size: int | list[int] | tuple[int, int] = 16, num_channels: int = 3, qkv_bias: bool = True, drop_path_rate: float | int = 0.0, _out_features: list[str] | None = None, _out_indices: list[int] | None = None, apply_layernorm: bool = True, reshape_hidden_states: bool = True, n_cls_tokens: int = 8)
```

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

**매개변수:**

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

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

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

mlp_ratio (`int`, *선택 사항*, 기본값 `4`) : MLP 숨겨진 차원과 임베딩 차원의 비율입니다.

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

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

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

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

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

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

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

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

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

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

apply_layernorm (`bool`, *선택 사항*, 기본값 `True`) : 모델이 백본으로 사용될 경우, 피처 맵에 레이어 정규화를 적용할지 여부입니다.

reshape_hidden_states (`bool`, *선택 사항*, 기본값 `True`) : 모델이 백본으로 사용될 경우, feature maps를 `(batch_size, hidden_size, height, width)` 형태의 4D 텐서로 reshape할지 여부입니다. `False`인 경우, feature maps는 `(batch_size, seq_len, hidden_size)` 형태의 3D 텐서가 됩니다.

n_cls_tokens (`int`, *선택 사항*, 기본값 8) : Transformer 인코더의 클래스 토큰 수.

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

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 PixioConfig, PixioModel

>>> # Initializing a Pixio pixio-huge style configuration
>>> configuration = PixioConfig()

>>> # Initializing a model (with random weights) from the pixio-huge style configuration
>>> model = PixioModel(configuration)

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

## PixioModel[[transformers.PixioModel]]

#### transformers.PixioModel[[transformers.PixioModel]]

```python
transformers.PixioModel(config: PixioConfig)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/pixio/modeling_pixio.py#L322)

**매개변수:**

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

특정 헤드가 위에 없는 상태의 Pixio Model이 원시 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.PixioModel.forward]]

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

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/pixio/modeling_pixio.py#L334)

**매개변수:**

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

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

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

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

[PixioModel](/docs/transformers/main/ko/model_doc/pixio#transformers.PixioModel)의 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
```

## PixioBackbone[[transformers.PixioBackbone]]

#### transformers.PixioBackbone[[transformers.PixioBackbone]]

```python
transformers.PixioBackbone(config: PixioConfig)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/pixio/modeling_pixio.py#L369)

**매개변수:**

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

DETR, MaskFormer와 같은 프레임워크와 함께 사용할 Pixio backbone입니다.

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

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

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/pixio/modeling_pixio.py#L379)

**매개변수:**

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

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

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

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

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

예:

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

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

>>> processor = AutoImageProcessor.from_pretrained("facebook/pixio-huge")
>>> model = AutoBackbone.from_pretrained(
...     "facebook/pixio-huge", out_features=["stage7", "stage15", "stage23", "stage31"]
... )

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

>>> outputs = model(**inputs)
>>> feature_maps = outputs.feature_maps
>>> list(feature_maps[-1].shape)
[1, 1280, 16, 16]
```

