Transformers documentation

OWL-ViT

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2022-05-12 在 HF papers 上发布,并于 2022-07-22 贡献至 Hugging Face Transformers。

OWL-ViT

概述

OWL-ViT(Vision Transformer for Open-World Localization 的缩写)由 Matthias Minderer、Alexey Gritsenko、Austin Stone、Maxim Neumann、Dirk Weissenborn、Alexey Dosovitskiy、Aravindh Mahendran、Anurag Arnab、Mostafa Dehghani、Zhuoran Shen、Xiao Wang、Xiaohua Zhai、Thomas Kipf 和 Neil Houlsby 在 Simple Open-Vocabulary Object Detection with Vision Transformers 中提出。OWL-ViT 是一个在多种(图像,文本)配对数据上训练的开集目标检测网络。它可以使用一个或多个文本查询来检索图像,并检测文本中描述的目标对象。

该论文的摘要如下:

将简单架构与大规模预训练相结合,已在图像分类任务上带来了巨大的性能提升。而在目标检测领域,预训练和规模化方法尚不够成熟,尤其是在长尾分布和开放词汇场景下,训练数据相对匮乏。本文提出了一种将图文模型迁移至开放词汇目标检测的强效方案。我们采用经过最小化修改的标准 Vision Transformer 架构,结合对比式图文预训练以及端到端的检测微调。我们对这一设置中规模化特性的分析表明,增加图像级预训练数据和模型规模,均能在下游检测任务上带来一致的性能提升。我们提供了实现零样本文本条件目标检测和单样本图像条件目标检测所需的高性能适配策略与正则化方法。相关代码和模型已在 GitHub 上开源。

drawing OWL-ViT architecture. Taken from the original paper.

该模型由 adirik 贡献。原始代码可在此处找到。

使用技巧

OWL-ViT 是一个零样本文本条件目标检测模型。OWL-ViT 使用 CLIP 作为其多模态骨干网络,其中采用类 ViT 的 Transformer 提取视觉特征,并采用因果语言模型提取文本特征。为了将 CLIP 用于检测,OWL-ViT 移除了视觉模型最后的 token 池化层,并为每个 Transformer 输出 token 附加了一个轻量级的分类和边界框头。通过将固定的分类层权重替换为从文本模型获得的类别名称嵌入,实现了开放词汇分类。作者首先从头训练 CLIP,然后使用二部匹配损失在标准检测数据集上对分类头和边界框头进行端到端微调。每张图像可以使用一个或多个文本查询来执行零样本文本条件目标检测。

OwlViTImageProcessor 可用于对图像进行缩放(或重新缩放)和归一化,以适配模型,而 CLIPTokenizer 用于对文本进行编码。OwlViTProcessor 将 OwlViTImageProcessor 和 CLIPTokenizer 封装为单一实例,从而同时完成文本编码和图像预处理。以下示例展示了如何使用 OwlViTProcessor 和 OwlViTForObjectDetection 执行目标检测。

import requests
from PIL import Image
import torch

from transformers import OwlViTProcessor, OwlViTForObjectDetection

processor = OwlViTProcessor.from_pretrained("google/owlvit-base-patch32")
model = OwlViTForObjectDetection.from_pretrained("google/owlvit-base-patch32", device_map="auto")

url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)
text_labels = [["a photo of a cat", "a photo of a dog"]]
inputs = processor(text=text_labels, images=image, return_tensors="pt").to(model.device)
outputs = model(**inputs)

# Target image sizes (height, width) to rescale box predictions [batch_size, 2]
target_sizes = torch.tensor([(image.height, image.width)])
# Convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
results = processor.post_process_grounded_object_detection(
    outputs=outputs, target_sizes=target_sizes, threshold=0.1, text_labels=text_labels
)
# Retrieve predictions for the first image for the corresponding text queries
result = results[0]
boxes, scores, text_labels = result["boxes"], result["scores"], result["text_labels"]
for box, score, text_label in zip(boxes, scores, text_labels):
    box = [round(i, 2) for i in box.tolist()]
    print(f"Detected {text_label} with confidence {round(score.item(), 3)} at location {box}")
Detected a photo of a cat with confidence 0.707 at location [324.97, 20.44, 640.58, 373.29]
Detected a photo of a cat with confidence 0.717 at location [1.46, 55.26, 315.55, 472.17]

资源

使用 OWL-ViT 进行零样本和单样本(图像引导)目标检测的演示笔记本可在此处找到。

OwlViTConfig

class transformers.OwlViTConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsedtype: 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 = Nonereturn_dict: bool = Truetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonevision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneprojection_dim: int = 512logit_scale_init_value: float = 2.6592initializer_factor: float = 1.0 )

参数

  • return_dict (bool,可选,默认为 True) — 是否返回 ModelOutput(dataclass)而不是普通的元组。
  • text_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 文本骨干网络的配置对象或字典。
  • vision_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 视觉骨干网络的配置对象或字典。
  • projection_dim (int,可选,默认为 512) — 文本和视觉投影层的维度。
  • logit_scale_init_value (float,可选,默认为 2.6592) — logit_scale 参数的初始值。
  • initializer_factor (float,可选,默认为 1.0) — 用于初始化所有权重矩阵的系数(应保持为 1,内部用于初始化测试)。

这是用于存储 OwlViTModel 配置的类。它根据指定的参数实例化 Owlvit 模型,并定义模型架构。使用默认值实例化配置将得到与 google/owlvit-base-patch16 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

OwlViTTextConfig

class transformers.OwlViTTextConfig

< >

( 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 = Nonevocab_size: int = 49408hidden_size: int = 512intermediate_size: int = 2048num_hidden_layers: int = 12num_attention_heads: int = 8max_position_embeddings: int = 16hidden_act: str = 'quick_gelu'layer_norm_eps: float = 1e-05attention_dropout: float | int = 0.0initializer_range: float = 0.02initializer_factor: float = 1.0pad_token_id: int | None = 0bos_token_id: int | None = 49406eos_token_id: int | list[int] | None = 49407 )

参数

  • vocab_size (int,可选,默认为 49408) — 模型的词汇表大小。定义了 input_ids 可以表示的不同 token 数量。
  • hidden_size (int,可选,默认为 512) — 隐藏表示的维度。
  • intermediate_size (int,可选,默认为 2048) — MLP 表示的维度。
  • num_hidden_layers (int, 可选, 默认为 12) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 8) — Transformer 解码器中每个注意力层的注意力头数量。
  • max_position_embeddings (int,可选,默认为 16) — 该模型可能使用的最大序列长度。
  • hidden_act (str,可选,默认为 quick_gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • layer_norm_eps (float,可选,默认为 1e-05) — 层归一化层所使用的 epsilon 值。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • initializer_factor (float,可选,默认为 1.0) — 用于初始化所有权重矩阵的系数(应保持为 1,内部用于初始化测试)。
  • pad_token_id (int, 可选,默认为 0) — 词表中用于填充的 token id。
  • bos_token_id (int,可选,默认为 49406) — 词汇表中用于表示流起始的 Token ID。
  • eos_token_id (Union[int, list[int]],可选,默认为 49407) — 词汇表中用于表示流结束(end-of-stream)的 token id。

这是用于存储 OwlViTModel 配置的类。它根据指定的参数实例化 Owlvit 模型,并定义模型架构。使用默认值实例化配置将得到与 google/owlvit-base-patch16 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

示例:

>>> from transformers import OwlViTTextConfig, OwlViTTextModel

>>> # Initializing a OwlViTTextModel with google/owlvit-base-patch32 style configuration
>>> configuration = OwlViTTextConfig()

>>> # Initializing a OwlViTTextConfig from the google/owlvit-base-patch32 style configuration
>>> model = OwlViTTextModel(configuration)

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

OwlViTVisionConfig

class transformers.OwlViTVisionConfig

< >

( 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 = 768intermediate_size: int = 3072num_hidden_layers: int = 12num_attention_heads: int = 12num_channels: int = 3image_size: int | list[int] | tuple[int, int] = 768patch_size: int | list[int] | tuple[int, int] = 32hidden_act: str = 'quick_gelu'layer_norm_eps: float = 1e-05attention_dropout: float | int = 0.0initializer_range: float = 0.02initializer_factor: float = 1.0 )

参数

  • hidden_size (int,可选,默认为 768) — 隐藏表示的维度。
  • intermediate_size (int,可选,默认为 3072) — MLP 表示的维度。
  • num_hidden_layers (int, 可选, 默认为 12) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 12) — Transformer 解码器中每个注意力层的注意力头数量。
  • num_channels (int,可选,默认为 3) — 输入通道的数量。
  • image_size (Union[int, list[int], tuple[int, int]],可选,默认为 768) — 每张图片的尺寸(分辨率)。
  • patch_size (Union[int, list[int], tuple[int, int]],可选,默认为 32) — 每个 patch 的大小(分辨率)。
  • hidden_act (str,可选,默认为 quick_gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • layer_norm_eps (float,可选,默认为 1e-05) — 层归一化层所使用的 epsilon 值。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • initializer_factor (float,可选,默认为 1.0) — 用于初始化所有权重矩阵的系数(应保持为 1,内部用于初始化测试)。

这是用于存储 OwlViTModel 配置的类。它根据指定的参数实例化 Owlvit 模型,并定义模型架构。使用默认值实例化配置将得到与 google/owlvit-base-patch16 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

示例:

>>> from transformers import OwlViTVisionConfig, OwlViTVisionModel

>>> # Initializing a OwlViTVisionModel with google/owlvit-base-patch32 style configuration
>>> configuration = OwlViTVisionConfig()

>>> # Initializing a OwlViTVisionModel model from the google/owlvit-base-patch32 style configuration
>>> model = OwlViTVisionModel(configuration)

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

OwlViTImageProcessor

class transformers.OwlViTImageProcessor

< >

( **kwargs: *<class 'transformers.processing_utils.ImagesKwargs'> )

参数

  • do_convert_rgb (bool,kwargs,可选,默认为 True) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选,默认为 True) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None],kwargs,默认为 {'height' -- 768, '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' -- 768, 'width': 768}): 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为 3) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举 PILImageResampling 中的一个值。仅当 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.48145466, 0.4578275, 0.40821073]) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, 可选,默认为 [0.26862954, 0.26130258, 0.27577711]) — 用于归一化的图像标准差。仅当 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,可选,默认为 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,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。

构建 OwlViTImageProcessor 图像处理器。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]*argsimage_like_kwargs: dict[str, typing.Any] | None = None**kwargs: *<class 'transformers.processing_utils.ImagesKwargs'> ) → ~image_processing_base.BatchFeature

参数

  • 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。
  • image_like_kwargs (dict[str, Any], 可选) — 用于额外图像类输入的开发者标志,这些输入也将被预处理。仅在以关键字参数传递输入不起作用时使用此标志。例如,preprocess(images, masks=masks) 是首选方式,但对于某些模型会导致参数优先级问题。在这种情况下,可以改用 preprocess(images, image_like_inputs={"masks": masks})。
  • 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 为整数时,是否在调整大小时默认使用正方形图像。
  • 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 中的一个值。仅当 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,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。

返回值

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

预处理一张图像或一批图像。

OwlViTImageProcessorPil

class transformers.OwlViTImageProcessorPil

< >

( **kwargs: *<class 'transformers.processing_utils.ImagesKwargs'> )

参数

  • do_convert_rgb (bool,kwargs,可选,默认为 True) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选,默认为 True) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None],kwargs,默认为 {'height' -- 768, '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' -- 768, 'width': 768}): 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为 3) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举 PILImageResampling 中的一个值。仅当 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.48145466, 0.4578275, 0.40821073]) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, 可选,默认为 [0.26862954, 0.26130258, 0.27577711]) — 用于归一化的图像标准差。仅当 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,可选,默认为 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,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。

构建 OwlViTImageProcessor 图像处理器。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]*argsimage_like_kwargs: dict[str, typing.Any] | None = None**kwargs: *<class 'transformers.processing_utils.ImagesKwargs'> ) → ~image_processing_base.BatchFeature

参数

  • 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。
  • image_like_kwargs (dict[str, Any], 可选) — 用于额外图像类输入的开发者标志,这些输入也将被预处理。仅在以关键字参数传递输入不起作用时使用此标志。例如,preprocess(images, masks=masks) 是首选方式,但对于某些模型会导致参数优先级问题。在这种情况下,可以改用 preprocess(images, image_like_inputs={"masks": masks})。
  • 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 为整数时,是否在调整大小时默认使用正方形图像。
  • 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 中的一个值。仅当 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,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。

返回值

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

预处理一张图像或一批图像。

post_process_object_detection

< >

( outputs: OwlViTObjectDetectionOutputthreshold: float = 0.1target_sizes: transformers.utils.generic.TensorType | list[tuple] | None = None ) → list[Dict]

参数

  • outputs (OwlViTObjectDetectionOutput) — 模型的原始输出。
  • threshold (float,可选,默认为 0.1) — 用于保留目标检测预测结果的分数阈值。
  • target_sizes (torch.Tensor 或 list[tuple[int, int]],可选) — 形状为 (batch_size, 2) 的张量,或包含目标尺寸 (height, width) 的元组列表(tuple[int, int]),表示批次中每张图片的目标大小。如果未设置,预测结果将不会被调整大小。

返回值

list[Dict]

一个字典列表,每个字典包含以下键:

  • “scores”:图像上每个预测框的置信度分数。
  • “labels”:模型在图像上预测的类别索引。
  • “boxes”:图像边界框,格式为 (top_left_x, top_left_y, bottom_right_x, bottom_right_y)。

将 OwlViTForObjectDetection 的原始输出转换为 (top_left_x, top_left_y, bottom_right_x, bottom_right_y) 格式的最终边界框。

post_process_image_guided_detection

< >

( outputsthreshold = 0.0nms_threshold = 0.3target_sizes = None ) → list[Dict]

参数

  • outputs (OwlViTImageGuidedObjectDetectionOutput) — 模型的原始输出。
  • threshold (float,可选,默认为 0.0) — 用于过滤预测框的最低置信度阈值。
  • nms_threshold (float,可选,默认值为 0.3) — 用于对重叠框执行非极大值抑制的 IoU 阈值。
  • target_sizes (torch.Tensor, 可选) — 形状为 (batch_size, 2) 的张量,其中每个元素表示批次中对应图像的 (height, width)。如果设置,预测的归一化边界框将重新缩放到目标尺寸。如果保持为 None,预测结果将不会进行反归一化。

返回值

list[Dict]

一个字典列表,每个字典包含模型在批次中为一张图像预测的分数、标签和边界框。由于 OwlViTForObjectDetection.image_guided_detection 执行单样本目标检测,所有标签均被设置为 None。

将 OwlViTForObjectDetection.image_guided_detection() 的输出转换为 COCO api 所期望的格式。

OwlViTProcessor

class transformers.OwlViTProcessor

< >

( image_processor = Nonetokenizer = None**kwargs )

参数

  • image_processor (OwlViTImageProcessor) — 图像处理器是必需的输入。
  • tokenizer (CLIPTokenizer) — 分词器是必需的输入。

构造一个 OwlViTProcessor,它将图像处理器和分词器封装为单个处理器。

OwlViTProcessor 提供了 OwlViTImageProcessor 和 CLIPTokenizer 的所有功能。有关更多信息,请参阅 ~OwlViTImageProcessor 和 ~CLIPTokenizer。

__call__

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Nonetext: str | list[str] | list[list[str]] = Nonequery_images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None**kwargs: *<class 'transformers.processing_utils.ProcessingKwargs'> ) → BatchFeature

参数

  • 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。
  • text (Union[str, list[str], list[list[str]]],可选) — 要编码的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果传入预分词输入,请设置 is_split_into_words=True,以避免与批量输入产生歧义。
  • query_images (ImageInput,可选) — 用于图像引导目标检测的查询图像。提供时,这些图像将作为视觉查询,用于在主 images 中查找相似的目标。查询图像会覆盖任何文本提示,模型将执行图像到图像的匹配,而非文本到图像的匹配。
  • return_mm_token_type_ids (bool, kwargs) — 是否返回多模态 token 类型 id,用于指示多模态占位符 token 的位置。
  • return_text_replacement_offsets (bool, kwargs) — 是否返回每个多模态占位符及其替换内容的字符偏移量。
  • return_tensors (str 或 TensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:
    • 'pt':返回 PyTorch torch.Tensor 对象。
    • 'np':返回 NumPy np.ndarray 对象。
  • **kwargs (ProcessingKwargs,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。

返回值

BatchFeature

一个包含以下字段的 BatchFeature:

  • input_ids — 要输入模型的 token id 列表。当 text 不为 None 时返回。
  • attention_mask — 一个索引列表,指定模型应关注哪些 token(当 return_attention_mask=True,或当 “attention_mask” 位于 self.model_input_names 中且 text 不为 None 时)。
  • pixel_values — 输入模型的像素值。当 images 不为 None 时返回。
  • query_pixel_values — 输入模型的查询图像的像素值。当 query_images 不为 None 时返回。

post_process_grounded_object_detection

< >

( outputs: OwlViTObjectDetectionOutputthreshold: float = 0.1target_sizes: transformers.utils.generic.TensorType | list[tuple] | None = Nonetext_labels: list[list[str]] | None = None ) → list[Dict]

参数

  • outputs (OwlViTObjectDetectionOutput) — 模型的原始输出。
  • threshold (float,可选,默认为 0.1) — 用于保留目标检测预测结果的分数阈值。
  • target_sizes (torch.Tensor 或 list[tuple[int, int]],可选) — 形状为 (batch_size, 2) 的张量,或包含目标尺寸 (height, width) 的元组列表(tuple[int, int]),表示批次中每张图片的目标大小。如果未设置,预测结果将不会被调整大小。
  • text_labels (list[list[str]],可选) — 批处理中每张图片的文本标签列表。如果未设置,输出中的“text_labels”将被设置为 None。

返回值

list[Dict]

一个字典列表,每个字典包含以下键:

  • “scores”:图像上每个预测框的置信度分数。
  • “labels”:模型在图像上预测的类别索引。
  • “boxes”:图像边界框,格式为 (top_left_x, top_left_y, bottom_right_x, bottom_right_y)。
  • “text_labels”:图像上每个预测边界框对应的文本标签。

将 OwlViTForObjectDetection 的原始输出转换为 (top_left_x, top_left_y, bottom_right_x, bottom_right_y) 格式的最终边界框。

post_process_image_guided_detection

< >

( outputs: OwlViTImageGuidedObjectDetectionOutputthreshold: float = 0.0nms_threshold: float = 0.3target_sizes: transformers.utils.generic.TensorType | list[tuple] | None = None ) → list[Dict]

参数

  • outputs (OwlViTImageGuidedObjectDetectionOutput) — 模型的原始输出。
  • threshold (float,可选,默认为 0.0) — 用于过滤预测框的最低置信度阈值。
  • nms_threshold (float,可选,默认值为 0.3) — 用于对重叠框执行非极大值抑制的 IoU 阈值。
  • target_sizes (torch.Tensor, 可选) — 形状为 (batch_size, 2) 的张量,其中每个元素表示批次中对应图像的 (height, width)。如果设置,预测的归一化边界框将重新缩放到目标尺寸。如果保持为 None,预测结果将不会进行反归一化。

返回值

list[Dict]

一个字典列表,每个字典包含以下键:

  • “scores”:图像上每个预测框的置信度分数。
  • “boxes”:图像边界框,格式为 (top_left_x, top_left_y, bottom_right_x, bottom_right_y)。
  • “labels”:设置为 None。

将 OwlViTForObjectDetection.image_guided_detection() 的输出转换为 COCO api 所期望的格式。

OwlViTModel

class transformers.OwlViTModel

< >

( config: OwlViTConfig )

参数

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

未添加任何特定头部的裸 Owlvit 模型,直接输出原始隐藏状态。

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

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonereturn_loss: bool | None = Noneinterpolate_pos_encoding: bool = Falsereturn_base_image_embeds: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → OwlViTOutput or tuple(torch.Tensor)

参数

  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。

    什么是输入 ID?

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

    什么是注意力掩码?

  • return_loss (bool, 可选) — 是否返回对比损失。
  • interpolate_pos_encoding (bool,可选,默认为 False) — 是否对预训练的位置编码进行插值。
  • return_base_image_embeds (bool,可选) — 是否返回基础图像嵌入。

返回值

OwlViTOutput 或 tuple(torch.Tensor)

OwlViTOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(OwlViTConfig)和输入。

OwlViTModel 的 forward 方法会重写 __call__ 特殊方法。

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

  • loss (torch.Tensor,形状为 (1,),可选,当 return_loss 为 True 时返回) — 用于图像-文本相似度的对比损失。
  • logits_per_image(形状为 (image_batch_size, text_batch_size) 的 torch.Tensor)— image_embeds 与 text_embeds 之间的缩放点积分数。这表示图像-文本相似度分数。
  • logits_per_text(形状为 (text_batch_size, image_batch_size) 的 torch.Tensor)— text_embeds 与 image_embeds 之间的缩放点积分数。这表示文本-图像相似度分数。
  • text_embeds(形状为 (batch_size * num_max_text_queries, output_dim 的 torch.Tensor)—— 通过对 OwlViTTextModel 的池化输出应用投影层获得的文本嵌入。
  • image_embeds (torch.Tensor,形状为 (batch_size, output_dim) — 通过对 OwlViTVisionModel 的池化输出应用投影层得到的图像嵌入。
  • text_model_output (~modeling_outputs.BaseModelOutputWithPooling,可选) — OwlViTTextModel 的输出。
  • vision_model_output(~modeling_outputs.BaseModelOutputWithPooling,可选)— OwlViTVisionModel 的输出。

示例:

>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from transformers import AutoProcessor, OwlViTModel

>>> model = OwlViTModel.from_pretrained("google/owlvit-base-patch32")
>>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch32")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))
>>> inputs = processor(text=[["a photo of a cat", "a photo of a dog"]], images=image, return_tensors="pt")
>>> outputs = model(**inputs)
>>> logits_per_image = outputs.logits_per_image  # this is the image-text similarity score
>>> probs = logits_per_image.softmax(dim=1)  # we can take the softmax to get the label probabilities

get_text_features

< >

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

参数

  • input_ids(形状为 (batch_size * num_max_text_queries, sequence_length) 的 torch.LongTensor)— 输入序列中各个 token 在词汇表中的索引。可以使用 AutoTokenizer 获取这些索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。什么是输入 ID?
  • 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),其包含的元素取决于配置(OwlViTConfig)和输入。

  • 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 之后的权重,用于在自注意力头中计算加权平均值。

示例:

>>> import torch
>>> from transformers import AutoProcessor, OwlViTModel

>>> model = OwlViTModel.from_pretrained("google/owlvit-base-patch32")
>>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch32")
>>> inputs = processor(
...     text=[["a photo of a cat", "a photo of a dog"], ["photo of a astranaut"]], return_tensors="pt"
... )
>>> with torch.inference_mode():
...     text_features = model.get_text_features(**inputs)

get_image_features

< >

( pixel_values: Tensorinterpolate_pos_encoding: bool = False**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

参数

  • pixel_values(形状为 (batch_size, num_channels, image_size, image_size) 的 torch.Tensor)— 与输入图像对应的张量。可以使用 OwlViTImageProcessor 获取像素值。有关详细信息,请参阅 OwlViTImageProcessor.call()(OwlViTProcessor 使用 OwlViTImageProcessor 来处理图像)。
  • interpolate_pos_encoding (bool,可选,默认为 False) — 是否对预训练的位置编码进行插值。

返回值

BaseModelOutputWithPooling 或 tuple(torch.Tensor)

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

  • 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 之后的权重,用于在自注意力头中计算加权平均值。

示例:

>>> import torch
>>> from transformers.image_utils import load_image
>>> from transformers import AutoProcessor, OwlViTModel

>>> model = OwlViTModel.from_pretrained("google/owlvit-base-patch32")
>>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch32")

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = load_image(url)

>>> inputs = processor(images=image, return_tensors="pt")
>>> with torch.inference_mode():
...     image_features = model.get_image_features(**inputs)

OwlViTTextModel

class transformers.OwlViTTextModel

< >

( config: OwlViTTextConfig )

forward

< >

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

参数

  • input_ids(形状为 (batch_size * num_max_text_queries, sequence_length) 的 torch.LongTensor)— 输入序列中各个 token 在词汇表中的索引。可以使用 AutoTokenizer 获取这些索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。什么是输入 ID?
  • 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),其包含的元素取决于配置(OwlViTConfig)和输入。

OwlViTTextModel 的 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 之后的权重,用于在自注意力头中计算加权平均值。

示例:

>>> from transformers import AutoProcessor, OwlViTTextModel

>>> model = OwlViTTextModel.from_pretrained("google/owlvit-base-patch32")
>>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch32")
>>> inputs = processor(
...     text=[["a photo of a cat", "a photo of a dog"], ["photo of a astranaut"]], return_tensors="pt"
... )
>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state
>>> pooled_output = outputs.pooler_output  # pooled (EOS token) states

OwlViTVisionModel

class transformers.OwlViTVisionModel

< >

( config: OwlViTVisionConfig )

forward

< >

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

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 OwlViTImageProcessor 获取像素值。有关详细信息,请参阅 OwlViTImageProcessor.call()(OwlViTProcessor 使用 OwlViTImageProcessor 来处理图像)。
  • interpolate_pos_encoding (bool,可选,默认为 False) — 是否对预训练的位置编码进行插值。

返回值

BaseModelOutputWithPooling 或 tuple(torch.Tensor)

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

OwlViTVisionModel 的 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 之后的权重,用于在自注意力头中计算加权平均值。

示例:

>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from transformers import AutoProcessor, OwlViTVisionModel

>>> model = OwlViTVisionModel.from_pretrained("google/owlvit-base-patch32")
>>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch32")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

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

>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state
>>> pooled_output = outputs.pooler_output  # pooled CLS states

OwlViTForObjectDetection

class transformers.OwlViTForObjectDetection

< >

( config: OwlViTConfig )

forward

< >

( input_ids: Tensorpixel_values: Tensorattention_mask: typing.Optional[torch.Tensor] = Noneinterpolate_pos_encoding: bool = False**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → OwlViTObjectDetectionOutput or tuple(torch.Tensor)

参数

  • input_ids(形状为 (batch_size * num_max_text_queries, sequence_length) 的 torch.LongTensor,可选) — 输入序列中各 token 在词汇表中的索引。可通过 AutoTokenizer 获取这些索引。详情请参见 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。什么是输入 ID?
  • pixel_values(形状为 (batch_size, num_channels, image_size, image_size) 的 torch.Tensor)— 与输入图像对应的张量。可以使用 OwlViTImageProcessor 获取像素值。有关详细信息,请参阅 OwlViTImageProcessor.call()(OwlViTProcessor 使用 OwlViTImageProcessor 来处理图像)。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • interpolate_pos_encoding (bool,可选,默认为 False) — 是否对预训练的位置编码进行插值。

返回值

OwlViTObjectDetectionOutput 或 tuple(torch.Tensor)

OwlViTObjectDetectionOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(OwlViTConfig)和输入。

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

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

  • loss (torch.Tensor,形状为 (1,),可选,在提供 labels 时返回)) — 总损失,是类别预测的负对数似然(交叉熵)与边界框损失的线性组合。后者定义为 L1 损失与广义尺度不变 IoU 损失的线性组合。
  • loss_dict (Dict,可选) — 包含各项单独损失的字典。适用于日志记录。
  • logits(形状为 (batch_size, num_patches, num_queries) 的 torch.Tensor)— 所有查询的分类 logits(包括无对象)。
  • pred_boxes(形状为 (batch_size, num_patches, 4) 的 torch.Tensor)— 所有查询的归一化框坐标,表示为 (center_x, center_y, width, height)。这些值在 [0, 1] 范围内归一化,相对于批次中每张图片的单独尺寸(忽略可能的填充)。您可以使用 post_process_object_detection() 来获取未归一化的边界框。
  • text_embeds(形状为 (batch_size, num_max_text_queries, output_dim 的 torch.Tensor)—— 通过对 OwlViTTextModel 的池化输出应用投影层获得的文本嵌入。
  • image_embeds (torch.Tensor,形状为 (batch_size, patch_size, patch_size, output_dim) — OwlViTVisionModel 的池化输出。OWL-ViT 将图像表示为一组图像块(image patches),并为每个图像块计算图像嵌入。
  • class_embeds (torch.Tensor,形状为 (batch_size, num_patches, hidden_size)) — 所有图像块的类别嵌入。OWL-ViT 将图像表示为一组图像块,其中图像块的总数为 (image_size / patch_size)**2。
  • text_model_output (~modeling_outputs.BaseModelOutputWithPooling,可选) — OwlViTTextModel 的输出。
  • vision_model_output(~modeling_outputs.BaseModelOutputWithPooling,可选)— OwlViTVisionModel 的输出。

示例:

>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from PIL import Image
>>> import torch

>>> from transformers import OwlViTProcessor, OwlViTForObjectDetection

>>> processor = OwlViTProcessor.from_pretrained("google/owlvit-base-patch32")
>>> model = OwlViTForObjectDetection.from_pretrained("google/owlvit-base-patch32")

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))
>>> text_labels = [["a photo of a cat", "a photo of a dog"]]
>>> inputs = processor(text=text_labels, images=image, return_tensors="pt")
>>> outputs = model(**inputs)

>>> # Target image sizes (height, width) to rescale box predictions [batch_size, 2]
>>> target_sizes = torch.tensor([(image.height, image.width)])
>>> # Convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
>>> results = processor.post_process_grounded_object_detection(
...     outputs=outputs, target_sizes=target_sizes, threshold=0.1, text_labels=text_labels
... )
>>> # Retrieve predictions for the first image for the corresponding text queries
>>> result = results[0]
>>> boxes, scores, text_labels = result["boxes"], result["scores"], result["text_labels"]
>>> for box, score, text_label in zip(boxes, scores, text_labels):
...     box = [round(i, 2) for i in box.tolist()]
...     print(f"Detected {text_label} with confidence {round(score.item(), 3)} at location {box}")
Detected a photo of a cat with confidence 0.707 at location [324.97, 20.44, 640.58, 373.29]
Detected a photo of a cat with confidence 0.717 at location [1.46, 55.26, 315.55, 472.17]

image_guided_detection

< >

( pixel_values: Tensorquery_pixel_values: typing.Optional[torch.Tensor] = Noneinterpolate_pos_encoding: bool = False**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → OwlViTImageGuidedObjectDetectionOutput or tuple(torch.Tensor)

参数

  • pixel_values(形状为 (batch_size, num_channels, image_size, image_size) 的 torch.Tensor)— 与输入图像对应的张量。可以使用 OwlViTImageProcessor 获取像素值。有关详细信息,请参阅 OwlViTImageProcessor.call()(OwlViTProcessor 使用 OwlViTImageProcessor 来处理图像)。
  • query_pixel_values (torch.Tensor,形状为 (batch_size, num_channels, height, width)) — 待检测查询图像的像素值。请为每个目标图像传入一张查询图像。
  • interpolate_pos_encoding (bool,可选,默认为 False) — 是否对预训练的位置编码进行插值。

返回值

OwlViTImageGuidedObjectDetectionOutput 或 tuple(torch.Tensor)

OwlViTImageGuidedObjectDetectionOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(OwlViTConfig)和输入。

  • logits(形状为 (batch_size, num_patches, num_queries) 的 torch.Tensor)— 所有查询的分类 logits(包括无对象)。
  • image_embeds (torch.Tensor,形状为 (batch_size, patch_size, patch_size, output_dim) — OwlViTVisionModel 的池化输出。OWL-ViT 将图像表示为一组图像块(image patches),并为每个图像块计算图像嵌入。
  • query_image_embeds (torch.Tensor,形状为 (batch_size, patch_size, patch_size, output_dim) — OwlViTVisionModel 的池化输出。OWL-ViT 将图像表示为一组图像块,并为每个图像块计算图像嵌入。
  • target_pred_boxes(形状为 (batch_size, num_patches, 4) 的 torch.Tensor)— 所有查询的归一化框坐标,表示为 (center_x, center_y, width, height)。这些值在 [0, 1] 范围内归一化,相对于批次中每个目标图像的尺寸(忽略可能的填充)。您可以使用 post_process_object_detection() 来获取未归一化的边界框。
  • query_pred_boxes(形状为 (batch_size, num_patches, 4) 的 torch.Tensor)— 所有查询的归一化边界框坐标,表示为 (center_x, center_y, width, height)。这些值在 [0, 1] 范围内归一化,相对于批次中每个查询图像各自的尺寸(忽略可能的填充)。您可以使用 post_process_object_detection() 来获取未归一化的边界框。
  • class_embeds (torch.Tensor,形状为 (batch_size, num_patches, hidden_size)) — 所有图像块的类别嵌入。OWL-ViT 将图像表示为一组图像块,其中图像块的总数为 (image_size / patch_size)**2。
  • text_model_output (~modeling_outputs.BaseModelOutputWithPooling,可选) — OwlViTTextModel 的输出。
  • vision_model_output(~modeling_outputs.BaseModelOutputWithPooling,可选)— OwlViTVisionModel 的输出。

示例:

>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from PIL import Image
>>> import torch
>>> from transformers import AutoProcessor, OwlViTForObjectDetection

>>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch16")
>>> model = OwlViTForObjectDetection.from_pretrained("google/owlvit-base-patch16")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))
>>> query_url = "http://images.cocodataset.org/val2017/000000001675.jpg"
>>> with httpx.stream("GET", query_url) as response:
...     query_image = Image.open(BytesIO(response.read()))
>>> inputs = processor(images=image, query_images=query_image, return_tensors="pt")
>>> with torch.no_grad():
...     outputs = model.image_guided_detection(**inputs)
>>> # Target image sizes (height, width) to rescale box predictions [batch_size, 2]
>>> target_sizes = torch.Tensor([image.size[::-1]])
>>> # Convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
>>> results = processor.post_process_image_guided_detection(
...     outputs=outputs, threshold=0.6, nms_threshold=0.3, target_sizes=target_sizes
... )
>>> i = 0  # Retrieve predictions for the first image
>>> boxes, scores = results[i]["boxes"], results[i]["scores"]
>>> for box, score in zip(boxes, scores):
...     box = [round(i, 2) for i in box.tolist()]
...     print(f"Detected similar object with confidence {round(score.item(), 3)} at location {box}")
Detected similar object with confidence 0.856 at location [10.94, 50.4, 315.8, 471.39]
Detected similar object with confidence 1.0 at location [334.84, 25.33, 636.16, 374.71]
Update on GitHub