Transformers 文档

OmDet-Turbo

OmDet-Turbo

概述

OmDet-Turbo模型由Tiancheng Zhao、Peng Liu、Xuan He、Lu Zhang、Kyusong Lee在Real-time Transformer-based Open-Vocabulary Detection with Efficient Fusion Head中提出。OmDet-Turbo结合了RT-DETR的组件,并引入了一个快速的多模态融合模块,以实现实时开放词汇对象检测能力,同时保持高精度。该基础模型在COCO零样本上实现了高达100.2 FPS和53.4 AP的性能。

论文的摘要如下:

基于端到端变压器的检测器(DETRs)通过整合语言模态,在封闭集和开放词汇对象检测(OVD)任务中表现出色。然而,它们对计算资源的高需求阻碍了它们在实时对象检测(OD)场景中的实际应用。在本文中,我们仔细分析了OVDEval基准测试中两个领先模型OmDet和Grounding-DINO的局限性,并介绍了OmDet-Turbo。这种新型的基于变压器的实时OVD模型具有创新的高效融合头(EFH)模块,旨在缓解在OmDet和Grounding-DINO中观察到的瓶颈。值得注意的是,OmDet-Turbo-Base在应用TensorRT和语言缓存技术后,达到了每秒100.2帧(FPS)的速度。值得注意的是,在COCO和LVIS数据集的零样本场景中,OmDet-Turbo的性能几乎与当前最先进的监督模型相当。此外,它在ODinW和OVDEval上建立了新的最先进基准,分别达到了30.1的AP和26.86的NMS-AP。OmDet-Turbo在基准数据集上的卓越性能和优越的推理速度,突显了其在工业应用中的实用性,使其成为实时对象检测任务的一个引人注目的选择。

drawing OmDet-Turbo architecture overview. Taken from the original paper.

该模型由yonigozlan贡献。 原始代码可以在这里找到。

使用提示

与其他零样本目标检测模型(如Grounding DINO)相比,OmDet-Turbo的一个独特属性是解耦的类别和提示嵌入结构,允许缓存文本嵌入。这意味着模型需要类别和任务作为输入,其中类别是我们想要检测的对象列表,任务是用以指导开放词汇检测的接地文本。这种方法限制了开放词汇检测的范围,并使解码过程更快。

OmDetTurboProcessor 用于准备类别、任务和图像的三元组。任务输入是可选的,当未提供时,它将默认为 "Detect [class1], [class2], [class3], ..."。要处理模型的结果,可以使用 OmDetTurboProcessor 中的 post_process_grounded_object_detection。值得注意的是,该函数接受输入类别,因为与其他零样本目标检测模型不同,类别和任务嵌入的解耦意味着在后处理步骤中不需要对预测的类别嵌入进行解码,预测的类别可以直接与输入的类别匹配。

使用示例

单张图像推理

以下是如何加载模型并准备输入以在单张图像上执行零样本目标检测:

import requests
from PIL import Image

from transformers import AutoProcessor, OmDetTurboForObjectDetection

processor = AutoProcessor.from_pretrained("omlab/omdet-turbo-swin-tiny-hf")
model = OmDetTurboForObjectDetection.from_pretrained("omlab/omdet-turbo-swin-tiny-hf")

url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)
classes = ["cat", "remote"]
inputs = processor(image, text=classes, return_tensors="pt")

outputs = model(**inputs)

# convert outputs (bounding boxes and class logits)
results = processor.post_process_grounded_object_detection(
    outputs,
    classes=classes,
    target_sizes=[image.size[::-1]],
    score_threshold=0.3,
    nms_threshold=0.3,
)[0]
for score, class_name, box in zip(
    results["scores"], results["classes"], results["boxes"]
):
    box = [round(i, 1) for i in box.tolist()]
    print(
        f"Detected {class_name} with confidence "
        f"{round(score.item(), 2)} at location {box}"
    )

多图像推理

OmDet-Turbo 可以执行批量多图像推理,支持在同一批次中使用不同的文本提示和类别:

>>> import torch
>>> import requests
>>> from io import BytesIO
>>> from PIL import Image
>>> from transformers import AutoProcessor, OmDetTurboForObjectDetection

>>> processor = AutoProcessor.from_pretrained("omlab/omdet-turbo-swin-tiny-hf")
>>> model = OmDetTurboForObjectDetection.from_pretrained("omlab/omdet-turbo-swin-tiny-hf")

>>> url1 = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image1 = Image.open(BytesIO(requests.get(url1).content)).convert("RGB")
>>> classes1 = ["cat", "remote"]
>>> task1 = "Detect {}.".format(", ".join(classes1))

>>> url2 = "http://images.cocodataset.org/train2017/000000257813.jpg"
>>> image2 = Image.open(BytesIO(requests.get(url2).content)).convert("RGB")
>>> classes2 = ["boat"]
>>> task2 = "Detect everything that looks like a boat."

>>> url3 = "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"
>>> image3 = Image.open(BytesIO(requests.get(url3).content)).convert("RGB")
>>> classes3 = ["statue", "trees"]
>>> task3 = "Focus on the foreground, detect statue and trees."

>>> inputs = processor(
...     images=[image1, image2, image3],
...     text=[classes1, classes2, classes3],
...     task=[task1, task2, task3],
...     return_tensors="pt",
... )

>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> # convert outputs (bounding boxes and class logits)
>>> results = processor.post_process_grounded_object_detection(
...     outputs,
...     classes=[classes1, classes2, classes3],
...     target_sizes=[image1.size[::-1], image2.size[::-1], image3.size[::-1]],
...     score_threshold=0.2,
...     nms_threshold=0.3,
... )

>>> for i, result in enumerate(results):
...     for score, class_name, box in zip(
...         result["scores"], result["classes"], result["boxes"]
...     ):
...         box = [round(i, 1) for i in box.tolist()]
...         print(
...             f"Detected {class_name} with confidence "
...             f"{round(score.item(), 2)} at location {box} in image {i}"
...         )
Detected remote with confidence 0.77 at location [39.9, 70.4, 176.7, 118.0] in image 0
Detected cat with confidence 0.72 at location [11.6, 54.2, 314.8, 474.0] in image 0
Detected remote with confidence 0.56 at location [333.4, 75.8, 370.7, 187.0] in image 0
Detected cat with confidence 0.55 at location [345.2, 24.0, 639.8, 371.7] in image 0
Detected boat with confidence 0.32 at location [146.9, 219.8, 209.6, 250.7] in image 1
Detected boat with confidence 0.3 at location [319.1, 223.2, 403.2, 238.4] in image 1
Detected boat with confidence 0.27 at location [37.7, 220.3, 84.0, 235.9] in image 1
Detected boat with confidence 0.22 at location [407.9, 207.0, 441.7, 220.2] in image 1
Detected statue with confidence 0.73 at location [544.7, 210.2, 651.9, 502.8] in image 2
Detected trees with confidence 0.25 at location [3.9, 584.3, 391.4, 785.6] in image 2
Detected trees with confidence 0.25 at location [1.4, 621.2, 118.2, 787.8] in image 2
Detected statue with confidence 0.2 at location [428.1, 205.5, 767.3, 759.5] in image 2

OmDetTurboConfig

transformers.OmDetTurboConfig

< >

( text_config = None backbone_config = None use_timm_backbone = True backbone = 'swin_tiny_patch4_window7_224' backbone_kwargs = None use_pretrained_backbone = False apply_layernorm_after_vision_backbone = True image_size = 640 disable_custom_kernels = False layer_norm_eps = 1e-05 batch_norm_eps = 1e-05 init_std = 0.02 text_projection_in_dim = 512 text_projection_out_dim = 512 task_encoder_hidden_dim = 1024 class_embed_dim = 512 class_distance_type = 'cosine' num_queries = 900 csp_activation = 'silu' conv_norm_activation = 'gelu' encoder_feedforward_activation = 'relu' encoder_feedforward_dropout = 0.0 encoder_dropout = 0.0 hidden_expansion = 1 vision_features_channels = [256, 256, 256] encoder_hidden_dim = 256 encoder_in_channels = [192, 384, 768] encoder_projection_indices = [2] encoder_attention_heads = 8 encoder_dim_feedforward = 2048 encoder_layers = 1 positional_encoding_temperature = 10000 num_feature_levels = 3 decoder_hidden_dim = 256 decoder_num_heads = 8 decoder_num_layers = 6 decoder_activation = 'relu' decoder_dim_feedforward = 2048 decoder_num_points = 4 decoder_dropout = 0.0 eval_size = None learn_initial_query = False cache_size = 100 is_encoder_decoder = True **kwargs )

参数

  • text_config (PretrainedConfig, optional) — 文本主干的配置。
  • backbone_config (PretrainedConfig, optional) — 视觉骨干网络的配置。
  • use_timm_backbone (bool, optional, defaults to True) — 是否使用timm作为视觉骨干网络。
  • backbone (str, 可选, 默认为 "swin_tiny_patch4_window7_224") — 使用的预训练视觉骨干网络的名称。如果 use_pretrained_backbone=False,则使用具有相同架构的随机初始化骨干网络 backbone
  • backbone_kwargs (dict, optional) — 用于视觉骨干的额外kwargs。
  • use_pretrained_backbone (bool, 可选, 默认为 False) — 是否使用预训练的视觉骨干网络.
  • apply_layernorm_after_vision_backbone (bool, optional, defaults to True) — 是否在视觉骨干输出的特征图上应用层归一化。
  • image_size (int, optional, 默认为 640) — 每张图像的尺寸(分辨率)。
  • disable_custom_kernels (bool, optional, defaults to False) — 是否禁用自定义内核.
  • layer_norm_eps (float, optional, 默认为 1e-05) — 层归一化的 epsilon 值。
  • batch_norm_eps (float, optional, defaults to 1e-05) — 批归一化的epsilon值。
  • init_std (float, optional, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • text_projection_in_dim (int, optional, defaults to 512) — 文本投影的输入维度。
  • text_projection_out_dim (int, optional, defaults to 512) — 文本投影的输出维度。
  • task_encoder_hidden_dim (int, optional, defaults to 1024) — 任务编码器的前馈维度。
  • class_embed_dim (int, optional, 默认为 512) — 类别嵌入的维度。
  • class_distance_type (str, 可选, 默认为 "cosine") — 用于比较预测类别与投影类别嵌入的距离类型。 可以是 "cosine""dot".
  • num_queries (int, 可选, 默认为 900) — 查询的数量.
  • csp_activation (str, optional, defaults to "silu") — 编码器的跨阶段部分(CSP)网络的激活函数。
  • conv_norm_activation (str, 可选, 默认为 "gelu") — 编码器的ConvNormLayer层的激活函数。
  • encoder_feedforward_activation (str, optional, defaults to "relu") — 编码器前馈网络的激活函数。
  • encoder_feedforward_dropout (float, optional, defaults to 0.0) — 编码器前馈网络激活后的丢弃率。
  • encoder_dropout (float, optional, 默认为 0.0) — 编码器多头注意力模块的丢弃率。
  • hidden_expansion (int, optional, defaults to 1) — 编码器中CSP网络的隐藏扩展。
  • vision_features_channels (tuple(int), 可选, 默认为 [256, 256, 256]) — 用作解码器输入的投影视觉特征通道。
  • encoder_hidden_dim (int, optional, defaults to 256) — 编码器的隐藏维度。
  • encoder_in_channels (List(int), 可选, 默认为 [192, 384, 768]) — 编码器的输入通道数。
  • encoder_projection_indices (List(int), 可选, 默认为 [2]) — 每层投影的输入特征的索引。
  • encoder_attention_heads (int, optional, defaults to 8) — 编码器的注意力头数。
  • encoder_dim_feedforward (int, optional, 默认为 2048) — 编码器的前馈维度。
  • encoder_layers (int, optional, defaults to 1) — 编码器中的层数。
  • positional_encoding_temperature (int, optional, 默认为 10000) — 编码器中的位置编码温度。
  • num_feature_levels (int, optional, defaults to 3) — 解码器的多尺度可变形注意力模块的特征级别数量。
  • decoder_hidden_dim (int, optional, 默认为 256) — 解码器的隐藏维度。
  • decoder_num_heads (int, optional, defaults to 8) — 解码器的头数。
  • decoder_num_layers (int, optional, defaults to 6) — 解码器的层数。
  • decoder_activation (str, optional, defaults to "relu") — 解码器的激活函数。
  • decoder_dim_feedforward (int, optional, 默认为 2048) — 解码器的前馈维度。
  • decoder_num_points (int, optional, defaults to 4) — 解码器多尺度可变形注意力模块中采样的点数。
  • decoder_dropout (float, optional, 默认为 0.0) — 解码器的丢弃率。
  • eval_size (Tuple[int, int], 可选) — 用于计算位置嵌入的有效高度和宽度的值,考虑了步幅(参见RTDetr)。
  • learn_initial_query (bool, 可选, 默认为 False) — 是否学习初始查询.
  • cache_size (int, optional, 默认为 100) — 类和提示缓存的缓存大小。
  • is_encoder_decoder (bool, optional, 默认为 True) — 模型是否被用作编码器-解码器模型。
  • kwargs (Dict[str, Any], 可选) — 来自架构的额外参数。kwargs 中的值将作为配置的一部分保存,并可用于控制模型输出。

这是用于存储OmDetTurboForObjectDetection配置的配置类。 它用于根据指定的参数实例化一个OmDet-Turbo模型,定义模型架构。 使用默认值实例化配置将产生与OmDet-Turbo omlab/omdet-turbo-swin-tiny-hf架构类似的配置。

配置对象继承自PretrainedConfig,可用于控制模型输出。阅读PretrainedConfig的文档以获取更多信息。

示例:

>>> from transformers import OmDetTurboConfig, OmDetTurboForObjectDetection

>>> # Initializing a OmDet-Turbo omlab/omdet-turbo-swin-tiny-hf style configuration
>>> configuration = OmDetTurboConfig()

>>> # Initializing a model (with random weights) from the omlab/omdet-turbo-swin-tiny-hf style configuration
>>> model = OmDetTurboForObjectDetection(configuration)

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

OmDetTurboProcessor

transformers.OmDetTurboProcessor

< >

( image_processor tokenizer )

参数

  • image_processor (DetrImageProcessor) — 一个 DetrImageProcessor 的实例。图像处理器是一个必需的输入。
  • tokenizer (AutoTokenizer) — [‘PreTrainedTokenizer`]的一个实例。tokenizer是一个必需的输入。

构建一个OmDet-Turbo处理器,它将可变形DETR图像处理器和AutoTokenizer包装成一个单一的处理器。

OmDetTurboProcessor 提供了 DetrImageProcessorAutoTokenizer 的所有功能。有关更多信息,请参阅 __call__()decode() 的文档字符串。

post_process_grounded_object_detection

< >

( 输出 类别: typing.Union[typing.List[str], typing.List[typing.List[str]]] 分数阈值: float = 0.3 非极大值抑制阈值: float = 0.5 目标尺寸: typing.Union[transformers.utils.generic.TensorType, typing.List[typing.Tuple], NoneType] = None 最大检测数量: typing.Optional[int] = None ) List[Dict]

参数

  • 输出 (OmDetTurboObjectDetectionOutput) — 模型的原始输出。
  • classes (Union[List[str], List[List[str]]]) — 输入的类名。
  • score_threshold (float, 默认为 0.3) — 仅返回置信度分数超过此阈值的检测结果。
  • nms_threshold (float, 默认值为 0.5) — 用于框非最大抑制的阈值。值在 [0, 1] 之间。
  • target_sizes (torch.TensorList[Tuple[int, int]], 可选, 默认为 None) — 形状为 (batch_size, 2) 的张量或包含批次中每个图像目标大小的元组列表 (Tuple[int, int]),目标大小为 (height, width)。如果未设置,预测将不会调整大小。
  • max_num_det (int, 可选, 默认为 None) — 返回的最大检测数量。

返回

List[Dict]

一个字典列表,每个字典包含模型预测的批次中图像的分数、类别和框。

OmDetTurboForObjectDetection的原始输出转换为最终边界框,格式为(左上角x,左上角y,右下角x,右下角y),并获取相关的文本类别。

OmDetTurboForObjectDetection

transformers.OmDetTurboForObjectDetection

< >

( 配置: OmDetTurboConfig )

参数

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

OmDetTurbo 模型(由视觉和文本骨干以及编码器-解码器架构组成)输出用于 COCO 检测等任务的边界框和类别分数。

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

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( pixel_values: Tensor classes_input_ids: Tensor classes_attention_mask: Tensor tasks_input_ids: Tensor tasks_attention_mask: Tensor classes_structure: Tensor labels: typing.Optional[torch.Tensor] = None output_attentions = None output_hidden_states = None return_dict = None ) transformers.models.omdet_turbo.modeling_omdet_turbo.OmDetTurboObjectDetectionOutputtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) — Pixel values. Padding will be ignored by default should you provide it.

    可以使用AutoImageProcessor获取像素值。详情请参见DetrImageProcessor.call()

  • classes_input_ids (torch.LongTensor of shape (total_classes (>= batch_size), sequence_length)) — Indices of input classes sequence tokens in the vocabulary of the language model. Several classes can be provided for each tasks, thus the tokenized classes are flattened and the structure of the classes is provided in the classes_structure argument.

    可以使用OmDetTurboProcessor获取索引。详情请参见OmDetTurboProcessor.__call__()

    什么是输入ID?

  • classes_attention_mask (torch.BoolTensor of shape (total_classes (>= batch_size), num_classes, sequence_length)) — 类的注意力掩码。这是一个二进制掩码,指示哪些标记应该被关注, 哪些不应该被关注。
  • tasks_input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input tasks sequence tokens in the vocabulary of the language model.

    可以使用OmDetTurboProcessor获取索引。详情请参见OmDetTurboProcessor.__call__()

    什么是输入ID?

  • tasks_attention_mask (torch.BoolTensor of shape (batch_size, sequence_length)) — 任务的注意力掩码。这是一个二进制掩码,指示哪些标记应该被关注, 哪些不应该被关注。
  • classes_structure (torch.LongTensor of shape (batch_size)) — 类的结构。该张量表示每个任务的类别数量。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。

返回

transformers.models.omdet_turbo.modeling_omdet_turbo.OmDetTurboObjectDetectionOutputtuple(torch.FloatTensor)

一个 transformers.models.omdet_turbo.modeling_omdet_turbo.OmDetTurboObjectDetectionOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含根据配置(OmDetTurboConfig)和输入的各种元素。

  • loss (torch.FloatTensor) — 损失值。
  • decoder_coord_logits (torch.FloatTensor 形状为 (batch_size, num_queries, 4)) — 预测的物体坐标 logits。
  • decoder_class_logits (torch.FloatTensor 形状为 (batch_size, num_queries, num_classes)) — 预测的物体类别。
  • init_reference_points (torch.FloatTensor 形状为 (batch_size, num_queries, 4)) — 初始参考点。
  • intermediate_reference_points (Tuple[Tuple[torch.FloatTensor]]) — 中间参考点。
  • encoder_coord_logits (torch.FloatTensor 形状为 (batch_size, num_queries, 4)) — 从编码器预测的物体坐标。
  • encoder_class_logits (Tuple[torch.FloatTensor]) — 从编码器预测的物体类别。
  • encoder_extracted_states (torch.FloatTensor) — 从编码器的特征金字塔网络(FPN)和路径聚合网络(PAN)中提取的状态。
  • decoder_hidden_states (Optional[Tuple[torch.FloatTensor]]) — 由 torch.FloatTensor 组成的元组(一个用于嵌入的输出 + 一个用于每层的输出),形状为 (batch_size, sequence_length, hidden_size)。模型在每层输出处的隐藏状态加上初始嵌入输出。
  • decoder_attentions (Optional[Tuple[Tuple[torch.FloatTensor]]]) — 由 torch.FloatTensor 组成的元组(每层一个注意力),形状为 (batch_size, num_heads, sequence_length, sequence_length)。注意力 softmax 后的注意力权重,用于计算自注意力、交叉注意力和多尺度可变形注意力头中的加权平均值。
  • encoder_hidden_states (Optional[Tuple[torch.FloatTensor]]) — 由 torch.FloatTensor 组成的元组(一个用于嵌入的输出 + 一个用于每层的输出),形状为 (batch_size, sequence_length, hidden_size)。模型在每层输出处的隐藏状态加上初始嵌入输出。
  • encoder_attentions (Optional[Tuple[Tuple[torch.FloatTensor]]]) — 由 torch.FloatTensor 组成的元组(每层一个注意力),形状为 (batch_size, num_heads, sequence_length, sequence_length)。注意力 softmax 后的注意力权重,用于计算自注意力、交叉注意力和多尺度可变形注意力头中的加权平均值。

OmDetTurboForObjectDetection 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> import requests
>>> from PIL import Image

>>> from transformers import AutoProcessor, OmDetTurboForObjectDetection

>>> processor = AutoProcessor.from_pretrained("omlab/omdet-turbo-swin-tiny-hf")
>>> model = OmDetTurboForObjectDetection.from_pretrained("omlab/omdet-turbo-swin-tiny-hf")

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> classes = ["cat", "remote"]
>>> task = "Detect {}.".format(", ".join(classes))
>>> inputs = processor(image, text=classes, task=task, return_tensors="pt")

>>> outputs = model(**inputs)

>>> # convert outputs (bounding boxes and class logits)
>>> results = processor.post_process_grounded_object_detection(
...     outputs,
...     classes=classes,
...     target_sizes=[image.size[::-1]],
...     score_threshold=0.3,
...     nms_threshold=0.3,
>>> )[0]
>>> for score, class_name, box in zip(results["scores"], results["classes"], results["boxes"]):
...     box = [round(i, 1) for i in box.tolist()]
...     print(
...         f"Detected {class_name} with confidence "
...         f"{round(score.item(), 2)} at location {box}"
...     )
Detected remote with confidence 0.76 at location [39.9, 71.3, 176.5, 117.9]
Detected cat with confidence 0.72 at location [345.1, 22.5, 639.7, 371.9]
Detected cat with confidence 0.65 at location [12.7, 53.8, 315.5, 475.3]
Detected remote with confidence 0.57 at location [333.4, 75.6, 370.7, 187.0]
< > Update on GitHub