Transformers documentation
OmDet-Turbo
该模型于 2024-03-11 在 HF papers 上发布,并于 2024-09-25 贡献至 Hugging Face Transformers。
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 的性能。
该论文的摘要如下:
基于 Transformer 的端到端检测器(DETR)通过整合语言模态,在闭集和开放词汇目标检测(OVD)任务中均展现出卓越的性能。然而,其高昂的计算需求阻碍了其在实时目标检测(OD)场景中的实际应用。本文深入剖析了 OVDEval 基准测试中两个领先模型 OmDet 和 Grounding-DINO 的局限性,并提出了 OmDet-Turbo。这款新颖的基于 Transformer 的实时 OVD 模型具备创新的 Efficient Fusion Head (EFH) 模块,旨在缓解 OmDet 和 Grounding-DINO 中观察到的瓶颈问题。值得注意的是,应用 TensorRT 和语言缓存技术后,OmDet-Turbo-Base 实现了 100.2 帧每秒(FPS)的速度。此外,在 COCO 和 LVIS 数据集的零样本场景中,OmDet-Turbo 达到了与当前最先进的监督模型几乎相当的性能水平。同时,它在 ODinW 和 OVDEval 上确立了新的最先进基准,AP 分别为 30.1,NMS-AP 分别为 26.86。OmDet-Turbo 在基准数据集上的卓越表现和优越的推理速度,凸显了其在工业应用中的实用性,使其成为实时目标检测任务的理想选择。
OmDet-Turbo architecture overview. Taken from the original paper. 该模型由 yonigozlan 贡献。 原始代码可在此处找到。
使用技巧
与 Grounding DINO 等其他零样本目标检测模型相比,OmDet-Turbo 的一个独特之处在于其解耦的类别与提示嵌入结构,该结构支持对文本嵌入进行缓存。这意味着模型需要同时输入 classes 和 task,其中 classes 是我们希望检测的对象列表,而 task 是用于引导开放词汇检测的接地文本。这种方法限制了开放词汇检测的范围,并使解码过程更快。
OmDetTurboProcessor 用于准备类别、任务和图像这三元组。任务输入是可选的,如果未提供,则默认为 "Detect [class1], [class2], [class3], ..."。要处理模型的输出结果,可以使用 OmDetTurboProcessor 中的 post_process_grounded_object_detection。值得注意的是,该函数需要接收输入类别,因为与其他零样本目标检测模型不同,类别嵌入和任务嵌入的解耦意味着在后处理步骤中无需对预测的类别嵌入进行解码,预测的类别可以直接与输入的类别进行匹配。
使用示例
单图像推理
以下是如何加载模型并准备输入,以在单张图像上执行零样本目标检测:
import torch
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", device_map="auto")
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)
text_labels = ["cat", "remote"]
inputs = processor(image, text=text_labels, return_tensors="pt").to(model.device)
with torch.no_grad():
outputs = model(**inputs)
# convert outputs (bounding boxes and class logits)
results = processor.post_process_grounded_object_detection(
outputs,
target_sizes=[(image.height, image.width)],
text_labels=text_labels,
threshold=0.3,
nms_threshold=0.3,
)
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 remote with confidence 0.768 at location [39.89, 70.35, 176.74, 118.04]
Detected cat with confidence 0.72 at location [11.6, 54.19, 314.8, 473.95]
Detected remote with confidence 0.563 at location [333.38, 75.77, 370.7, 187.03]
Detected cat with confidence 0.552 at location [345.15, 23.95, 639.75, 371.67]多图像推理
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", device_map="auto")
url1 = "http://images.cocodataset.org/val2017/000000039769.jpg"
image1 = Image.open(BytesIO(requests.get(url1).content)).convert("RGB")
text_labels1 = ["cat", "remote"]
task1 = "Detect {}.".format(", ".join(text_labels1))
url2 = "http://images.cocodataset.org/train2017/000000257813.jpg"
image2 = Image.open(BytesIO(requests.get(url2).content)).convert("RGB")
text_labels2 = ["boat"]
task2 = "Detect everything that looks like a boat."
url3 = "https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/statue_of_liberty.jpg"
image3 = Image.open(BytesIO(requests.get(url3).content)).convert("RGB")
text_labels3 = ["statue", "trees"]
task3 = "Focus on the foreground, detect statue and trees."
inputs = processor(
images=[image1, image2, image3],
text=[text_labels1, text_labels2, text_labels3],
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,
text_labels=[text_labels1, text_labels2, text_labels3],
target_sizes=[(image.height, image.width) for image in [image1, image2, image3]],
threshold=0.2,
nms_threshold=0.3,
)
for i, result in enumerate(results):
for score, text_label, box in zip(
result["scores"], result["text_labels"], result["boxes"]
):
box = [round(i, 1) for i in box.tolist()]
print(
f"Detected {text_label} 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
class transformers.OmDetTurboConfig
< source >( 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 = 0id2label: 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 = Noneis_encoder_decoder: bool = Truetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonebackbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneapply_layernorm_after_vision_backbone: bool = Trueimage_size: int | list[int] | tuple[int, int] = 640disable_custom_kernels: bool = Falselayer_norm_eps: float = 1e-05batch_norm_eps: float = 1e-05init_std: float = 0.02text_projection_in_dim: int = 512text_projection_out_dim: int = 512task_encoder_hidden_dim: int = 1024class_embed_dim: int = 512class_distance_type: typing.Literal['cosine', 'dot'] = 'cosine'num_queries: int = 900csp_activation: str = 'silu'conv_norm_activation: str = 'gelu'encoder_feedforward_activation: str = 'relu'encoder_feedforward_dropout: float | int = 0.0encoder_dropout: float | int = 0.0hidden_expansion: int = 1encoder_hidden_dim: int = 256vision_features_channels: list[int] | tuple[int, ...] = (256, 256, 256)encoder_in_channels: list[int] | tuple[int, ...] = (192, 384, 768)encoder_projection_indices: list[int] | tuple[int, ...] = (2,)encoder_attention_heads: int = 8encoder_dim_feedforward: int = 2048encoder_layers: int = 1positional_encoding_temperature: int = 10000num_feature_levels: int = 3decoder_hidden_dim: int = 256decoder_num_heads: int = 8decoder_num_layers: int = 6decoder_activation: str = 'relu'decoder_dim_feedforward: int = 2048decoder_num_points: int = 4decoder_dropout: float | int = 0.0eval_size: int | None = Nonelearn_initial_query: bool = Falsecache_size: int = 100 )
参数
- is_encoder_decoder (
bool,可选,默认为True) — 指示该模型是否用作编码器/解码器。 - text_config (
Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 文本骨干网络的配置对象或字典。 - backbone_config (
Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 主干模型的配置。 - apply_layernorm_after_vision_backbone (
bool,可选,默认为True) — 是否对视觉骨干网络输出的特征图应用层归一化。 - image_size (
Union[int, list[int], tuple[int, int]],可选,默认为640) — 每张图片的尺寸(分辨率)。 - disable_custom_kernels (
bool,可选,默认为False) — 是否禁用自定义内核。 - layer_norm_eps (
float,可选,默认为1e-05) — 层归一化层所使用的 epsilon 值。 - batch_norm_eps (
float,可选,默认为1e-05) — 批归一化层使用的 epsilon 值。 - init_std (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - text_projection_in_dim (
int,可选,默认为 512) — 文本投影的输入维度。 - text_projection_out_dim (
int,可选,默认为 512) — 文本投影的输出维度。 - task_encoder_hidden_dim (
int,可选,默认值为 1024) — 任务编码器的前馈维度。 - class_embed_dim (
int,可选,默认为 512) — 类别嵌入的维度。 - class_distance_type (
str,可选,默认为"cosine") — 用于比较预测类别与投影类别嵌入的距离类型。 可以是"cosine"或"dot"。 - num_queries (
int,可选,默认为 900) — 查询的数量。 - csp_activation (
str,可选,默认为"silu") — 编码器中 Cross Stage Partial (CSP) 网络的激活函数。 - conv_norm_activation (
str,可选,默认为"gelu") — 编码器中 ConvNormLayer 层的激活函数。 - encoder_feedforward_activation (
str, 可选,默认为"relu") — 编码器前馈网络的激活函数。 - encoder_feedforward_dropout (
float, 可选,默认为 0.0) — 编码器前馈网络激活后的 dropout 率。 - encoder_dropout (
Union[float, int],可选,默认为0.0) — 所有 dropout 层的比率。 - hidden_expansion (
int,可选,默认为 1) — 编码器中 CSP 网络的隐藏层扩展系数。 - encoder_hidden_dim (
int,可选,默认为256) — 隐藏表示的维度。 - vision_features_channels (
tuple(int),可选,默认为[256, 256, 256]) — 用作解码器输入的投影视觉特征通道数。 - encoder_in_channels (
List(int),可选,默认为[192, 384, 768]) — 编码器的输入通道数。 - encoder_projection_indices (
List(int),可选,默认为[2]) — 每个层所投影的输入特征的索引。 - encoder_attention_heads (
int,可选,默认为8) — Transformer 编码器中每个注意力层的注意力头数量。 - encoder_dim_feedforward (
int,可选,默认为 2048) — 编码器的前馈维度。 - encoder_layers (
int,可选,默认为1) — Transformer 编码器中的隐藏层数量。如果未设置,将使用与num_layers相同的值。 - positional_encoding_temperature (
int,可选,默认值为 10000) — 编码器中的位置编码温度。 - num_feature_levels (
int, 可选,默认为 3) — 解码器中多尺度可变形注意力模块的特征层数。 - decoder_hidden_dim (
int,可选,默认为256) — 隐藏表示的维度。 - decoder_num_heads (
int,可选,默认为8) — Transformer 解码器中每个注意力层的注意力头数量。 - decoder_num_layers (
int,可选,默认为6) — Transformer 解码器中的隐藏层数量。如果未设置,将使用与num_layers相同的值。 - decoder_activation (
str,可选,默认为"relu") — 解码器的激活函数。 - decoder_dim_feedforward (
int,可选,默认值为 2048) — 解码器的前馈维度。 - decoder_num_points (
int,可选,默认为 4) — 解码器多尺度可变形注意力模块中采样的点数。 - decoder_dropout (
float, 可选,默认为 0.0) — 解码器的 dropout 率。 - eval_size (
tuple[int, int],可选) — 用于在考虑步长(参见 RTDetr)后计算位置嵌入的有效高度和宽度。 - learn_initial_query (
bool,可选,默认为False) — 是否学习初始查询。 - cache_size (
int,可选,默认为 100) — 用于类和提示词缓存的缓存大小。
这是用于存储 Omdet TurboModel 配置的类。它根据指定的参数实例化 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.configOmDetTurboProcessor
class transformers.OmDetTurboProcessor
< source >( image_processortokenizer )
构建一个 OmDetTurboProcessor,它将图像处理器和分词器封装为单个处理器。
OmDetTurboProcessor 提供了 DetrImageProcessor 和 CLIPTokenizer 的所有功能。有关更多信息,请参阅 ~DetrImageProcessor 和 ~CLIPTokenizer。
__call__
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Nonetext: list[str] | list[list[str]] | None = None**kwargs: *<class 'transformers.models.omdet_turbo.processing_omdet_turbo.OmDetTurboProcessorKwargs'> ) → ~feature_extraction_utils.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[list[str], list[list[str]]],可选) — 要编码的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果传入预分词输入,请设置is_split_into_words=True以避免与批量输入产生歧义。 - task (
str, kwargs,list[str],TextInput或PreTokenizedInput,可选) — 要编码的检测任务描述。如果未提供,则会根据text输入生成默认的任务描述(例如,“Detect {text}.”)。可以是单个字符串、字符串列表(每张图片对应一个)或预分词输入。任务描述用于指导模型检测图像中的哪些对象。 - return_tensors (
str或 TensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:'pt':返回 PyTorchtorch.Tensor对象。'np':返回 NumPynp.ndarray对象。
- **kwargs (ProcessingKwargs,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。
返回值
~feature_extraction_utils.BatchFeature
- data (
dict,可选) — 由 call/pad 方法返回的列表/数组/张量字典(例如 ‘input_values’、‘attention_mask’ 等)。 - tensor_type (
Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。 - skip_tensor_conversion(
list[str]或set[str],可选)——即使指定了tensor_type,也不应转换为张量的键的列表或集合。
post_process_grounded_object_detection
< source >( outputs: OmDetTurboObjectDetectionOutputtext_labels: list[str] | list[list[str]] | None = Nonethreshold: float = 0.3nms_threshold: float = 0.5target_sizes: transformers.utils.generic.TensorType | list[tuple] | None = Nonemax_num_det: int | None = None ) → list[Dict]
参数
- outputs (
OmDetTurboObjectDetectionOutput) — 模型的原始输出。 - text_labels (Union[list[str], list[list[str]]], 可选) —
输入类别的名称。如果未提供,
outputs中的text_labels将被设置为None。 - threshold (float, 默认值为 0.3) — 仅返回置信度分数超过此阈值的检测结果。
- nms_threshold (float, 默认值为 0.5) — 用于框非极大值抑制的阈值。取值范围为 [0, 1]。
- target_sizes (
torch.Tensor或list[tuple[int, int]],可选) — 形状为(batch_size, 2)的张量,或包含目标尺寸(height, width)的元组列表(tuple[int, int]),表示批次中每张图片的目标大小。如果未设置,预测结果将不会被调整大小。 - max_num_det (
int, 可选) — 要返回的最大检测数量。
返回值
list[Dict]
一个字典列表,每个字典包含模型预测的批次中某张图像的分数、类别和边界框。
将 OmDetTurboForObjectDetection 的原始输出转换为 (top_left_x, top_left_y, bottom_right_x, bottom_right_y) 格式的最终边界框,并获取对应的文本类别。
OmDetTurboForObjectDetection
class transformers.OmDetTurboForObjectDetection
< source >( config: OmDetTurboConfig )
参数
- config (OmDetTurboConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
OmDetTurbo 模型(由视觉骨干网络和文本骨干网络组成,并采用编码器-解码器架构),用于输出边界框和类别分数,以完成 COCO 检测等任务。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: Tensorclasses_input_ids: LongTensorclasses_attention_mask: LongTensortasks_input_ids: LongTensortasks_attention_mask: LongTensorclasses_structure: LongTensorlabels: typing.Optional[torch.LongTensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → OmDetTurboObjectDetectionOutput or tuple(torch.Tensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size)) — 与输入图像对应的张量。可以使用 DetrImageProcessor 获取像素值。有关详细信息,请参阅 DetrImageProcessor.call()(OmDetTurboProcessor 使用 DetrImageProcessor 处理图像)。 - classes_input_ids (
torch.LongTensor形状为(total_classes (>= batch_size), sequence_length)) — 输入类别序列 token 在语言模型词汇表中的索引。 每个任务可以提供多个类别,因此 token 化的类别会被展平,类别的结构通过classes_structure参数提供。可以使用 OmDetTurboProcessor 获取索引。有关详细信息,请参阅 OmDetTurboProcessor.call()。
- classes_attention_mask(形状为
(total_classes (>= batch_size), num_classes, sequence_length)的torch.BoolTensor)— 用于类别的注意力掩码。这是一个二进制掩码,指示哪些 token 应被关注,哪些不应被关注。 - tasks_input_ids (
torch.LongTensor形状为(batch_size, sequence_length)) — 输入任务序列 token 在语言模型词汇表中的索引。可以使用 OmDetTurboProcessor 获取索引。有关详细信息,请参阅 OmDetTurboProcessor.call()。
- tasks_attention_mask (
torch.BoolTensor,形状为(batch_size, sequence_length)) — 任务的注意力掩码。这是一个二元掩码,用于指示哪些 token 应被关注,哪些不应被关注。 - classes_structure (
torch.LongTensor,形状为(batch_size)) — 类别的结构。此张量指示每个任务的类别数量。 - labels (
list[Dict],长度为(batch_size,),可选) — 用于计算二部图匹配损失的标签。一个字典列表,每个字典至少包含以下 2 个键:‘class_labels’ 和 ‘boxes’(分别表示批次中某张图像的分类标签和边界框)。分类标签本身应是一个长度为(number of bounding boxes in the image,)的torch.LongTensor,边界框应是一个形状为(number of bounding boxes in the image, 4)的torch.Tensor。 - output_attentions (
bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的attentions。 - output_hidden_states (
bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的hidden_states。 - return_dict (
bool, 可选) — 是否返回 ModelOutput 而不是普通元组。
返回值
OmDetTurboObjectDetectionOutput 或 tuple(torch.Tensor)
OmDetTurboObjectDetectionOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(OmDetTurboConfig)和输入。
OmDetTurboForObjectDetection 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
- loss (
torch.Tensor, 可选) — 损失值。 - decoder_coord_logits(形状为
(batch_size, num_queries, 4)的torch.Tensor)— 预测的对象坐标 logits。 - decoder_class_logits(形状为
(batch_size, num_queries, num_classes)的torch.Tensor)— 预测的对象类别。 - init_reference_points(形状为
(batch_size, num_queries, 4)的torch.Tensor)— 初始参考点。 - intermediate_reference_points (
tuple[tuple[torch.Tensor]],可选) — 中间参考点。 - encoder_coord_logits(形状为
(batch_size, num_queries, 4)的torch.Tensor)— 编码器预测的对象坐标。 - encoder_class_logits (
tuple[torch.Tensor],可选) — 编码器预测的对象类别。 - encoder_extracted_states (
torch.Tensor, 可选) — 从编码器的特征金字塔网络(FPN)和路径聚合网络(PAN)中提取的状态。 - decoder_hidden_states (
tuple[torch.Tensor],可选) — 一个torch.Tensor元组(包含嵌入层的输出以及每一层的输出),形状为(batch_size, sequence_length, hidden_size)。模型在每一层输出处的隐藏状态,外加初始嵌入层的输出。 - decoder_attentions (
tuple[tuple[torch.Tensor]],可选) — 由torch.Tensor元组组成的元组(每个层对应一个注意力元组),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力 softmax 之后的注意力权重,用于在自注意力、交叉注意力和多尺度可变形注意力头中计算加权平均值。 - encoder_hidden_states (
tuple[torch.Tensor], 可选) — 一个torch.Tensor元组(包含一个嵌入层输出张量和每个隐藏层的一个输出张量),形状为(batch_size, sequence_length, hidden_size)。模型在每一层输出处的隐藏状态,外加初始嵌入层的输出。 - encoder_attentions (
tuple[tuple[torch.Tensor]], 可选) — 由torch.Tensor元组组成的元组(每个层对应一个注意力元组),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力 softmax 之后的注意力权重,用于在自注意力、交叉注意力和多尺度可变形注意力头中计算加权平均值。 - classes_structure (
torch.LongTensor, 可选) — 每张图像所查询的类别数量。
示例:
>>> from huggingface_hub.utils import httpx
>>> 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")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
... image = Image.open(BytesIO(response.read()))
>>> 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]