# DAB-DETR

## 概述

DAB-DETR 模型由 Shilong Liu、Feng Li、Hao Zhang、Xiao Yang、Xianbiao Qi、Hang Su、Jun Zhu 和 Lei Zhang 在 [DAB-DETR: Dynamic Anchor Boxes are Better Queries for DETR](https://huggingface.co/papers/2201.12329) 中提出。DAB-DETR 是 Conditional DETR 的增强变体。它利用动态更新的锚框来提供参考查询点 (x, y) 和参考锚框尺寸 (w, h)，从而改进交叉注意力计算。这种新方法在仅使用单个 ResNet-50 模型作为骨干网络并训练 50 个 epoch 的情况下，达到了 45.7% 的 AP。

<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/dab_detr_convergence_plot.png"
alt="drawing" width="600"/>

该论文的摘要如下：

*本文提出了一种用于 DETR（DEtection TRansformer）的新型查询构造方法，该方法采用动态锚框，并对 DETR 中查询的作用提供了更深入的理解。这种新的构造方式直接在 Transformer 解码器中使用框坐标作为查询，并逐层动态更新它们。使用框坐标不仅有助于利用显式的位置先验来改善查询与特征之间的相似性，从而消除 DETR 中训练收敛缓慢的问题，还允许我们利用框的宽度和高度信息来调节位置注意力图。这种设计清晰地表明，DETR 中的查询可以以级联方式逐层实现为软 ROI 池化。因此，在相同设置下，该方法在 MS-COCO 基准测试中取得了 DETR 类检测模型中的最佳性能，例如，使用 ResNet50-DC5 作为骨干网络并训练 50 个 epoch 时，AP 达到 45.7%。我们还进行了大量实验以确认我们的分析并验证所提方法的有效性。*

该模型由 [davidhajdu](https://huggingface.co/davidhajdu) 贡献。原始代码可在 [此处](https://github.com/IDEA-Research/DAB-DETR) 找到。

## 如何开始使用模型

使用以下代码开始使用该模型。

```python
import requests
import torch
from PIL import Image

from transformers import AutoImageProcessor, AutoModelForObjectDetection

url = 'http://images.cocodataset.org/val2017/000000039769.jpg'
image = Image.open(requests.get(url, stream=True).raw)

image_processor = AutoImageProcessor.from_pretrained("IDEA-Research/dab-detr-resnet-50")
model = AutoModelForObjectDetection.from_pretrained("IDEA-Research/dab-detr-resnet-50", 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=torch.tensor([image.size[::-1]]), threshold=0.3)

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}")
```

这应该会输出

```text
cat: 0.87 [14.7, 49.39, 320.52, 469.28]
remote: 0.86 [41.08, 72.37, 173.39, 117.2]
cat: 0.86 [344.45, 19.43, 639.85, 367.86]
remote: 0.61 [334.27, 75.93, 367.92, 188.81]
couch: 0.59 [-0.04, 1.34, 639.9, 477.09]
```

还有另外三种实例化 DAB-DETR 模型的方法（取决于你的偏好）：

选项 1：使用整个模型的预训练权重实例化 DAB-DETR

```python
from transformers import DabDetrForObjectDetection

model = DabDetrForObjectDetection.from_pretrained("IDEA-Research/dab-detr-resnet-50", device_map="auto")
```

选项 2：使用随机初始化的权重实例化 Transformer 部分的 DAB-DETR，但使用预训练权重初始化 backbone

```python
from transformers import DabDetrConfig, DabDetrForObjectDetection

config = DabDetrConfig()
model = DabDetrForObjectDetection(config)
```

选项 3：使用随机初始化的权重实例化 DAB-DETR 的骨干网络 + Transformer

```py
config = DabDetrConfig()
model = DabDetrForObjectDetection(config)
```

## DabDetrConfig[[transformers.DabDetrConfig]]

#### transformers.DabDetrConfig[[transformers.DabDetrConfig]]

```python
transformers.DabDetrConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, is_encoder_decoder: bool = True, backbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, num_queries: int = 300, encoder_layers: int = 6, encoder_ffn_dim: int = 2048, encoder_attention_heads: int = 8, decoder_layers: int = 6, decoder_ffn_dim: int = 2048, decoder_attention_heads: int = 8, activation_function: str = 'prelu', hidden_size: int = 256, dropout: float | int = 0.1, attention_dropout: float | int = 0.0, activation_dropout: float | int = 0.0, init_std: float = 0.02, init_xavier_std: float = 1.0, auxiliary_loss: bool = False, dilation: bool = False, class_cost: int = 2, bbox_cost: int = 5, giou_cost: int = 2, cls_loss_coefficient: int = 2, bbox_loss_coefficient: int = 5, giou_loss_coefficient: int = 2, focal_alpha: float = 0.25, temperature_height: int = 20, temperature_width: int = 20, query_dim: int = 4, random_refpoints_xy: bool = False, keep_query_pos: bool = False, num_patterns: int = 0, normalize_before: bool = False, sine_position_embedding_scale: float | None = None, initializer_bias_prior_prob: float | None = None, tie_word_embeddings: bool = True)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dab_detr/configuration_dab_detr.py#L25)

**参数：**

is_encoder_decoder (`bool`，*可选*，默认为 `True`)：模型是否用作编码器/解码器。

backbone_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`，*可选*)：骨干模型的配置。

num_queries (`int`, *可选*，默认为 300)：对象查询的数量，即检测槽位。这是 [DabDetrModel](/docs/transformers/v5.23.0/zh/model_doc/dab-detr#transformers.DabDetrModel) 在单张图像中可检测到的最大对象数量。对于 COCO，我们建议使用 100 个查询。

encoder_layers (`int`，*可选*，默认为 `6`)：Transformer 编码器中的隐藏层数。如果未设置，将使用与 `num_layers` 相同的值。

encoder_ffn_dim (`int`，*可选*，默认为 `2048`)：编码器中“中间”（通常称为前馈）层的维度。

encoder_attention_heads (`int`，*可选*，默认为 `8`)：Transformer 编码器中每个注意力层的注意力头数量。

decoder_layers (`int`，*可选*，默认为 `6`)：Transformer 解码器中的隐藏层数。如果未设置，将使用与 `num_layers` 相同的值。

decoder_ffn_dim (`int`，*可选*，默认为 `2048`)：解码器中“中间”（通常称为前馈）层的维度。

decoder_attention_heads (`int`，*可选*，默认为 `8`)：Transformer 解码器中每个注意力层的注意力头数量。

activation_function (`str`，*可选*，默认为 `prelu`)：解码器中的非线性激活函数（函数或字符串）。例如，`"gelu"`、`"relu"`、`"silu"` 等。

hidden_size (`int`，*可选*，默认为 `256`)：隐藏表示的维度。

dropout (`Union[float, int]`，*可选*，默认为 `0.1`)：所有 dropout 层的比率。

attention_dropout (`Union[float, int]`，*可选*，默认值为 `0.0`)：注意力概率的 dropout 比率。

activation_dropout (`Union[float, int]`，*可选*，默认值为 `0.0`)：全连接层内部激活值的 dropout 比率。

init_std (`float`，*可选*，默认值为 `0.02`)：用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

init_xavier_std (`float`, *可选*，默认为 `1.0`) : 用于交叉注意力权重 Xavier 初始化的缩放因子。

auxiliary_loss (`bool`，*可选*，默认为 `False`)：是否使用辅助解码损失（即每个解码器层的损失）。

dilation (`bool`，*可选*，默认为 `False`)：是否将最后一个卷积块（DC5）中的 stride 替换为 dilation。仅在 `use_timm_backbone` = `True` 时支持。

class_cost (`int`, *可选*，默认为 `2`)：匈牙利匹配代价中分类误差的相对权重。

bbox_cost (`int`, *可选*，默认为 `5`)：匈牙利匹配代价中 L1 边界框误差的相对权重。

giou_cost (`int`, *可选*，默认为 `2`)：匈牙利匹配代价中广义 IoU 损失的相对权重。

cls_loss_coefficient (`int`, *可选*，默认为 `2`)：全景分割损失中分类损失的相对权重。

bbox_loss_coefficient (`int`, *可选*，默认为 `5`)：全景分割损失中 L1 边界框损失的相对权重。

giou_loss_coefficient (`int`, *可选*，默认为 `2`)：全景分割损失中广义 IoU 损失的相对权重。

focal_alpha (`float`, *可选*, 默认为 `0.25`) : 焦点损失中的 Alpha 参数。

temperature_height (`int`, *可选*, 默认为 20) : 用于调节位置注意力（HEIGHT）平坦度的温度参数

temperature_width (`int`, *可选*, 默认值为 20) : 用于调节位置注意力（WIDTH）平坦度的温度参数

query_dim (`int`，*可选*，默认为 4)：查询维度参数表示输出向量的大小。

random_refpoints_xy (`bool`，*可选*，默认为 `False`)：是否使用随机初始化来固定锚框的 x 和 y 坐标。

keep_query_pos (`bool`，*可选*，默认为 `False`)：是否在每个解码器层中，将对象查询投影得到的位置嵌入拼接到原始查询（键）中。

num_patterns (`int`，*可选*，默认为 0)：模式嵌入的数量。

normalize_before (`bool`, *可选*, 默认为 `False`) : 是否在 Encoder 中使用归一化层。

sine_position_embedding_scale (`float`, *可选*, 默认为 'None') : 应用于归一化位置编码的缩放因子。

initializer_bias_prior_prob (`float`, *可选*) : 偏置初始化器用于初始化 `enc_score_head` 和 `class_embed` 偏置的先验概率。如果为 `None`，则在初始化模型权重时，`prior_prob` 的计算方式为 `prior_prob = 1 / (num_labels + 1)`。

tie_word_embeddings (`bool`，*可选*，默认为 `True`)：是否根据模型的 `tied_weights_keys` 映射来绑定权重嵌入。

这是用于存储 Dab Detr 模型配置的类。它根据指定的参数实例化 Dab Detr 模型，并定义模型架构。使用默认值实例化配置将得到与 [IDEA-Research/dab-detr-resnet-50](https://huggingface.co/IDEA-Research/dab-detr-resnet-50) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

示例：

```python
>>> from transformers import DabDetrConfig, DabDetrModel

>>> # Initializing a DAB-DETR IDEA-Research/dab-detr-resnet-50 style configuration
>>> configuration = DabDetrConfig()

>>> # Initializing a model (with random weights) from the IDEA-Research/dab-detr-resnet-50 style configuration
>>> model = DabDetrModel(configuration)

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

## DabDetrModel[[transformers.DabDetrModel]]

#### transformers.DabDetrModel[[transformers.DabDetrModel]]

```python
transformers.DabDetrModel(config: DabDetrConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dab_detr/modeling_dab_detr.py#L1144)

**参数：**

config ([DabDetrConfig](/docs/transformers/v5.23.0/zh/model_doc/dab-detr#transformers.DabDetrConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

裸 DAB-DETR 模型（由骨干网络和编码器-解码器 Transformer 组成），输出原始隐藏状态、中间隐藏状态、参考点和输出坐标，其顶部未添加任何特定的预测头。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.DabDetrModel.forward]]

```python
forward(pixel_values: Tensor, pixel_mask: typing.Optional[torch.LongTensor] = None, decoder_attention_mask: typing.Optional[torch.LongTensor] = None, encoder_outputs: typing.Optional[torch.Tensor] = None, inputs_embeds: typing.Optional[torch.Tensor] = None, decoder_inputs_embeds: typing.Optional[torch.Tensor] = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dab_detr/modeling_dab_detr.py#L1196)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`)：与输入图像对应的张量。可以使用 `image_processor_class` 获取像素值。有关详细信息，请参阅 `image_processor_class.__call__`（`processor_class` 使用 `image_processor_class` 处理图像）。

pixel_mask (`torch.LongTensor`，形状为 `(batch_size, height, width)`，*可选*)：用于避免对填充像素值执行注意力的掩码。掩码值取自 `[0, 1]`：  - 1 表示真实像素（即 **未掩码**）， - 0 表示填充像素（即 **已掩码**）。  [什么是注意力掩码？](../glossary#attention-mask)

decoder_attention_mask (`torch.Tensor`，形状为 `(batch_size, num_queries)`，*可选*)：默认情况下不使用。可用于对对象查询进行掩码处理。

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 + 投影层的输出）外，你还可以选择直接传入图像的展平表示。

decoder_inputs_embeds (`torch.Tensor`，形状为 `(batch_size, num_queries, hidden_size)`，*可选*)：可选地，你可以选择直接传入嵌入表示，而不是用零张量来初始化查询。

output_attentions (`bool`, *可选*) : 是否返回所有注意力层的注意力张量。有关更多详细信息，请参阅返回张量中的 `attentions`。

output_hidden_states (`bool`, *可选*) : 是否返回所有层的隐藏状态。有关更多详细信息，请参阅返回张量中的 `hidden_states`。

return_dict (`bool`, *可选*) : 是否返回 [ModelOutput](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.utils.ModelOutput) 而不是普通元组。

**返回：** `DabDetrModelOutput` 或 `tuple(torch.Tensor)`

`DabDetrModelOutput` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[DabDetrConfig](/docs/transformers/v5.23.0/zh/model_doc/dab-detr#transformers.DabDetrConfig)）和输入。

[DabDetrModel](/docs/transformers/v5.23.0/zh/model_doc/dab-detr#transformers.DabDetrModel) 的 forward 方法重写了 `__call__` 特殊方法。

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

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型解码器最后一层输出的隐藏状态序列。

  如果使用了 `past_key_values`，则仅输出形状为 `(batch_size, 1, hidden_size)` 的序列的最后一个隐藏状态。
- **past_key_values**（`EncoderDecoderCache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）-- 它是一个 [EncoderDecoderCache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.EncoderDecoderCache) 实例。更多详情，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

  包含预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于（参见 `past_key_values` 输入）加速顺序解码。
- **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 之后的注意力权重，用于在自注意力头中计算加权平均值。
- **intermediate_hidden_states**（形状为 `(config.decoder_layers, batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`，*可选*，当 `config.auxiliary_loss=True` 时返回）-- 中间解码器激活值，即每个解码器层的输出，且每个输出都经过了层归一化。
- **reference_points**（形状为 `(config.decoder_layers, batch_size, num_queries, 2 (anchor points))` 的 `torch.Tensor`）-- 参考点（解码器每一层的参考点）。

示例：

```python
>>> from transformers import AutoImageProcessor, AutoModel
>>> 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("IDEA-Research/dab-detr-resnet-50")
>>> model = AutoModel.from_pretrained("IDEA-Research/dab-detr-resnet-50")

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

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

>>> # the last hidden states are the final query embeddings of the Transformer decoder
>>> # these are of shape (batch_size, num_queries, hidden_size)
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 300, 256]
```

## DabDetrForObjectDetection[[transformers.DabDetrForObjectDetection]]

#### transformers.DabDetrForObjectDetection[[transformers.DabDetrForObjectDetection]]

```python
transformers.DabDetrForObjectDetection(config: DabDetrConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dab_detr/modeling_dab_detr.py#L1416)

**参数：**

config ([DabDetrConfig](/docs/transformers/v5.23.0/zh/model_doc/dab-detr#transformers.DabDetrConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

DAB_DETR 模型（由骨干网络和编码器-解码器 Transformer 组成），顶部带有目标检测头，用于 COCO 检测等任务。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.DabDetrForObjectDetection.forward]]

```python
forward(pixel_values: Tensor, pixel_mask: typing.Optional[torch.LongTensor] = None, decoder_attention_mask: typing.Optional[torch.LongTensor] = None, encoder_outputs: typing.Optional[torch.Tensor] = None, inputs_embeds: typing.Optional[torch.Tensor] = None, decoder_inputs_embeds: typing.Optional[torch.Tensor] = None, labels: list[dict] | None = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dab_detr/modeling_dab_detr.py#L1445)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`)：与输入图像对应的张量。可以使用 `image_processor_class` 获取像素值。有关详细信息，请参阅 `image_processor_class.__call__`（`processor_class` 使用 `image_processor_class` 处理图像）。

pixel_mask (`torch.LongTensor`，形状为 `(batch_size, height, width)`，*可选*)：用于避免对填充像素值执行注意力的掩码。掩码值取自 `[0, 1]`：  - 1 表示真实像素（即 **未掩码**）， - 0 表示填充像素（即 **已掩码**）。  [什么是注意力掩码？](../glossary#attention-mask)

decoder_attention_mask (`torch.Tensor`，形状为 `(batch_size, num_queries)`，*可选*)：默认情况下不使用。可用于对对象查询进行掩码处理。

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 + 投影层的输出）外，你还可以选择直接传入图像的展平表示。

decoder_inputs_embeds (`torch.Tensor`，形状为 `(batch_size, num_queries, hidden_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](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.utils.ModelOutput) 而不是普通元组。

**返回：** `DabDetrObjectDetectionOutput` 或 `tuple(torch.Tensor)`

`DabDetrObjectDetectionOutput` 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[DabDetrConfig](/docs/transformers/v5.23.0/zh/model_doc/dab-detr#transformers.DabDetrConfig)）和输入。

[DabDetrForObjectDetection](/docs/transformers/v5.23.0/zh/model_doc/dab-detr#transformers.DabDetrForObjectDetection) 的 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] 范围内归一化，相对于批次中每张图片的单独尺寸（忽略可能的填充）。您可以使用 `~DabDetrImageProcessor.post_process_object_detection` 来获取未归一化的边界框。
- **auxiliary_outputs** (`list[Dict]`, *可选*) -- 可选，仅在启用辅助损失（即 `config.auxiliary_loss` 设置为 `True`）且提供了标签时返回。它是一个字典列表，包含每个解码器层的上述两个键（`logits` 和 `pred_boxes`）。
- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `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 之后的注意力权重，用于在自注意力头中计算加权平均值。

示例：

```python
>>> from transformers import AutoImageProcessor, AutoModelForObjectDetection
>>> 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("IDEA-Research/dab-detr-resnet-50")
>>> model = AutoModelForObjectDetection.from_pretrained("IDEA-Research/dab-detr-resnet-50")

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

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

>>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
>>> target_sizes = torch.tensor([(image.height, image.width)])
>>> results = image_processor.post_process_object_detection(outputs, threshold=0.5, target_sizes=target_sizes)[0]
>>> for score, label, box in zip(results["scores"], results["labels"], results["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 remote with confidence 0.833 at location [38.31, 72.1, 177.63, 118.45]
Detected cat with confidence 0.831 at location [9.2, 51.38, 321.13, 469.0]
Detected cat with confidence 0.804 at location [340.3, 16.85, 642.93, 370.95]
Detected remote with confidence 0.683 at location [334.48, 73.49, 366.37, 190.01]
Detected couch with confidence 0.535 at location [0.52, 1.19, 640.35, 475.1]
```

