Transformers 文档

Pixio

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

该模型于 2025-12-17 贡献给 Hugging Face Transformers。 该模型即将发布

FlashAttention SDPA

Pixio

Pixio 是一种视觉基础模型,它使用 ViT 作为特征提取器,用于深度估计、语义分割、前馈 3D 重建、机器人技术和图像分类等多种下游任务。它建立在掩码自编码器 (Masked Autoencoder, MAE) 预训练框架之上,并进行了四项微小但关键的更新:1) 更深的解码器,2) 更大的掩码粒度,3) 更多的分类 token (class tokens),以及 4) 网络规模的精选训练数据。

你可以在 Pixio 合集中找到所有原始的 Pixio 检查点 (checkpoints)。

下面的示例演示了如何使用 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 token,适用于分类和检索任务。你可以对它们进行平均(推荐),也可以沿通道维度进行拼接。
    • 一组局部嵌入,对应输入图像的每个 16x16 分块 (patch),适用于密集预测任务,如深度估计和语义分割。
    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 = None architectures: list[str] | None = None output_hidden_states: bool | None = False return_dict: bool | None = True dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = 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: typing.Optional[typing.Literal['regression', 'single_label_classification', 'multi_label_classification']] = 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 )

参数

  • 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 probability)。
  • attention_probs_dropout_prob (Union[float, int], 可选, 默认值为 0.0) — 注意力概率的丢弃率。
  • 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) — 是否为查询 (queries)、键 (keys) 和值 (values) 添加偏置。
  • drop_path_rate (Union[float, int], 可选, 默认值为 0.0) — 用于分块融合 (patch fusion) 的丢弃路径率 (drop path rate)。
  • 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 编码器中的分类 token 数量。

这是用于存储 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 模型,输出原始隐藏状态,顶部没有任何特定的头部 (head)。

该模型继承自 PreTrainedModel。请查看超类文档以了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头部等)。

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( pixel_values: torch.Tensor | None = None attention_mask: torch.Tensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) BaseModelOutputWithPoolingtuple(torch.FloatTensor)

参数

  • pixel_values (形状为 (batch_size, num_channels, image_size, image_size)torch.Tensor, 可选) — 对应输入图像的张量。像素值可以使用 BitImageProcessor 获取。有关详细信息,请参阅 BitImageProcessor.__call__() (processor_class 使用 BitImageProcessor 处理图像)。
  • attention_mask (形状为 (batch_size, sequence_length)torch.Tensor, 可选) — 用于避免对填充 token 索引执行注意力操作的掩码。掩码值在 [0, 1] 中选择:

    • 1 表示 未被掩码 的 token,
    • 0 表示 被掩码 的 token。

    什么是注意力掩码?

返回

BaseModelOutputWithPooling or tuple(torch.FloatTensor)

一个 BaseModelOutputWithPooling 或一个 torch.FloatTensor 元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),根据配置 (PixioConfig) 和输入包含不同的元素。

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

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

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

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

  • hidden_states (tuple(torch.FloatTensor), optional, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(一个用于嵌入层的输出,如果模型有嵌入层;+一个用于每个层的输出),形状为 (batch_size, sequence_length, hidden_size)

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

  • attentions (tuple(torch.FloatTensor), optional, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 的元组(每个层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

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

示例

PixioBackbone

class transformers.PixioBackbone

< >

( config: PixioConfig )

参数

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

Pixio 主干 (backbone),用于 DETR 和 MaskFormer 等框架。

该模型继承自 PreTrainedModel。请查看超类文档以了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头部等)。

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( pixel_values: Tensor attention_mask: torch.Tensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) BackboneOutputtuple(torch.FloatTensor)

参数

  • pixel_values (形状为 (batch_size, num_channels, image_size, image_size)torch.Tensor) — 对应输入图像的张量。像素值可以使用 BitImageProcessor 获取。有关详细信息,请参阅 BitImageProcessor.__call__() (processor_class 使用 BitImageProcessor 处理图像)。
  • attention_mask (形状为 (batch_size, sequence_length)torch.Tensor, 可选) — 用于避免对填充 token 索引执行注意力操作的掩码。掩码值在 [0, 1] 中选择:

    • 1 表示 未被掩码 的 token,
    • 0 表示 被掩码 的 token。

    什么是注意力掩码?

返回

BackboneOutputtuple(torch.FloatTensor)

一个 BackboneOutput 或一个 torch.FloatTensor 元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),根据配置 (PixioConfig) 和输入包含不同的元素。

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

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

  • feature_maps (tuple(torch.FloatTensor) of shape (batch_size, num_channels, height, width)) — 阶段的特征图。

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — torch.FloatTensor 元组(一个用于嵌入输出 + 每个层输出一个)的形状为 (batch_size, sequence_length, hidden_size)(batch_size, num_channels, height, width),具体取决于主干网络。

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

  • attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — torch.FloatTensor 元组(每个层一个)的形状为 (batch_size, num_heads, sequence_length, sequence_length)。仅当主干网络使用注意力时适用。

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

示例

>>> from transformers import AutoImageProcessor, AutoBackbone
>>> import torch
>>> from PIL import Image
>>> 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]
在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.