Transformers documentation

Pixio

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.2).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

이 모델은 2025-12-17에 Hugging Face Transformers에 기여되었습니다. 이 모델은 발표 예정

FlashAttention SDPA

Pixio

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

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

아래 예제는 AutoModel 클래스를 사용하여 이미지 임베딩을 얻는 방법을 보여줍니다.

<hfoptions id="usage"> <hfoption id="AutoModel">
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) 작업에 유용합니다.
    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를 사용하여 추론 속도를 높입니다.

    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

class transformers.PixioConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 1280num_hidden_layers: int = 32num_attention_heads: int = 16mlp_ratio: int = 4hidden_act: str = 'gelu'hidden_dropout_prob: float | int = 0.0attention_probs_dropout_prob: float | int = 0.0initializer_range: float = 0.02layer_norm_eps: float = 1e-06image_size: int | list[int] | tuple[int, int] = 256patch_size: int | list[int] | tuple[int, int] = 16num_channels: int = 3qkv_bias: bool = Truedrop_path_rate: float | int = 0.0_out_features: list[str] | None = None_out_indices: list[int] | None = Noneapply_layernorm: bool = Truereshape_hidden_states: bool = Truen_cls_tokens: int = 8 )

매개변수

  • 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) — 임베딩, 인코더, 풀러의 모든 완전 연결 계층에 적용되는 드롭아웃 확률입니다.
  • 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) — 모델이 backbone으로 사용될 경우 feature map에 layer normalization을 적용할지 여부.
  • reshape_hidden_states (bool, 선택 사항, 기본값 True) — 모델이 backbone으로 사용될 때, feature maps를 (batch_size, hidden_size, height, width) 형태의 4D tensor로 reshape할지 여부입니다. False인 경우, feature maps는 (batch_size, seq_len, hidden_size) 형태의 3D tensor가 됩니다.
  • n_cls_tokens (int, 선택 사항, 기본값 8) — Transformer 인코더의 클래스 토큰 수입니다.

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

Configuration 객체는 PreTrainedConfig를 상속하며 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 PreTrainedConfig의 문서를 참고하세요.

예:

>>> 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

class transformers.PixioModel

< >

( config: PixioConfig )

매개변수

  • config (PixioConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 연관된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.

특정 헤드가 위에 없는 상태의 Pixio Model이 원시 hidden-states를 출력하는 형태입니다.

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

이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.

forward

< >

( pixel_values: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

매개변수

  • pixel_values (torch.Tensor, shape (batch_size, num_channels, image_size, image_size), 선택 사항) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 BitImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 BitImageProcessor.call()를 참조하세요 (processor_class는 이미지 처리에 BitImageProcessor를 사용합니다).
  • attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요? [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

    어텐션 마스크란 무엇인가요?

반환값

BaseModelOutputWithPooling 또는 tuple(torch.Tensor)

torch.Tensor의 튜플 또는 BaseModelOutputWithPooling입니다. 구성(PixioConfig)과 입력에 따라 다양한 요소를 포함하며, return_dict=False가 전달되었거나 config.return_dict=False인 경우에도 동일합니다.

PixioModel의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.

이 함수 내에서 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 가중치.

예:

PixioBackbone

class transformers.PixioBackbone

< >

( config: PixioConfig )

매개변수

  • config (PixioConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 연관된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.

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

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

이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.

forward

< >

( pixel_values: Tensorattention_mask: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BackboneOutput or tuple(torch.Tensor)

매개변수

  • pixel_values (torch.Tensor, shape (batch_size, num_channels, image_size, image_size)) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 BitImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 BitImageProcessor.call()를 참조하세요 (processor_class는 이미지 처리에 BitImageProcessor를 사용합니다).
  • attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요? [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

    어텐션 마스크란 무엇인가요?

반환값

BackboneOutput 또는 tuple(torch.Tensor)

BackboneOutput 또는 torch.Tensor의 튜플(return_dict=False가 전달되었거나 config.return_dict=False인 경우)로, 구성(PixioConfig)과 입력에 따라 다양한 요소를 포함합니다.

PixioBackbone의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.

이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신 Module 인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.

  • feature_maps (tuple(torch.Tensor), shape (batch_size, num_channels, height, width)) — 각 단계의 feature map입니다.

  • hidden_states (tuple(torch.Tensor), 선택 사항, output_hidden_states=True가 전달되었거나 config.output_hidden_states=True인 경우 반환됨) — 임베딩의 출력 하나와 각 레이어의 출력 하나씩을 포함하는 torch.Tensor의 튜플로, 백본에 따라 shape가 (batch_size, sequence_length, hidden_size) 또는 (batch_size, num_channels, height, width)입니다.

    각 단계의 출력에서 모델의 Hidden-states와 초기 임베딩 출력을 포함합니다.

  • attentions (tuple(torch.Tensor), 선택 사항, output_attentions=True가 전달되었거나 config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된 torch.Tensor의 튜플로, 모양은 (batch_size, num_heads, sequence_length, sequence_length)입니다. 백본이 attention을 사용하는 경우에만 적용됩니다.

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

예:

>>> 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]
Update on GitHub