Transformers documentation

RF-DETR

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-07-24 在 HF papers 上发布,并于 2026-05-07 贡献至 Hugging Face Transformers。

PyTorch

RF-DETR

RF-DETR 提出了一种感受野检测 Transformer(DETR)架构,旨在与主流的 YOLO 系列竞争并在实时目标检测中超越它。该架构通过结合最新的 Transformer 进展与高效的设计选择,在速度(延迟)和精度(mAP)之间实现了新的最先进平衡。

RF-DETR 架构以其简洁高效的架构为特点:一个 DINOv2 Backbone、一个 Projector 以及一个浅层 DETR Decoder。 它通过以下核心修改来增强 DETR 架构的效率和速度:

  1. DINOv2 骨干网络:使用强大的 DINOv2 骨干网络进行鲁棒的特征提取。
  2. Group DETR 训练:在训练过程中使用 Group-Wise One-to-Many Assignment 以加速收敛。
  3. 更丰富的输入:聚合骨干网络的多层级特征,并使用 C2f Projector(与 YOLOv8 类似)来传递多尺度特征。
  4. 更快的解码器:采用浅层 3 层 DETR 解码器,并结合可变形交叉注意力机制,以降低延迟。
  5. 优化查询:采用混合查询方案,结合可学习的内容查询和生成的空间查询。

您可以在 Roboflow 组织下找到所有可用的 RF-DETR 检查点。 原始代码可在此处找到。

得益于权重转换映射,RfDetr 兼容来自原始 rf-detr 库的模型,以及使用 Roboflow 平台训练的模型。这意味着您可以使用 Roboflow 平台训练模型,并在 transformers 中使用 RfDetr 导入权重,从而在任何地方部署您的模型。

点击右侧边栏中的 RF-DETR 模型,以查看更多将 RF-DETR 应用于不同目标检测任务的示例。

以下示例演示了如何使用 Pipeline 和 AutoModel 类执行目标检测。

Pipeline
AutoModel
from transformers import pipeline
import torch

pipeline = pipeline("object-detection", model="Roboflow/rf-detr-medium", device_map="auto")

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

使用监督信号可视化结果

你可以使用 supervision 库来可视化检测和分割结果。使用 pip install supervision 进行安装。

目标检测
实例分割
from transformers import AutoImageProcessor, AutoModelForObjectDetection
from PIL import Image
import supervision as sv

from huggingface_hub.utils import httpx
from io import BytesIO
import torch

url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(BytesIO(httpx.get(url).content))

image_processor = AutoImageProcessor.from_pretrained("Roboflow/rf-detr-medium")
model = AutoModelForObjectDetection.from_pretrained("Roboflow/rf-detr-medium", 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.3
)[0]

detections = sv.Detections.from_transformers(
    transformers_results=results, id2label=model.config.id2label
)

box_annotator = sv.BoxAnnotator()
label_annotator = sv.LabelAnnotator()

annotated_image = image.copy()
annotated_image = box_annotator.annotate(annotated_image, detections)
annotated_image = label_annotator.annotate(annotated_image, detections)

sv.plot_image(annotated_image)

资源

RfDetrConfig

类 transformers.RfDetrConfig

< >

( 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 = 0is_encoder_decoder: bool = Falseid2label: 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 = Nonebackbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonehidden_expansion: float = 0.5c2f_num_blocks: int = 3activation_function: str = 'silu'dropout: float = 0.1decoder_ffn_dim: int = 2048decoder_n_points: int = 4decoder_layers: int = 3decoder_self_attention_heads: int = 8decoder_cross_attention_heads: int = 16decoder_activation_function: str = 'relu'num_queries: int = 300attention_bias: bool = Trueattention_dropout: float | int = 0.0activation_dropout: float | int = 0.0group_detr: int = 13init_std: float = 0.02disable_custom_kernels: bool = Trueclass_cost: int | float = 2bbox_cost: int | float = 5giou_cost: int | float = 2class_loss_coefficient: int | float = 1dice_loss_coefficient: int | float = 1bbox_loss_coefficient: int | float = 5giou_loss_coefficient: int | float = 2eos_coefficient: float = 0.1focal_alpha: float = 0.25auxiliary_loss: bool = Trued_model: int = 256layer_norm_eps: float = 1e-05num_feature_levels: int = 1mask_loss_coefficient: int | float = 1mask_point_sample_ratio: int = 16mask_downsample_ratio: int = 4mask_class_loss_coefficient: int | float = 5.0mask_dice_loss_coefficient: int | float = 5.0segmentation_head_activation_function: str = 'gelu'intermediate_size: int = 1024 )

参数

  • backbone_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 主干模型的配置。
  • hidden_expansion (float,可选,默认为 0.5) — 投影层中隐藏维度的扩展因子。
  • c2f_num_blocks (int,可选,默认为 3) — C2F 层中的块数。
  • activation_function (str,可选,默认为 "silu") — 投影器中使用的非线性激活函数。支持的取值为 "silu"、"relu"、"gelu"。
  • dropout (float,可选,默认值为 0.1) — 所有 dropout 层的比率。
  • decoder_ffn_dim (int,可选,默认为 2048) — 解码器中“中间”(通常称为前馈)层的维度。
  • decoder_n_points (int,可选,默认为 4) — 解码器中每个注意力头在每个特征层级上采样的键数量。
  • decoder_layers (int, 可选,默认为 3) — Transformer 中解码器层的数量。
  • decoder_self_attention_heads (int,可选,默认为 8) — 解码器自注意力中每个注意力层的注意力头数量。
  • decoder_cross_attention_heads (int, 可选,默认为 16) — 解码器交叉注意力中每个注意力层的注意力头数量。
  • decoder_activation_function (str,可选,默认为 "relu") — 解码器中的非线性激活函数。支持的值为 "relu"、"silu"、"gelu"。
  • num_queries (int, 可选,默认为 300) — 对象查询的数量,即检测槽位。这是 RfDetrModel 在单张图像中可检测到的最大对象数量。
  • 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 (float,可选,默认为 1) — 目标检测损失中 DICE/F-1 损失的相对权重。
  • bbox_loss_coefficient (float,可选,默认值为 5) — 在目标检测损失中,L1 边界框损失的相对权重。
  • giou_loss_coefficient (float,可选,默认值为 2) — 目标检测损失中广义 IoU 损失的相对权重。
  • eos_coefficient (float,可选,默认为 0.1) — 目标检测损失中“无目标”类别的相对分类权重。
  • focal_alpha (float,可选,默认为 0.25) — Focal loss 中的 Alpha 参数。
  • auxiliary_loss (bool,可选,默认为 True) — 是否使用辅助解码损失(即每个解码器层的损失)。
  • d_model (int,可选,默认为 256) — 编码器层和池化层的维度大小。
  • layer_norm_eps (float,可选,默认为 1e-05) — 层归一化层所使用的 epsilon 值。
  • num_feature_levels (int, 可选,默认为 1) — 多尺度可变形注意力中使用的特征层数。
  • mask_loss_coefficient (float,可选,默认为 1) — 实例分割掩码损失中 Focal loss 的相对权重。
  • mask_point_sample_ratio (int,可选,默认值为 16) — 用于计算掩码损失的采样点比例。
  • mask_downsample_ratio (int,可选,默认为 4) — 分割掩码相对于输入图像分辨率的下采样比例。
  • mask_class_loss_coefficient (float,可选,默认值为 5.0) — 实例分割损失中 Focal loss 的相对权重。
  • mask_dice_loss_coefficient (float, 可选,默认值为 5.0) — 实例分割损失中 DICE/F-1 损失的相对权重。
  • segmentation_head_activation_function (str,可选,默认为 "gelu") — 分割头中的非线性激活函数。支持的值为 "relu"、"silu"、"gelu"。
  • intermediate_size (int,可选,默认为 1024) — MLP 表示的维度。

这是用于存储 RfDetrModel 配置的类。它根据指定的参数实例化 Rf Detr 模型,并定义模型架构。使用默认值实例化配置将生成与 Roboflow/rf-detr-base 类似的配置。

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

示例:

>>> from transformers import RfDetrConfig, RfDetrModel

>>> # Initializing a RF-DETR roboflow/rf-detr-base style configuration
>>> configuration = RfDetrConfig()

>>> # Initializing a model (with random weights) from the Roboflow/rf-detr-base style configuration
>>> model = RfDetrModel(configuration)

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

RfDetrDinov2Config

类 transformers.RfDetrDinov2Config

< >

( 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 = 0is_encoder_decoder: bool = Falseid2label: 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 = Nonehidden_size: int = 768num_hidden_layers: int = 12num_attention_heads: int = 12mlp_ratio: int = 4hidden_act: str = 'gelu'hidden_dropout_prob: float | int = 0.0attention_probs_dropout_prob: float | int = 0.0initializer_range: float = 0.02layer_norm_eps: float = 1e-06image_size: int | list[int] | tuple[int, int] = 224patch_size: int | list[int] | tuple[int, int] = 14num_channels: int = 3qkv_bias: bool = Truelayerscale_value: float = 1.0drop_path_rate: float | int = 0.0use_swiglu_ffn: bool = False_out_features: list[str] | None = None_out_indices: list[int] | None = Noneapply_layernorm: bool = Truereshape_hidden_states: bool = Trueuse_mask_token: bool = Truenum_windows: int = 4 )

参数

  • 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" 等。
  • hidden_dropout_prob (Union[float, int],可选,默认为 0.0) — 嵌入层、编码器和池化层中所有全连接层的 dropout 概率。
  • attention_probs_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]],可选,默认为 224) — 每张图片的尺寸(分辨率)。
  • patch_size (Union[int, list[int], tuple[int, int]],可选,默认为 14) — 每个 patch 的大小(分辨率)。
  • num_channels (int,可选,默认为 3) — 输入通道的数量。
  • qkv_bias (bool,可选,默认为 True) — 是否向查询、键和值添加偏置。
  • layerscale_value (float,可选,默认为 1.0) — 用于 layer scale 的初始值。
  • drop_path_rate (float,可选,默认值为 0.0) — 每个样本的随机深度率(当应用于残差层的主路径时)。
  • use_swiglu_ffn (bool,可选,默认为 False) — 是否使用 SwiGLU 前馈神经网络。
  • apply_layernorm (bool,可选,默认为 True) — 当模型用作 backbone 时,是否对特征图应用层归一化。
  • reshape_hidden_states (bool,可选,默认为 True) — 当模型用作骨干网络时,是否将特征图重塑为形状为 (batch_size, d_model, height, width) 的 4D 张量。如果为 False,则特征图将是形状为 (batch_size, seq_len, d_model) 的 3D 张量。
  • use_mask_token (bool,可选,默认为 True) — 是否在嵌入中使用 mask_token。
  • num_windows (int,可选,默认为 4) — 用于窗口注意力的窗口数量。如果为 1,则不使用窗口注意力。

这是用于存储 RfDetrModel 配置的类。它根据指定的参数实例化 Rf Detr 模型,并定义模型架构。使用默认值实例化配置将生成与 Roboflow/rf-detr-base 类似的配置。

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

示例:

>>> from transformers import RfDetrDinov2Config, RfDetrDinov2Backbone

>>> # Initializing a RfDetrDinov2 base style configuration
>>> configuration = RfDetrDinov2Config()

>>> # Initializing a model (with random weights) from the base style configuration
>>> model = RfDetrDinov2Backbone(configuration)

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

RfDetrImageProcessor

class transformers.RfDetrImageProcessor

< >

( **kwargs: *<class 'transformers.models.rf_detr.image_processing_rf_detr.RfDetrImageProcessorKwargs'> )

参数

  • do_convert_rgb (bool,kwargs,可选) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选,默认为 True) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为 {'shortest_edge' -- 800, 'longest_edge': 1333}): 描述输入到模型的最大尺寸。
  • default_to_square (bool,kwargs,可选,默认为 False) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为 2) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时才会生效。
  • do_rescale (bool,kwargs,可选,默认为 True) — 是否对图像进行重新缩放。
  • rescale_factor (float,kwargs,可选,默认为 0.00392156862745098) — 当 do_rescale 设置为 True 时,用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选,默认为 True) — 是否对图像进行归一化。
  • image_mean (Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为 [0.485, 0.456, 0.406]) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为 [0.229, 0.224, 0.225]) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时生效。
  • do_pad (bool,kwargs,可选,默认为 True) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的 {"height": int, "width" int} 尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供 pad_size,图像将被填充到批次中最大的高度和宽度。仅在 do_pad=True. 时应用。
  • do_center_crop (bool,kwargs,可选) — 是否对图像进行中心裁剪。
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持 ChannelDimension.FIRST。为兼容旧版处理器而添加。
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first" 或 ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。
    • "channels_last" 或 ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。
    • "none" 或 ChannelDimension.NONE:图像为 (height, width) 格式。
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • format (str, kwargs, optional, 默认为 AnnotationFormat.COCO_DETECTION) — 标注的数据格式。取值为 “coco_detection” 或 “coco_panoptic” 之一。
  • do_convert_annotations (bool, kwargs, 可选,默认为 True) — 控制是否将标注转换为 RF_DETR 模型所期望的格式。将边界框转换为 (center_x, center_y, width, height) 格式,且取值范围为 [0, 1]。可通过 preprocess 方法中的 do_convert_annotations 参数进行覆盖。

构建一个 RfDetrImageProcessor 图像处理器。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]annotations: dict[str, int | str | list[dict]] | list[dict[str, int | str | list[dict]]] | None = Nonereturn_segmentation_masks: bool | None = Nonemasks_path: str | pathlib.Path | None = None**kwargs: *<class 'transformers.models.rf_detr.image_processing_rf_detr.RfDetrImageProcessorKwargs'> ) → ~image_processing_base.BatchFeature

参数

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 要预处理的图像。期望输入单张图像或一批图像,其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置 do_rescale=False。
  • annotations(AnnotationType 或 list[AnnotationType],可选)— 根据应用于图像的填充进行转换的注释。
  • return_segmentation_masks (bool,可选,默认为 self.return_segmentation_masks) — 是否返回分割掩码。
  • masks_path (str 或 pathlib.Path,可选) — 包含分割掩码的目录路径。
  • do_convert_rgb (bool,kwargs,可选) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。
  • default_to_square (bool, kwargs, 可选) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时生效。
  • do_rescale (bool,kwargs,可选) — 是否对图像进行重新缩放。
  • rescale_factor (float, kwargs, 可选) — 如果 do_rescale 设置为 True,则用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选) — 是否对图像进行归一化。
  • image_mean (Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时生效。
  • do_pad (bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的 {"height": int, "width" int} 尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供 pad_size,图像将被填充到批次中最大的高度和宽度。仅在 do_pad=True. 时应用。
  • do_center_crop (bool,kwargs,可选) — 是否对图像进行中心裁剪。
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持 ChannelDimension.FIRST。为兼容旧版处理器而添加。
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first" 或 ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。
    • "channels_last" 或 ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。
    • "none" 或 ChannelDimension.NONE:图像为 (height, width) 格式。
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • format (str, kwargs, optional, 默认为 AnnotationFormat.COCO_DETECTION) — 标注的数据格式。取值为 “coco_detection” 或 “coco_panoptic” 之一。
  • do_convert_annotations (bool, kwargs, 可选,默认为 True) — 控制是否将标注转换为 RF_DETR 模型所期望的格式。将边界框转换为 (center_x, center_y, width, height) 格式,且取值范围为 [0, 1]。可通过 preprocess 方法中的 do_convert_annotations 参数进行覆盖。

返回值

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

post_process_object_detection

< >

( outputsthreshold: float = 0.5target_sizes: transformers.utils.generic.TensorType | list[tuple] | None = Nonetop_k: int | None = None ) → list[Dict]

参数

  • outputs (RfDetrObjectDetectionOutput) — 模型的原始输出。
  • threshold (float, 可选) — 用于保留目标检测预测结果的分数阈值。
  • target_sizes (torch.Tensor 或 list[tuple[int, int]],可选) — 形状为 (batch_size, 2) 的张量,或包含目标尺寸 (height, width) 的元组列表(tuple[int, int]),表示批次中每张图片的目标大小。如果未设置,预测结果将不会被调整大小。

返回值

list[Dict]

一个字典列表,每个字典包含模型在批次中为一张图像预测的分数、标签和边界框。

将 RfDetrForObjectDetection 的原始输出转换为 (top_left_x, top_left_y, bottom_right_x, bottom_right_y) 格式的最终边界框。仅支持 PyTorch。

post_process_instance_segmentation

< >

( outputsthreshold: float = 0.5mask_threshold: float = 0.0target_sizes: list[tuple[int, int]] | None = Nonereturn_coco_annotation: bool = Falsereturn_binary_maps: bool = Falsetop_k: int | None = None**kwargs ) → list[dict]

参数

  • outputs ([RfDetrInstanceSegmentationOutput]) — 模型的原始输出。
  • threshold (float,可选,默认为 0.5) — 用于保留预测实例掩码的分数阈值。
  • mask_threshold (float,可选,默认为 0.0) — 用于将预测掩码二值化的阈值。
  • target_sizes (list[tuple[int, int]], 可选) — 每张图像的(height, width)目标尺寸。如果未设置,掩码将不会被调整大小。
  • return_coco_annotation (bool,可选,默认为 False) — 如果为 True,则以 COCO 游程编码格式返回分割图,而不是张量。 与 return_binary_maps 互斥。
  • return_binary_maps (bool,可选,默认为 False) — 如果为 True,则返回分割图,格式为堆叠的二值实例掩码张量(每个检测到的实例对应一个),且不进行重叠消解。这与原始 rfdetr 包的输出格式一致。与 return_coco_annotation 互斥。
  • top_k (int, 可选) — 在应用分数阈值之前评估的最大候选查询数量。 默认值为查询的总数。

返回值

list[dict]

每张图片对应一个字典,包含以下键:

  • segmentation — Tensor[H, W] 的 int32 段 ID(-1 = 背景), 当 return_binary_maps=True 时为 Tensor[num_instances, H, W] 的布尔二值掩码, 或当 return_coco_annotation=True 时为 RLE 编码列表。
  • segments_info — 一个字典列表,包含键 id、label_id 和 score。

将 [RfDetrForInstanceSegmentation] 的输出转换为实例分割预测结果。

RfDetrModel

class transformers.RfDetrModel

< >

( config: RfDetrConfig )

参数

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

原始的 LW Detr 模型(由骨干网络和解码器 Transformer 组成),输出未经任何特定头部处理的原始隐藏状态。

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

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

forward

< >

( pixel_values: Tensorpixel_mask: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → RfDetrModelOutput or tuple(torch.Tensor)

参数

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

    什么是注意力掩码?

返回值

RfDetrModelOutput 或 tuple(torch.Tensor)

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

RF-DETR 模型的前向传播过程。该流程如下:

  1. 从骨干网络的展平输出中生成初始的对象查询嵌入和空间位置建议。
  2. 初始化用于存储精炼后的编码器阶段预测结果的存储空间(以适配多组查询结构),并针对每个查询组迭代地精炼对象查询及其坐标,从而捕获编码器阶段中置信度最高的候选目标。
  3. 初始化可学习的查询特征和空间参考点(在推理阶段,为提高效率,仅限制在主组内)。
  4. 将基础参考点投影到整个批次,使用预测的坐标细化值对其进行优化(在解码前将注意力转移到已发现的物体位置),并将目标查询特征扩展以匹配批次维度。
  5. 将精炼后的查询和更新后的参考点通过 Transformer 解码器,以从多尺度特征中聚合详细的空间上下文。
  • last_hidden_state(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选)— 模型最后一层输出的隐藏状态序列。

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

  • intermediate_hidden_states(形状为 (batch_size, config.decoder_layers, num_queries, d_model) 的 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 之后的注意力权重,用于在交叉注意力头中计算加权平均值。

  • backbone_features(形状为 (batch_size, config.num_channels, config.image_size, config.image_size) 的 torch.Tensor 的 list)— 来自骨干网络的特征。

示例:

>>> from transformers import AutoImageProcessor, RfDetrModel
>>> from PIL import Image
>>> import requests

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

>>> image_processor = AutoImageProcessor.from_pretrained("Roboflow/rf-detr-base")
>>> model = RfDetrModel.from_pretrained("Roboflow/rf-detr-base")

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

>>> outputs = model(**inputs)

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

RfDetrForObjectDetection

class transformers.RfDetrForObjectDetection

< >

( config: RfDetrConfig )

参数

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

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

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

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

forward

< >

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

参数

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

    什么是注意力掩码?

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

返回值

RfDetrObjectDetectionOutput 或 tuple(torch.Tensor)

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

前向传播过程如下:

  1. 通过基础 RF-DETR 模型处理视觉输入,以获取 Transformer 的最后一个隐藏状态以及最终的参考点序列。
  2. 第一阶段:从编码器提出的对象查询嵌入生成分类 logits。
  3. 第二阶段:使用解码器的最后一个隐藏状态以及最近的参考点,预测最终的分类标签和精化的边界框
  • 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, d_model) 的 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 之后的注意力权重,用于在交叉注意力头中计算加权平均值。

  • backbone_features(形状为 (batch_size, config.num_channels, config.image_size, config.image_size) 的 torch.Tensor 的 list)— 来自骨干网络的特征。

示例:

>>> from transformers import AutoImageProcessor, RfDetrForObjectDetection
>>> from PIL import Image
>>> import requests

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

>>> image_processor = AutoImageProcessor.from_pretrained("Roboflow/rf-detr-base")
>>> model = RfDetrForObjectDetection.from_pretrained("Roboflow/rf-detr-base")

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

RfDetrForInstanceSegmentation

class transformers.RfDetrForInstanceSegmentation

< >

( config: RfDetrConfig )

forward

< >

( pixel_values: Tensor = Nonepixel_mask: typing.Optional[torch.LongTensor] = Nonelabels: list[dict] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> )

参数

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

    什么是注意力掩码?

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

RF-DETR 模型用于实例分割的前向传播过程。该流程如下:

  1. 通过基础 RF-DETR 模型处理视觉输入,以获取多尺度空间特征、查询嵌入及其变换历史。
  2. 从编码器提出的对象查询嵌入中生成分类 logits 和初始分割掩码(第一阶段)。
  3. 使用解码器的最后一个隐藏状态(第二阶段)预测最终的分类标签和精化的边界框。
  4. 将高分辨率空间特征和查询隐藏状态通过分割头,以生成最终的详细实例掩码。

RfDetrDinov2Backbone

class transformers.RfDetrDinov2Backbone

< >

( config: RfDetrDinov2Config )

参数

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

RfDetrDinov2 骨干网络,用于与 DETR 和 MaskFormer 等框架配合使用。

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

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

forward

< >

( pixel_values: Tensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BackboneOutput or tuple(torch.Tensor)

参数

返回值

BackboneOutput 或 tuple(torch.Tensor)

BackboneOutput 或 torch.Tensor 元组(如果传入 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(RfDetrConfig)和输入。

RfDetrDinov2Backbone 的 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 之后的权重,用于在自注意力头中计算加权平均值。

示例:

>>> from transformers import AutoImageProcessor, AutoBackbone
>>> import torch
>>> from PIL import Image
>>> import requests

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

>>> processor = AutoImageProcessor.from_pretrained("facebook/dinov2-base")
>>> model = AutoBackbone.from_pretrained(
...     "facebook/dinov2-base", out_features=["stage2", "stage5", "stage8", "stage11"]
... )

>>> inputs = processor(image, return_tensors="pt")

>>> outputs = model(**inputs)
>>> feature_maps = outputs.feature_maps
>>> list(feature_maps[-1].shape)
[1, 768, 16, 16]
Update on GitHub