Transformers documentation

D-FINE

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2024-10-17 在 HF papers 上发布,并于 2025-04-29 贡献至 Hugging Face Transformers。

D-FINE

概述

D-FINE 模型由 Yansong Peng、Hebei Li、Peixi Wu、Yueyi Zhang、Xiaoyan Sun 和 Feng Wu 在 D-FINE: Redefine Regression Task in DETRs as Fine-grained Distribution Refinement 中提出。

该论文的摘要如下:

我们提出了 D-FINE,一种强大的实时目标检测器,通过重新定义 DETR 模型中的边界框回归任务,实现了卓越的定位精度。D-FINE 包含两个关键组件:细粒度分布精化(FDR)和全局最优定位自蒸馏(GO-LSD)。 FDR 将回归过程从预测固定坐标转变为迭代精化概率分布,提供了一种细粒度的中间表示,从而显著提升定位精度。GO-LSD 是一种双向优化策略,通过自蒸馏将定位知识从精化后的分布传递到更浅的层,同时简化了更深层的残差预测任务。此外,D-FINE 在计算密集型模块和运算中引入了轻量级优化,在速度和精度之间取得了更好的平衡。具体而言,D-FINE-L / X 在 COCO 数据集上分别达到 54.0% / 55.8% AP,在 NVIDIA T4 GPU 上的速度为 124 / 78 FPS。当在 Objects365 上进行预训练时,D-FINE-L / X 达到 57.1% / 59.3% AP,超越了所有现有的实时检测器。此外,我们的方法在几乎不增加额外参数和训练成本的情况下,将多种 DETR 模型的性能提升了高达 5.3% AP。我们的代码和预训练模型:this https URL。

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

使用技巧

import torch

from transformers import AutoImageProcessor, DFineForObjectDetection
from transformers.image_utils import load_image


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

image_processor = AutoImageProcessor.from_pretrained("ustc-community/dfine_x_coco")
model = DFineForObjectDetection.from_pretrained("ustc-community/dfine_x_coco", device_map="auto")

inputs = image_processor(images=image, return_tensors="pt").to(model.device)

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

results = image_processor.post_process_object_detection(outputs, target_sizes=[(image.height, image.width)], threshold=0.5)

for result in results:
    for score, label_id, box in zip(result["scores"], result["labels"], result["boxes"]):
        score, label = score.item(), label_id.item()
        box = [round(i, 2) for i in box.tolist()]
        print(f"{model.config.id2label[label]}: {score:.2f} {box}")
cat: 0.96 [344.49, 23.4, 639.84, 374.27]
cat: 0.96 [11.71, 53.52, 316.64, 472.33]
remote: 0.95 [40.46, 73.7, 175.62, 117.57]
sofa: 0.92 [0.59, 1.88, 640.25, 474.74]
remote: 0.89 [333.48, 77.04, 370.77, 187.3]

DFineConfig

class transformers.DFineConfig

< >

( 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 = Trueinitializer_range: float = 0.01initializer_bias_prior_prob: float | None = Nonelayer_norm_eps: float = 1e-05batch_norm_eps: float = 1e-05backbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonefreeze_backbone_batch_norms: bool = Trueencoder_hidden_dim: int = 256encoder_in_channels: list[int] | tuple[int, ...] = (512, 1024, 2048)feat_strides: list[int] | tuple[int, ...] = (8, 16, 32)encoder_layers: int = 1encoder_ffn_dim: int = 1024encoder_attention_heads: int = 8dropout: float | int = 0.0activation_dropout: float | int = 0.0encode_proj_layers: list[int] | tuple[int, ...] = (2,)positional_encoding_temperature: int = 10000encoder_activation_function: str = 'gelu'activation_function: str = 'silu'eval_size: int | None = Nonenormalize_before: bool = Falsehidden_expansion: float = 1.0d_model: int = 256num_queries: int = 300decoder_in_channels: list[int] | tuple[int, ...] = (256, 256, 256)decoder_ffn_dim: int = 1024num_feature_levels: int = 3decoder_n_points: int | list[int] = 4decoder_layers: int = 6decoder_attention_heads: int = 8decoder_activation_function: str = 'relu'attention_dropout: float | int = 0.0num_denoising: int = 100label_noise_ratio: float = 0.5box_noise_scale: float = 1.0learn_initial_query: bool = Falseanchor_image_size: int | list[int] | None = Nonewith_box_refine: bool = Truematcher_alpha: float = 0.25matcher_gamma: float = 2.0matcher_class_cost: float = 2.0matcher_bbox_cost: float = 5.0matcher_giou_cost: float = 2.0use_focal_loss: bool = Trueauxiliary_loss: bool = Truefocal_loss_alpha: float = 0.75focal_loss_gamma: float = 2.0weight_loss_vfl: float = 1.0weight_loss_bbox: float = 5.0weight_loss_giou: float = 2.0weight_loss_fgl: float = 0.15weight_loss_ddf: float = 1.5eos_coefficient: float = 0.0001eval_idx: int = -1layer_scale: int | float = 1.0max_num_bins: int = 32reg_scale: float = 4.0depth_mult: float = 1.0top_prob_values: int = 4lqe_hidden_dim: int = 64lqe_layers: int = 2decoder_offset_scale: float = 0.5decoder_method: str = 'default'up: float = 0.5tie_word_embeddings: bool = True )

参数

  • is_encoder_decoder (bool,可选,默认为 True) — 指示该模型是否用作编码器/解码器。
  • initializer_range (float,可选,默认为 0.01) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • initializer_bias_prior_prob (float, 可选) — 用于初始化 enc_score_head 和 class_embed 偏置的先验概率。 如果为 None,则在初始化模型权重时,prior_prob 的计算方式为 prior_prob = 1 / (num_labels + 1)。
  • layer_norm_eps (float,可选,默认为 1e-05) — 层归一化层所使用的 epsilon 值。
  • batch_norm_eps (float,可选,默认为 1e-05) — 批归一化层使用的 epsilon 值。
  • backbone_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 主干模型的配置。
  • freeze_backbone_batch_norms (bool,可选,默认为 True) — 是否冻结主干网络中的批归一化层。
  • encoder_hidden_dim (int,可选,默认为 256) — 隐藏表示的维度。
  • encoder_in_channels (list,可选,默认为 [512, 1024, 2048]) — 编码器的多级特征输入。
  • feat_strides(list[int],可选,默认为 [8, 16, 32])— 每个特征图中使用的步长。
  • encoder_layers (int,可选,默认为 1) — Transformer 编码器中的隐藏层数量。如果未设置,将使用与 num_layers 相同的值。
  • encoder_ffn_dim (int,可选,默认为 1024) — 编码器中“中间”(通常称为前馈)层的维度。
  • encoder_attention_heads (int,可选,默认为 8) — Transformer 编码器中每个注意力层的注意力头数量。
  • dropout (Union[float, int],可选,默认为 0.0) — 所有 dropout 层的比率。
  • activation_dropout (Union[float, int],可选,默认为 0.0) — 全连接层中激活值的 dropout 比率。
  • encode_proj_layers (list[int],可选,默认为 [2]) — 编码器中要使用的投影层的索引。
  • positional_encoding_temperature (int,可选,默认为 10000) — 用于创建位置编码的温度参数。
  • encoder_activation_function (str,可选,默认为 "gelu") — 编码器和池化器中使用的非线性激活函数(函数或字符串)。如果为字符串,则支持 "gelu"、"relu"、"silu" 和 "gelu_new"。
  • activation_function (str,可选,默认为 silu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu" 等。
  • eval_size (tuple[int, int],可选) — 用于在考虑步长后计算位置嵌入的有效高度和宽度的高度和宽度。
  • normalize_before (bool,可选,默认为 False) — 确定是否在 Transformer 编码器层的自注意力和前馈模块之前应用层归一化。
  • hidden_expansion (float,可选,默认值为 1.0) — 用于扩大 RepVGGBlock 和 CSPRepLayer 维度大小的扩展比例。
  • d_model (int,可选,默认为 256) — 编码器层和池化层的维度大小。
  • num_queries (int,可选,默认为 300) — 对象查询的数量。
  • decoder_in_channels (list,可选,默认为 [256, 256, 256]) — 解码器的多级特征维度
  • decoder_ffn_dim (int,可选,默认为 1024) — 解码器中“中间”(通常称为前馈)层的维度。
  • num_feature_levels (int, 可选,默认为 3) — 输入特征层级的数量。
  • decoder_n_points (int,可选,默认为 4) — 解码器中每个注意力头在每个特征层级上采样的键数量。
  • decoder_layers (int, 可选,默认为 6) — Transformer 解码器中的隐藏层数量。如果未设置,将使用与 num_layers 相同的值。
  • decoder_attention_heads (int,可选,默认为 8) — Transformer 解码器中每个注意力层的注意力头数量。
  • decoder_activation_function (str,可选,默认为 "relu") — 解码器中的非线性激活函数(函数或字符串)。如果为字符串,则支持 "gelu"、"relu"、"silu" 和 "gelu_new"。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • num_denoising (int,可选,默认为 100) — 用于对比去噪的去噪任务或查询的总数。
  • label_noise_ratio (float,可选,默认值为 0.5) — 应添加随机噪声的去噪标签比例。
  • box_noise_scale (float,可选,默认值为 1.0) — 添加到边界框的噪声的缩放比例或幅度。
  • learn_initial_query (bool,可选,默认为 False) — 指示是否应在训练过程中学习解码器的初始查询嵌入
  • anchor_image_size (tuple[int, int], 可选) — 评估期间用于生成边界框锚点的输入图像的高度和宽度。如果为 None,则应用自动生成的锚点。
  • with_box_refine (bool,可选,默认为 True) — 是否应用迭代式边界框细化,即每个解码器层基于上一层的预测结果来细化边界框。
  • matcher_alpha (float,可选,默认为 0.25) — 匈牙利匹配器(Hungarian Matcher)使用的参数 alpha。
  • matcher_gamma (float,可选,默认值为 2.0) — 匈牙利匹配器(Hungarian Matcher)所使用的参数 gamma。
  • matcher_class_cost (float,可选,默认为 2.0) — Hungarian Matcher 使用的类别损失的相对权重。
  • matcher_bbox_cost (float,可选,默认为 5.0) — 匈牙利匹配器(Hungarian Matcher)中边界框损失的相对权重。
  • matcher_giou_cost (float, 可选,默认为 2.0) — Hungarian Matcher 使用的 giou 损失的相对权重。
  • use_focal_loss (bool,可选,默认为 True) — 指示是否应使用 focal loss 的参数。
  • auxiliary_loss (bool,可选,默认为 True) — 是否使用辅助解码损失(即每个解码器层的损失)。
  • focal_loss_alpha (float, 可选,默认为 0.75) — 用于计算 focal loss 的参数 alpha。
  • focal_loss_gamma (float,可选,默认为 2.0) — 用于计算 focal loss 的参数 gamma。
  • weight_loss_vfl (float, 可选,默认为 1.0) — 在目标检测损失中,变焦点损失的相对权重。
  • weight_loss_bbox (float,可选,默认值为 5.0) — 目标检测损失中 L1 边界框损失的相对权重。
  • weight_loss_giou (float,可选,默认为 2.0) — 目标检测损失中广义 IoU 损失的相对权重。
  • weight_loss_fgl (float,可选,默认值为 0.15) — 在目标检测损失中,细粒度定位损失的相对权重。
  • weight_loss_ddf (float, 可选,默认为 1.5) — 在目标检测损失中,解耦蒸馏焦点损失的相对权重。
  • eos_coefficient (float,可选,默认为 0.0001) — 目标检测损失中“无目标”类别的相对分类权重。
  • eval_idx (int,可选,默认为 -1) — 用于评估的解码器层索引。如果为负数,则从末尾开始计数(例如,-1 表示使用最后一层)。这允许在解码器堆栈中进行早期预测,同时仍然训练后面的层。
  • layer_scale (float,可选,默认为 1.0) — 后续解码器层中隐藏维度的缩放因子。用于在评估层之后调整模型容量。
  • max_num_bins (int,可选,默认为 32) — 用于分布引导的边界框精化的最大 bin 数量。 较高的值可以实现更精细的定位,但会增加计算量。
  • reg_scale (float,可选,默认值为 4.0) — 回归分布的缩放因子。控制边界框细化过程的范围和粒度。
  • depth_mult (float,可选,默认为 1.0) — RepNCSPELAN4 层中块数量的乘数。用于在保持模型架构不变的情况下调整模型的深度。
  • top_prob_values (int,可选,默认为 4) — 从每个角点的分布中考虑的前几个概率值的数量。
  • lqe_hidden_dim (int, 可选,默认为 64) — 位置质量估计器(LQE)网络的隐藏层维度大小。
  • lqe_layers (int,可选,默认为 2) — 位置质量估计器 MLP 的层数。
  • decoder_offset_scale (float,可选,默认值为 0.5) — 用于可变形注意力的偏移缩放。
  • decoder_method (str,可选,默认为 "default") — 解码器使用的方法:"default" 或 "discrete"。
  • up (float,可选,默认值为 0.5) — 控制 Weighting Function 的上界。
  • tie_word_embeddings (bool,可选,默认为 True) — 是否根据模型的 tied_weights_keys 映射来绑定权重嵌入。

这是用于存储 DFineModel 配置的类。它根据指定的参数实例化 D Fine 模型,并定义模型架构。使用默认值实例化配置将生成与 ustc-community/dfine-xlarge-coco 类似的配置。

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

DFineModel

class transformers.DFineModel

< >

( config: DFineConfig )

参数

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

RT-DETR 模型(由骨干网络和编码器-解码器组成),输出未经任何头部处理的原始隐藏状态。

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

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

forward

< >

( pixel_values: Tensorpixel_mask: typing.Optional[torch.LongTensor] = Noneencoder_outputs: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: list[dict] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → DFineModelOutput or tuple(torch.Tensor)

参数

  • pixel_values(形状为 (batch_size, num_channels, image_size, image_size) 的 torch.Tensor)— 对应于输入图像的张量。可以使用 image_processor_class 获取像素值。有关详细信息,请参阅 image_processor_class.__call__(processor_class 使用 image_processor_class 来处理图像)。
  • pixel_mask (torch.LongTensor 形状为 (batch_size, height, width), 可选) — 用于避免对填充像素值执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 对于真实的像素(即未被掩码的像素),值为 1,
    • 对于填充像素(即 被屏蔽 的像素),值为 0。

    什么是注意力掩码?

  • encoder_outputs (torch.Tensor, 可选) — 元组由 (last_hidden_state, 可选: hidden_states, 可选: attentions) last_hidden_state 的形状为 (batch_size, sequence_length, hidden_size), 可选) 是编码器最后一层输出的隐藏状态序列。用于解码器的交叉注意力。
  • inputs_embeds (torch.Tensor,形状为 (batch_size, sequence_length, hidden_size),可选) — 可选地,除了传入展平的特征图(backbone + 投影层的输出)外,您还可以选择直接传入图像的展平表示。
  • 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。

返回值

DFineModelOutput 或 tuple(torch.Tensor)

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

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

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

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

  • intermediate_hidden_states(形状为 (batch_size, config.decoder_layers, num_queries, hidden_size) 的 torch.Tensor)— 堆叠的中间隐藏状态(解码器每一层的输出)。

  • intermediate_logits(形状为 (batch_size, config.decoder_layers, sequence_length, config.num_labels) 的 torch.Tensor)— 堆叠的中间 logits(解码器每一层的 logits)。

  • intermediate_reference_points(形状为 (batch_size, config.decoder_layers, num_queries, 4) 的 torch.Tensor)— 堆叠的中间参考点(解码器每一层的参考点)。

  • intermediate_predicted_corners(形状为 (batch_size, config.decoder_layers, num_queries, 4) 的 torch.Tensor)— 堆叠的中间预测角点(解码器每一层预测的角点)。

  • initial_reference_points(形状为 (batch_size, num_queries, 4) 的 torch.Tensor)— 用于第一个解码器层的初始参考点。

  • decoder_hidden_states (tuple[torch.Tensor],可选,在传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为 (batch_size, sequence_length, hidden_size)。

    解码器在每一层输出处的隐藏状态,以及初始嵌入输出。

  • decoder_attentions(tuple[torch.Tensor],可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回)—— 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

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

  • cross_attentions (tuple[torch.Tensor],可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    解码器交叉注意力层在注意力 softmax 之后的注意力权重,用于在交叉注意力头中计算加权平均值。

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

  • encoder_hidden_states (tuple[torch.Tensor],可选,在传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为 (batch_size, sequence_length, hidden_size)。

    编码器在每一层输出处的隐藏状态,以及初始嵌入输出。

  • encoder_attentions(tuple[torch.Tensor],可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回)—— 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

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

  • init_reference_points(形状为 (batch_size, num_queries, 4) 的 torch.Tensor)— 通过 Transformer 解码器传输的初始参考点。

  • enc_topk_logits(形状为 (batch_size, sequence_length, config.num_labels) 的 torch.Tensor)— 预测的边界框分数,其中得分最高的 config.two_stage_num_proposals 个边界框将在编码器阶段被选为区域建议。这是边界框二分类(即前景和背景)的输出。

  • enc_topk_bboxes(形状为 (batch_size, sequence_length, 4) 的 torch.Tensor)— 编码器阶段预测的边界框坐标的 Logits。

  • enc_outputs_class (torch.Tensor,形状为 (batch_size, sequence_length, config.num_labels),可选,当 config.with_box_refine=True 且 config.two_stage=True 时返回) — 预测的边界框分数,其中得分最高的 config.two_stage_num_proposals 个边界框在第一阶段被选为区域建议。边界框二分类(即前景和背景)的输出。

  • enc_outputs_coord_logits (torch.Tensor,形状为 (batch_size, sequence_length, 4),可选,当 config.with_box_refine=True 且 config.two_stage=True 时返回) — 第一阶段中预测的边界框坐标的 logits。

  • denoising_meta_values (dict,可选) — 用于去噪相关值的额外字典。

示例:

>>> from transformers import AutoImageProcessor, DFineModel
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> image_processor = AutoImageProcessor.from_pretrained("PekingU/DFine_r50vd")
>>> model = DFineModel.from_pretrained("PekingU/DFine_r50vd")

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

>>> outputs = model(**inputs)

>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 300, 256]

DFineForObjectDetection

class transformers.DFineForObjectDetection

< >

( config: DFineConfig )

参数

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

RT-DETR 模型(由 backbone 和 encoder-decoder 组成)输出 bounding boxes 和 logits,以便进一步解码为 scores 和 classes。

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

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

forward

< >

( pixel_values: Tensorpixel_mask: typing.Optional[torch.LongTensor] = Noneencoder_outputs: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: list[dict] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → DFineObjectDetectionOutput or tuple(torch.Tensor)

参数

  • pixel_values(形状为 (batch_size, num_channels, image_size, image_size) 的 torch.Tensor)— 对应于输入图像的张量。可以使用 image_processor_class 获取像素值。有关详细信息,请参阅 image_processor_class.__call__(processor_class 使用 image_processor_class 来处理图像)。
  • pixel_mask (torch.LongTensor 形状为 (batch_size, height, width), 可选) — 用于避免对填充像素值执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 对于真实的像素(即未被掩码的像素),值为 1,
    • 对于填充像素(即 被屏蔽 的像素),值为 0。

    什么是注意力掩码?

  • encoder_outputs (torch.Tensor, 可选) — 元组由 (last_hidden_state, 可选: hidden_states, 可选: attentions) last_hidden_state 的形状为 (batch_size, sequence_length, hidden_size), 可选) 是编码器最后一层输出的隐藏状态序列。用于解码器的交叉注意力。
  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • 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。

返回值

DFineObjectDetectionOutput 或 tuple(torch.Tensor)

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

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

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

  • loss (torch.Tensor,形状为 (1,),可选,在提供 labels 时返回)) — 总损失,是类别预测的负对数似然(交叉熵)与边界框损失的线性组合。后者定义为 L1 损失与广义尺度不变 IoU 损失的线性组合。

  • loss_dict (Dict,可选) — 包含各项单独损失的字典。适用于日志记录。

  • logits(形状为 (batch_size, num_queries, num_classes + 1) 的 torch.Tensor)— 所有查询的分类 logits(包括 no-object)。

  • pred_boxes(形状为 (batch_size, num_queries, 4) 的 torch.Tensor)— 所有查询的归一化框坐标,表示为 (center_x, center_y, width, height)。这些值在 [0, 1] 范围内归一化,相对于批次中每张图片的单独尺寸(忽略可能的填充)。您可以使用 ~DFineImageProcessor.post_process_object_detection 来获取未归一化(绝对)的边界框。

  • auxiliary_outputs (list[Dict],可选) — 可选,仅在启用辅助损失(即 config.auxiliary_loss 设置为 True)且提供了标签时返回。它是一个字典列表,包含每个解码器层的上述两个键(logits 和 pred_boxes)。

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

  • intermediate_hidden_states(形状为 (batch_size, config.decoder_layers, num_queries, hidden_size) 的 torch.Tensor)— 堆叠的中间隐藏状态(解码器每一层的输出)。

  • intermediate_logits(形状为 (batch_size, config.decoder_layers, num_queries, config.num_labels) 的 torch.Tensor)— 堆叠的中间 logits(解码器每一层的 logits)。

  • intermediate_reference_points(形状为 (batch_size, config.decoder_layers, num_queries, 4) 的 torch.Tensor)— 堆叠的中间参考点(解码器每一层的参考点)。

  • intermediate_predicted_corners(形状为 (batch_size, config.decoder_layers, num_queries, 4) 的 torch.Tensor)— 堆叠的中间预测角点(解码器每一层预测的角点)。

  • initial_reference_points(形状为 (batch_size, config.decoder_layers, num_queries, 4) 的 torch.Tensor)— 堆叠的初始参考点(解码器每一层的初始参考点)。

  • decoder_hidden_states (tuple[torch.Tensor],可选,在传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为 (batch_size, sequence_length, hidden_size)。

    解码器在每一层输出处的隐藏状态,以及初始嵌入输出。

  • decoder_attentions(tuple[torch.Tensor],可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回)—— 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

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

  • cross_attentions (tuple[torch.Tensor],可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    解码器交叉注意力层在注意力 softmax 之后的注意力权重,用于在交叉注意力头中计算加权平均值。

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

  • encoder_hidden_states (tuple[torch.Tensor],可选,在传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为 (batch_size, sequence_length, hidden_size)。

    编码器在每一层输出处的隐藏状态,以及初始嵌入输出。

  • encoder_attentions(tuple[torch.Tensor],可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回)—— 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

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

  • init_reference_points(形状为 (batch_size, num_queries, 4) 的 torch.Tensor)— 通过 Transformer 解码器传输的初始参考点。

  • enc_topk_logits(形状为 (batch_size, sequence_length, config.num_labels) 的 torch.Tensor,可选,当 config.with_box_refine=True 且 config.two_stage=True 时返回)— 编码器中预测的边界框坐标的 logits。

  • enc_topk_bboxes(形状为 (batch_size, sequence_length, 4) 的 torch.Tensor,可选,当 config.with_box_refine=True 且 config.two_stage=True 时返回) — 编码器中预测的边界框坐标的 Logits。

  • enc_outputs_class (torch.Tensor,形状为 (batch_size, sequence_length, config.num_labels),可选,当 config.with_box_refine=True 且 config.two_stage=True 时返回) — 预测的边界框分数,其中得分最高的 config.two_stage_num_proposals 个边界框在第一阶段被选为区域建议。边界框二分类(即前景和背景)的输出。

  • enc_outputs_coord_logits (torch.Tensor,形状为 (batch_size, sequence_length, 4),可选,当 config.with_box_refine=True 且 config.two_stage=True 时返回) — 第一阶段中预测的边界框坐标的 logits。

  • denoising_meta_values (dict,可选) — 用于去噪相关值的额外字典

示例:

>>> import torch
>>> from transformers.image_utils import load_image
>>> from transformers import AutoImageProcessor, DFineForObjectDetection

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

>>> image_processor = AutoImageProcessor.from_pretrained("ustc-community/dfine-xlarge-coco")
>>> model = DFineForObjectDetection.from_pretrained("ustc-community/dfine-xlarge-coco")

>>> # prepare image for the model
>>> inputs = image_processor(images=image, return_tensors="pt")

>>> # forward pass
>>> outputs = model(**inputs)

>>> logits = outputs.logits
>>> list(logits.shape)
[1, 300, 80]

>>> boxes = outputs.pred_boxes
>>> list(boxes.shape)
[1, 300, 4]

>>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
>>> target_sizes = torch.tensor([image.size[::-1]])
>>> results = image_processor.post_process_object_detection(outputs, threshold=0.9, target_sizes=target_sizes)
>>> result = results[0]  # first image in batch

>>> for score, label, box in zip(result["scores"], result["labels"], result["boxes"]):
...     box = [round(i, 2) for i in box.tolist()]
...     print(
...         f"Detected {model.config.id2label[label.item()]} with confidence "
...         f"{round(score.item(), 3)} at location {box}"
...     )
Detected cat with confidence 0.958 at location [344.49, 23.4, 639.84, 374.27]
Detected cat with confidence 0.956 at location [11.71, 53.52, 316.64, 472.33]
Detected remote with confidence 0.947 at location [40.46, 73.7, 175.62, 117.57]
Detected sofa with confidence 0.918 at location [0.59, 1.88, 640.25, 474.74]
Update on GitHub