# RT-DETRv2

## 概述

RT-DETRv2 模型由 Wenyu Lv、Yian Zhao、Qinyao Chang、Kui Huang、Guanzhong Wang 和 Yi Liu 在 [RT-DETRv2: Improved Baseline with Bag-of-Freebies for Real-Time Detection Transformer](https://huggingface.co/papers/2407.17140) 中提出。

RT-DETRv2 通过引入选择性多尺度特征提取、用于提升更广泛部署兼容性的离散采样算子，以及动态数据增强和尺度自适应超参数等改进的训练策略，对 RT-DETR 进行了优化。这些改动在保持实时性能的同时，增强了灵活性和实用性。

该论文的摘要如下：

*本报告提出了 RT-DETRv2，一种改进的实时检测 Transformer（RT-DETR）。RT-DETRv2 基于此前最先进的实时检测器 RT-DETR，引入了一系列“免费午餐”（bag-of-freebies）以提升灵活性和实用性，并优化了训练策略以实现性能增强。为提高灵活性，我们建议在可变形注意力（deformable attention）中为不同尺度的特征设置不同数量的采样点，从而使解码器能够进行选择性多尺度特征提取。为增强实用性，我们提出了一种可选的离散采样算子，用于替代 RT-DETR 相较于 YOLOs 特有的 grid_sample 算子。这消除了 DETR 通常伴随的部署限制。在训练策略方面，我们提出了动态数据增强和尺度自适应超参数定制，以在不损失速度的前提下提升性能。*

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

## 使用技巧

RT-DETR 的第二个版本改进了解码器在图像中定位对象的方式。

- **更好的采样** – 调整偏移量，使模型关注正确的区域
- **灵活注意力** – 可使用平滑（双线性）或固定（离散）采样
- **优化处理** – 改进注意力权重混合信息的方式

该模型旨在与对应的 ImageProcessor 配合使用，处理尺寸为 640x640 的图像。调整为其他尺寸通常会导致性能下降。

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

from transformers import RTDetrImageProcessor, RTDetrV2ForObjectDetection

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

image_processor = RTDetrImageProcessor.from_pretrained("PekingU/rtdetr_v2_r18vd")
model = RTDetrV2ForObjectDetection.from_pretrained("PekingU/rtdetr_v2_r18vd", 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.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.97 [341.14, 25.11, 639.98, 372.89]
cat: 0.96 [12.78, 56.35, 317.67, 471.34]
remote: 0.95 [39.96, 73.12, 175.65, 117.44]
sofa: 0.86 [-0.11, 2.97, 639.89, 473.62]
sofa: 0.82 [-0.12, 1.78, 639.87, 473.52]
remote: 0.79 [333.65, 76.38, 370.69, 187.48]
```

## 资源

一份来自 Hugging Face 官方和社区（以 🌎 标识）的资源列表，帮助你快速上手 RT-DETRv2。

- 另请参阅：[目标检测任务指南](../tasks/object_detection)。
- 用于在自定义数据集上对 RT-DETRv2 进行[推理](https://github.com/qubvel/transformers-notebooks/blob/main/notebooks/RT_DETR_v2_inference.ipynb)和[微调](https://github.com/qubvel/transformers-notebooks/blob/main/notebooks/RT_DETR_v2_finetune_on_a_custom_dataset.ipynb)的 Notebook（🌎）。

## RTDetrV2Config[[transformers.RTDetrV2Config]]

#### transformers.RTDetrV2Config[[transformers.RTDetrV2Config]]

```python
transformers.RTDetrV2Config(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, initializer_range: float = 0.01, initializer_bias_prior_prob: float | None = None, layer_norm_eps: float = 1e-05, batch_norm_eps: float = 1e-05, backbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, freeze_backbone_batch_norms: bool = True, encoder_hidden_dim: int = 256, encoder_in_channels: list[int] | tuple[int, ...] = (512, 1024, 2048), feat_strides: list[int] | tuple[int, ...] = (8, 16, 32), encoder_layers: int = 1, encoder_ffn_dim: int = 1024, encoder_attention_heads: int = 8, dropout: float | int = 0.0, activation_dropout: float | int = 0.0, encode_proj_layers: list[int] | tuple[int, ...] = (2,), positional_encoding_temperature: int = 10000, encoder_activation_function: str = 'gelu', activation_function: str = 'silu', eval_size: int | None = None, normalize_before: bool = False, hidden_expansion: float = 1.0, d_model: int = 256, num_queries: int = 300, decoder_in_channels: list[int] | tuple[int, ...] = (256, 256, 256), decoder_ffn_dim: int = 1024, num_feature_levels: int = 3, decoder_n_points: int = 4, decoder_layers: int = 6, decoder_attention_heads: int = 8, decoder_activation_function: str = 'relu', attention_dropout: float | int = 0.0, num_denoising: int = 100, label_noise_ratio: float = 0.5, box_noise_scale: float = 1.0, learn_initial_query: bool = False, anchor_image_size: int | list[int] | None = None, with_box_refine: bool = True, matcher_alpha: float = 0.25, matcher_gamma: float = 2.0, matcher_class_cost: float = 2.0, matcher_bbox_cost: float = 5.0, matcher_giou_cost: float = 2.0, use_focal_loss: bool = True, auxiliary_loss: bool = True, focal_loss_alpha: float = 0.75, focal_loss_gamma: float = 2.0, weight_loss_vfl: float = 1.0, weight_loss_bbox: float = 5.0, weight_loss_giou: float = 2.0, eos_coefficient: float = 0.0001, decoder_n_levels: int = 3, decoder_offset_scale: float = 0.5, decoder_method: str = 'default', tie_word_embeddings: bool = True)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/rt_detr_v2/configuration_rt_detr_v2.py#L29)

**参数：**

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"` 和 `"gelu_new"`。

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)：匈牙利匹配器使用的参数 alpha。

matcher_gamma (`float`, *可选*, 默认值为 2.0) : 匈牙利匹配器使用的参数 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`) : 指示是否应使用焦点损失的参数。

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

focal_loss_alpha (`float`, *可选*, 默认值为 0.75) : 用于计算焦点损失的参数 alpha。

focal_loss_gamma (`float`, *可选*, 默认值为 2.0) : 用于计算焦点损失的参数 gamma。

weight_loss_vfl (`float`, *可选*, 默认值为 1.0) : 变焦损失在目标检测损失中的相对权重。

weight_loss_bbox (`float`, *可选*, 默认值为 5.0) : 目标检测损失中 L1 边界框损失的相对权重。

weight_loss_giou (`float`, *可选*, 默认值为 2.0) : 在目标检测损失中，广义 IoU 损失的相对权重。

eos_coefficient (`float`, *可选*, 默认为 `0.0001`) : 目标检测损失中“无目标”类别的相对分类权重。

decoder_n_levels (`int`，*可选*，默认为 3)：解码器使用的特征层数。

decoder_offset_scale (`float`, *可选*，默认为 0.5)：应用于解码器中注意力偏移的缩放因子。

decoder_method (`str`，*可选*，默认为 `"default"`)：解码器使用的方法：`"default"` 或 `"discrete"`。

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

这是用于存储 RTDetrV2Model 配置的类。它根据指定的参数实例化 Rt Detr V2 模型，并定义模型架构。使用默认值实例化配置将得到与 [PekingU/rtdetr_r18vd](https://huggingface.co/PekingU/rtdetr_r18vd) 类似的配置。

配置对象继承自 [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 RTDetrV2Config, RTDetrV2Model

>>> # Initializing a RT-DETR configuration
>>> configuration = RTDetrV2Config()

>>> # Initializing a model (with random weights) from the configuration
>>> model = RTDetrV2Model(configuration)

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

## RTDetrV2Model[[transformers.RTDetrV2Model]]

#### transformers.RTDetrV2Model[[transformers.RTDetrV2Model]]

```python
transformers.RTDetrV2Model(config: RTDetrV2Config)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/rt_detr_v2/modeling_rt_detr_v2.py#L1343)

**参数：**

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

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

该模型继承自 [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.RTDetrV2Model.forward]]

```python
forward(pixel_values: Tensor, pixel_mask: typing.Optional[torch.LongTensor] = None, encoder_outputs: typing.Optional[torch.Tensor] = None, inputs_embeds: typing.Optional[torch.Tensor] = None, labels: list[dict] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/rt_detr_v2/modeling_rt_detr_v2.py#L1462)

**参数：**

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)

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`。

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

`RTDetrV2ModelOutput` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（`None`）和输入。

[RTDetrV2Model](/docs/transformers/v5.23.0/zh/model_doc/rt_detr_v2#transformers.RTDetrV2Model) 的 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`, *可选*) -- 用于去噪相关值的额外字典。

示例：

```python
>>> from transformers import AutoImageProcessor, RTDetrV2Model
>>> 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/RTDetrV2_r50vd")
>>> model = RTDetrV2Model.from_pretrained("PekingU/RTDetrV2_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]
```

## RTDetrV2ForObjectDetection[[transformers.RTDetrV2ForObjectDetection]]

#### transformers.RTDetrV2ForObjectDetection[[transformers.RTDetrV2ForObjectDetection]]

```python
transformers.RTDetrV2ForObjectDetection(config: RTDetrV2Config)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/rt_detr_v2/modeling_rt_detr_v2.py#L1765)

**参数：**

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

RT-DETR 模型（由骨干网络和编码器-解码器组成）输出边界框和 logits，以便进一步解码为分数和类别。

该模型继承自 [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.RTDetrV2ForObjectDetection.forward]]

```python
forward(pixel_values: Tensor, pixel_mask: typing.Optional[torch.LongTensor] = None, encoder_outputs: typing.Optional[torch.Tensor] = None, inputs_embeds: typing.Optional[torch.Tensor] = None, labels: list[dict] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/rt_detr_v2/modeling_rt_detr_v2.py#L1798)

**参数：**

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)

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`。

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

`RTDetrV2ObjectDetectionOutput` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（`None`）和输入。

[RTDetrV2ForObjectDetection](/docs/transformers/v5.23.0/zh/model_doc/rt_detr_v2#transformers.RTDetrV2ForObjectDetection) 的 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] 范围内归一化，相对于批次中每张图片的单独尺寸（忽略可能的填充）。您可以使用 `~RTDetrV2ImageProcessor.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`, *可选*) -- 用于去噪相关值的额外字典

示例：

```python
>>> from transformers import RTDetrV2ImageProcessor, RTDetrV2ForObjectDetection
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> import torch

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

>>> image_processor = RTDetrV2ImageProcessor.from_pretrained("PekingU/RTDetrV2_r50vd")
>>> model = RTDetrV2ForObjectDetection.from_pretrained("PekingU/RTDetrV2_r50vd")

>>> # 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)[
...     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 sofa with confidence 0.97 at location [0.14, 0.38, 640.13, 476.21]
Detected cat with confidence 0.96 at location [343.38, 24.28, 640.14, 371.5]
Detected cat with confidence 0.958 at location [13.23, 54.18, 318.98, 472.22]
Detected remote with confidence 0.951 at location [40.11, 73.44, 175.96, 118.48]
Detected remote with confidence 0.924 at location [333.73, 76.58, 369.97, 186.99]
```

