# LW-DETR

[LW-DETR](https://huggingface.co/papers/2407.17140) 提出了一种轻量级的 Detection Transformer (DETR) 架构，旨在实时目标检测领域与主流的 YOLO 系列竞争并超越其性能。该架构通过结合最新的 transformer 进展与高效的设计选择，在速度（延迟）和精度（mAP）之间实现了新的最先进平衡。

LW-DETR 架构以其简洁高效的架构为特点：一个普通的 ViT Encoder、一个 Projector 和一个浅层 DETR Decoder。它通过以下核心修改来增强 DETR 架构的效率和速度：
1. 高效 ViT 编码器：采用朴素的 ViT，结合交替的窗口/全局注意力机制以及以窗口为主的组织方式，从而大幅降低注意力计算的复杂度和延迟。
2. 更丰富的输入：聚合来自编码器的多级特征，并使用 C2f Projector（YOLOv8）传递两个尺度的特征（$1/8$ 和 $1/32$）。
3. 更快的解码器：采用浅层 3 层 DETR 解码器，并结合可变形交叉注意力机制，以降低延迟并加快收敛速度。
4. 优化查询：采用混合查询方案，结合可学习的内容查询和生成的空间查询。

您可以在 [AnnaZhang](https://huggingface.co/AnnaZhang) 组织下找到所有可用的 LW DETR 检查点。原始代码可在[此处](https://github.com/Atten4Vis/LW-DETR)找到。

> [!TIP]
> 该模型由 [stevenbucaille](https://huggingface.co/stevenbucaille) 贡献。
>
> 点击右侧边栏中的 LW-DETR 模型，以查看更多将 LW-DETR 应用于不同目标检测任务的示例。

以下示例演示了如何使用 [Pipeline](/docs/transformers/main/zh/main_classes/pipelines#transformers.Pipeline) 和 [AutoModel](/docs/transformers/main/zh/model_doc/auto#transformers.AutoModel) 类执行目标检测。

```python

from transformers import pipeline

pipeline = pipeline(
    "object-detection",
    model="AnnaZhang/lwdetr_small_60e_coco",
    device_map=0
)

pipeline("http://images.cocodataset.org/val2017/000000039769.jpg")
```

```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("AnnaZhang/lwdetr_small_60e_coco")
model = AutoModelForObjectDetection.from_pretrained("AnnaZhang/lwdetr_small_60e_coco", device_map="auto")

# prepare image for the model
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}")
```

## 资源

以下是 Hugging Face 官方和社区（以 🌎 标识）提供的资源列表，可帮助您快速上手 LwDetr。

- 另请参阅：[目标检测任务指南](../tasks/object_detection)。

## LwDetrConfig[[transformers.LwDetrConfig]]

#### transformers.LwDetrConfig[[transformers.LwDetrConfig]]

```python
transformers.LwDetrConfig(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, is_encoder_decoder: bool = False, 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, backbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, projector_scale_factors: list[float] | tuple[float, ...] = (), hidden_expansion: float = 0.5, c2f_num_blocks: int = 3, activation_function: str = 'silu', batch_norm_eps: float = 1e-05, dropout: float | int = 0.0, decoder_ffn_dim: int = 2048, decoder_n_points: int = 4, decoder_layers: int = 3, decoder_self_attention_heads: int = 8, decoder_cross_attention_heads: int = 16, decoder_activation_function: str = 'relu', num_queries: int = 300, attention_bias: bool = True, attention_dropout: float | int = 0.0, activation_dropout: float | int = 0.0, group_detr: int = 13, init_std: float = 0.02, disable_custom_kernels: bool = True, class_cost: int | float = 2, bbox_cost: int | float = 5, giou_cost: int | float = 2, class_loss_coefficient: int | float = 1, dice_loss_coefficient: int | float = 1, bbox_loss_coefficient: int | float = 5, giou_loss_coefficient: int | float = 2, eos_coefficient: float = 0.1, focal_alpha: float = 0.25, auxiliary_loss: bool = True, d_model: int = 256)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/lw_detr/configuration_lw_detr.py#L109)

**参数：**

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

projector_scale_factors (`list[float]`, *可选*, 默认为 `[]`) : 特征金字塔网络的缩放因子。每个缩放因子决定不同层级特征的分辨率。支持的值为 0.5、1.0 和 2.0。

hidden_expansion (`float`, *可选*，默认为 0.5) : 投影层中隐藏维度的扩展因子。

c2f_num_blocks (`int`，*可选*，默认为 3)：C2F 层中的块数。

activation_function (`str`, *可选*, 默认为 `"silu"`) : 投影器中的非线性激活函数。支持的值为 `"silu"`、`"relu"`、`"gelu"`。

batch_norm_eps (`float`，*可选*，默认为 1e-05)：批归一化层的 epsilon 值。

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

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

decoder_n_points (`int`，*可选*，默认为 4)：解码器中每个注意力头在每个特征层级中采样的键数量。

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

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

decoder_cross_attention_heads (`int`，*可选*，默认为 16)：解码器交叉注意力中每个注意力层的注意力头数量。

decoder_activation_function (`str`，*可选*，默认为 `"relu"`)：解码器中的非线性激活函数。支持的值为 `"relu"`、`"silu"`、`"gelu"`。

num_queries (`int`, *可选*，默认为 300)：对象查询的数量，即检测槽位。这是 [LwDetrModel](/docs/transformers/main/zh/model_doc/lw_detr#transformers.LwDetrModel) 在单张图像中可检测到的最大对象数量。

attention_bias (`bool`，*可选*，默认为 `True`)：是否在使用自注意力机制时，在查询、键、值和输出投影层中使用偏置。

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

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

group_detr (`int`, *可选*，默认为 13)：Group DETR 注意力机制中的组数，有助于降低计算复杂度。

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

disable_custom_kernels (`bool`, *可选*, 默认为 `True`) : 禁用自定义 CUDA 和 CPU 内核。此选项对于 ONNX 导出是必需的，因为 PyTorch ONNX 导出不支持自定义内核。

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

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

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

class_loss_coefficient (`float`, *可选*，默认为 1) : 匈牙利匹配代价中分类损失的相对权重。

dice_loss_coefficient (`Union[int, float]`，*可选*，默认为 `1`)：全景分割损失中 Dice 损失的相对权重。

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

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

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

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

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

d_model (`int`，*可选*，默认为 `256`)：编码器层和池化层的大小。

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

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

示例：

```python
>>> from transformers import LwDetrConfig, LwDetrModel

>>> # Initializing a LW-DETR AnnaZhang/lwdetr_small_60e_coco style configuration
>>> configuration = LwDetrConfig()

>>> # Initializing a model (with random weights) from the AnnaZhang/lwdetr_small_60e_coco style configuration
>>> model = LwDetrModel(configuration)

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

## LwDetrViTConfig[[transformers.LwDetrViTConfig]]

#### transformers.LwDetrViTConfig[[transformers.LwDetrViTConfig]]

```python
transformers.LwDetrViTConfig(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, is_encoder_decoder: bool = False, 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, hidden_size: int = 768, num_hidden_layers: int = 12, num_attention_heads: int = 12, mlp_ratio: int = 4, hidden_act: str = 'gelu', dropout_prob: float | int = 0.0, initializer_range: float = 0.02, layer_norm_eps: float = 1e-06, image_size: int | list[int] | tuple[int, int] = 256, pretrain_image_size: int | list[int] | tuple[int, int] = 224, patch_size: int | list[int] | tuple[int, int] = 16, num_channels: int = 3, qkv_bias: bool = True, window_block_indices: list[int] | tuple[int, ...] = (), use_absolute_position_embeddings: bool = True, _out_features: list[str] | None = None, _out_indices: list[int] | None = None, cae_init_values: float = 0.1, num_windows: int = 16)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/lw_detr/configuration_lw_detr.py#L35)

**参数：**

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

num_hidden_layers (`int`，*可选*，默认为 `12`)：Transformer 解码器中的隐藏层数。

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

mlp_ratio (`int`，*可选*，默认为 `4`)：MLP 隐藏维度与嵌入维度的比率。

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

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

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

layer_norm_eps (`float`, *可选*, 默认为 `1e-06`) : 层归一化层使用的 epsilon。

image_size (`Union[int, list[int], tuple[int, int]]`，*可选*，默认为 `256`)：每张图片的尺寸（分辨率）。

pretrain_image_size (`int`, *可选*, 默认为 224) : 预训练期间每张图片的尺寸（分辨率）。

patch_size (`Union[int, list[int], tuple[int, int]]`，*可选*，默认为 `16`)：每个 patch 的大小（分辨率）。

num_channels (`int`，*可选*，默认为 `3`)：输入通道数。

qkv_bias (`bool`，*可选*，默认为 `True`)：是否向查询、键和值添加偏置。

window_block_indices (`list[int]`，*可选*，默认为 `[]`)：应使用窗口注意力而非常规全局自注意力的块索引列表。

use_absolute_position_embeddings (`bool`, *可选*, 默认为 `True`) : 是否向 patch 嵌入中添加绝对位置嵌入。

cae_init_values (`float`, *可选*，默认为 0.1) : 当启用 `use_cae` 时，CAE 参数的初始化值。

num_windows (`int`, *可选*，默认为 16)：基于窗口的注意力机制中的窗口数量。该值必须是一个完全平方数，且图像尺寸必须能被该值的平方根整除。这可以实现高效的窗口优先特征图组织。

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

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

示例：

```python
>>> from transformers import LwDetrViTConfig, LwDetrViTModel

>>> # Initializing a LW-DETR ViT configuration
>>> configuration = LwDetrViTConfig()

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

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

## LwDetrModel[[transformers.LwDetrModel]]

#### transformers.LwDetrModel[[transformers.LwDetrModel]]

```python
transformers.LwDetrModel(config: LwDetrConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/lw_detr/modeling_lw_detr.py#L1202)

**参数：**

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

裸 LW Detr 模型（由骨干网络和解码器 Transformer 组成），输出原始隐藏状态，顶部不附加任何特定头。

该模型继承自 [PreTrainedModel](/docs/transformers/main/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.LwDetrModel.forward]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/lw_detr/modeling_lw_detr.py#L1308)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*)：与输入图像对应的张量。可以使用 [DeformableDetrImageProcessor](/docs/transformers/main/zh/model_doc/deformable_detr#transformers.DeformableDetrImageProcessor) 获取像素值。有关详细信息，请参阅 [DeformableDetrImageProcessor.__call__()](/docs/transformers/main/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（`processor_class` 使用 [DeformableDetrImageProcessor](/docs/transformers/main/zh/model_doc/deformable_detr#transformers.DeformableDetrImageProcessor) 处理图像）。

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

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

`LwDetrModelOutput` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[LwDetrConfig](/docs/transformers/main/zh/model_doc/lw_detr#transformers.LwDetrConfig)）和输入。

[LwDetrModel](/docs/transformers/main/zh/model_doc/lw_detr#transformers.LwDetrModel) 的 forward 方法重写了 `__call__` 特殊方法。

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

- **init_reference_points**（形状为 `(batch_size, num_queries, 4)` 的 `torch.Tensor`）-- 通过 Transformer 解码器发送的初始参考点。
- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`，*可选*）-- 模型最后一层输出的隐藏状态序列。
- **intermediate_hidden_states**（形状为 `(batch_size, config.decoder_layers, num_queries, hidden_size)` 的 `torch.Tensor`）-- 堆叠的中间隐藏状态（解码器每一层的输出）。
- **intermediate_reference_points**（形状为 `(batch_size, config.decoder_layers, num_queries, 4)` 的 `torch.Tensor`）-- 堆叠的中间参考点（解码器每一层的参考点）。
- **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。
- **hidden_states** (`tuple[torch.Tensor, ...]`，*可选*，当传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层输出的一个张量，以及每个层输出的一个张量），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **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 之后的注意力权重，用于在交叉注意力头中计算加权平均值。

示例：

```python
>>> from transformers import AutoImageProcessor, DeformableDetrModel
>>> 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("AnnaZhang/lwdetr_small_60e_coco")
>>> model = DeformableDetrModel.from_pretrained("AnnaZhang/lwdetr_small_60e_coco")

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

## LwDetrForObjectDetection[[transformers.LwDetrForObjectDetection]]

#### transformers.LwDetrForObjectDetection[[transformers.LwDetrForObjectDetection]]

```python
transformers.LwDetrForObjectDetection(config: LwDetrConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/lw_detr/modeling_lw_detr.py#L1538)

**参数：**

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

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

该模型继承自 [PreTrainedModel](/docs/transformers/main/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.LwDetrForObjectDetection.forward]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/lw_detr/modeling_lw_detr.py#L1552)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*)：与输入图像对应的张量。可以使用 [DeformableDetrImageProcessor](/docs/transformers/main/zh/model_doc/deformable_detr#transformers.DeformableDetrImageProcessor) 获取像素值。有关详细信息，请参阅 [DeformableDetrImageProcessor.__call__()](/docs/transformers/main/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（`processor_class` 使用 [DeformableDetrImageProcessor](/docs/transformers/main/zh/model_doc/deformable_detr#transformers.DeformableDetrImageProcessor) 处理图像）。

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

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

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

`LwDetrObjectDetectionOutput` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[LwDetrConfig](/docs/transformers/main/zh/model_doc/lw_detr#transformers.LwDetrConfig)）和输入。

[LwDetrForObjectDetection](/docs/transformers/main/zh/model_doc/lw_detr#transformers.LwDetrForObjectDetection) 的 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] 范围内归一化，相对于批次中每张图片的单独尺寸（忽略可能的填充）。您可以使用 `~DeformableDetrProcessor.post_process_object_detection` 来获取未归一化的边界框。
- **auxiliary_outputs** (`list[Dict]`, *可选*) -- 可选，仅在启用辅助损失（即 `config.auxiliary_loss` 设置为 `True`）且提供了标签时返回。它是一个字典列表，包含每个解码器层的上述两个键（`logits` 和 `pred_boxes`）。
- **init_reference_points**（形状为 `(batch_size, num_queries, 4)` 的 `torch.Tensor`）-- 通过 Transformer 解码器发送的初始参考点。
- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`，*可选*）-- 模型最后一层输出的隐藏状态序列。
- **intermediate_hidden_states**（形状为 `(batch_size, config.decoder_layers, num_queries, hidden_size)` 的 `torch.Tensor`）-- 堆叠的中间隐藏状态（解码器每一层的输出）。
- **intermediate_reference_points**（形状为 `(batch_size, config.decoder_layers, num_queries, 4)` 的 `torch.Tensor`）-- 堆叠的中间参考点（解码器每一层的参考点）。
- **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。
- **hidden_states** (`tuple[torch.Tensor, ...]`，*可选*，当传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层输出的一个张量，以及每个层输出的一个张量），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **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 之后的注意力权重，用于在交叉注意力头中计算加权平均值。

示例：

```python
>>> from transformers import AutoImageProcessor, LwDetrForObjectDetection
>>> 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("AnnaZhang/lwdetr_small_60e_coco")
>>> model = LwDetrForObjectDetection.from_pretrained("AnnaZhang/lwdetr_small_60e_coco")

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

>>> # 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.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 cat with confidence 0.8 at location [16.5, 52.84, 318.25, 470.78]
Detected cat with confidence 0.789 at location [342.19, 24.3, 640.02, 372.25]
Detected remote with confidence 0.633 at location [40.79, 72.78, 176.76, 117.25]
```

## LwDetrViTBackbone[[transformers.LwDetrViTBackbone]]

#### transformers.LwDetrViTBackbone[[transformers.LwDetrViTBackbone]]

```python
transformers.LwDetrViTBackbone(config: LwDetrViTConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/lw_detr/modeling_lw_detr.py#L341)

**参数：**

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

Lw Detr 骨干网络。

该模型继承自 [PreTrainedModel](/docs/transformers/main/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.LwDetrViTBackbone.forward]]

```python
forward(pixel_values: Tensor, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/lw_detr/modeling_lw_detr.py#L355)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`)：与输入图像对应的张量。可以使用 [DeformableDetrImageProcessor](/docs/transformers/main/zh/model_doc/deformable_detr#transformers.DeformableDetrImageProcessor) 获取像素值。有关详细信息，请参阅 [DeformableDetrImageProcessor.__call__()](/docs/transformers/main/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（`processor_class` 使用 [DeformableDetrImageProcessor](/docs/transformers/main/zh/model_doc/deformable_detr#transformers.DeformableDetrImageProcessor) 处理图像）。

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

`BackboneOutput` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[LwDetrConfig](/docs/transformers/main/zh/model_doc/lw_detr#transformers.LwDetrConfig)）和输入。

[LwDetrViTBackbone](/docs/transformers/main/zh/model_doc/lw_detr#transformers.LwDetrViTBackbone) 的 forward 方法重写了 `__call__` 特殊方法。

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

- **feature_maps**（形状为 `(batch_size, num_channels, height, width)` 的 `tuple(torch.Tensor)`）-- 各阶段的特征图。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（包含嵌入层的输出以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)` 或 `(batch_size, num_channels, height, width)`，具体取决于骨干网络。

  模型在每个阶段输出处的隐藏状态，以及初始嵌入输出。
- **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 LwDetrViTConfig, LwDetrViTBackbone
>>> import torch

>>> config = LwDetrViTConfig()
>>> model = LwDetrViTBackbone(config)

>>> pixel_values = torch.randn(1, 3, 224, 224)

>>> with torch.no_grad():
...     outputs = model(pixel_values)

>>> feature_maps = outputs.feature_maps
>>> list(feature_maps[-1].shape)
[1, 768, 14, 14]
```

