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.1).
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) 预训练框架构建,并进行了四项精简但关键的更新:1) 更深的解码器,2) 更大的掩码粒度,3) 更多的类别 token,以及 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

备注

  • 下面的示例展示了如何将输出张量拆分为:

    • 一组用于整张图像的全局嵌入,通常称为 CLS 标记, 适用于分类和检索任务。 您可以选择对它们求平均(推荐)或沿通道维度进行拼接。
    • 一组局部嵌入,输入图像的每个 16x16 图像块对应一个, 适用于深度估计和语义分割等密集任务。
    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 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 16) — Transformer 解码器中每个注意力层的注意力头数量。
  • 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) — 注意力概率的 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) — 每个 patch 的大小(分辨率)。
  • num_channels (int,可选,默认为 3) — 输入通道的数量。
  • qkv_bias (bool,可选,默认为 True) — 是否向查询、键和值添加偏置。
  • drop_path_rate (Union[float, int],可选,默认为 0.0) — 用于 patch fusion 的 drop path 比率。
  • apply_layernorm (bool,可选,默认为 True) — 当模型用作 backbone 时,是否对特征图应用层归一化。
  • reshape_hidden_states (bool,可选,默认为 True) — 当模型用作骨干网络时,是否将特征图重塑为形状为 (batch_size, hidden_size, height, width) 的 4D 张量。如果为 False,则特征图将是形状为 (batch_size, seq_len, hidden_size) 的 3D 张量。
  • n_cls_tokens (int,可选,默认值为 8) — Transformer 编码器中的类别标记数量。

这是用于存储 PixioModel 配置的类。它根据指定的参数实例化 Pixio 模型,并定义模型架构。使用默认值实例化配置,将得到与 facebook/pixio-huge 类似的配置。

配置对象继承自 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 模型,直接输出原始隐藏状态。

该模型继承自 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,形状为 (batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 BitImageProcessor 获取像素值。有关详细信息,请参阅 BitImageProcessor.call()(processor_class 使用 BitImageProcessor 处理图像)。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

返回值

BaseModelOutputWithPooling 或 tuple(torch.Tensor)

一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(PixioConfig)和输入。

PixioModel 的 forward 方法重写了 __call__ 特殊方法。

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

  • last_hidden_state(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor)— 模型最后一层输出的隐藏状态序列。

  • pooler_output (torch.Tensor,形状为 (batch_size, hidden_size)) — 序列中第一个 token(分类 token)的最后一层隐藏状态,经过用于辅助预训练任务的层进一步处理后得到。例如,对于 BERT 系列模型,这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重在预训练期间通过下一句预测(分类)目标进行训练。

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为 (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 之后的权重,用于在自注意力头中计算加权平均值。

示例:

PixioBackbone

class transformers.PixioBackbone

< >

( config: PixioConfig )

参数

  • config (PixioConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

Pixio 骨干网络,用于与 DETR 和 MaskFormer 等框架配合使用。

该模型继承自 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,形状为 (batch_size, num_channels, image_size, image_size)) — 对应于输入图像的张量。可以使用 BitImageProcessor 获取像素值。有关详细信息,请参阅 BitImageProcessor.call()(processor_class 使用 BitImageProcessor 处理图像)。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

返回值

BackboneOutput 或 tuple(torch.Tensor)

BackboneOutput 或 torch.Tensor 元组(如果传入 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(PixioConfig)和输入。

PixioBackbone 的 forward 方法重写了 __call__ 特殊方法。

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

  • feature_maps(形状为 (batch_size, num_channels, height, width) 的 tuple(torch.Tensor))— 各阶段的特征图。

  • hidden_states (tuple(torch.Tensor),可选,在传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(包含嵌入层的输出以及每一层的输出),形状为 (batch_size, sequence_length, hidden_size) 或 (batch_size, num_channels, height, width),具体取决于骨干网络。

    模型在每个阶段输出处的隐藏状态,以及初始嵌入输出。

  • attentions (tuple(torch.Tensor),可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。仅当主干网络使用注意力机制时适用。

    注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。

示例:

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