The DAB-DETR model was proposed in DAB-DETR: Dynamic Anchor Boxes are Better Queries for DETR by Shilong Liu, Feng Li, Hao Zhang, Xiao Yang, Xianbiao Qi, Hang Su, Jun Zhu, Lei Zhang. DAB-DETR is an enhanced variant of Conditional DETR. It utilizes dynamically updated anchor boxes to provide both a reference query point (x, y) and a reference anchor size (w, h), improving cross-attention computation. This new approach achieves 45.7% AP when trained for 50 epochs with a single ResNet-50 model as the backbone.
The abstract from the paper is the following:
We present in this paper a novel query formulation using dynamic anchor boxes for DETR (DEtection TRansformer) and offer a deeper understanding of the role of queries in DETR. This new formulation directly uses box coordinates as queries in Transformer decoders and dynamically updates them layer-by-layer. Using box coordinates not only helps using explicit positional priors to improve the query-to-feature similarity and eliminate the slow training convergence issue in DETR, but also allows us to modulate the positional attention map using the box width and height information. Such a design makes it clear that queries in DETR can be implemented as performing soft ROI pooling layer-by-layer in a cascade manner. As a result, it leads to the best performance on MS-COCO benchmark among the DETR-like detection models under the same setting, e.g., AP 45.7% using ResNet50-DC5 as backbone trained in 50 epochs. We also conducted extensive experiments to confirm our analysis and verify the effectiveness of our methods.
This model was contributed by davidhajdu. The original code can be found here.
There are three ways to instantiate a DAB-DETR model (depending on what you prefer):
Option 1: Instantiate DAB-DETR with pre-trained weights for entire model
>>> from transformers import DABDETRForObjectDetection
>>> model = DABDETRForObjectDetection.from_pretrained("IDEA-Research/dab_detr_resnet50")
Option 2: Instantiate DAB-DETR with randomly initialized weights for Transformer, but pre-trained weights for backbone
>>> from transformers import DABDETRConfig, DABDETRForObjectDetection
>>> config = DABDETRConfig()
>>> model = DABDETRForObjectDetection(config)
Option 3: Instantiate DAB-DETR with randomly initialized weights for backbone + Transformer
>>> config = DABDETRConfig(use_pretrained_backbone=False)
>>> model = DABDETRForObjectDetection(config)
( use_timm_backbone = True backbone_config = None backbone = 'resnet50' use_pretrained_backbone = True backbone_kwargs = None num_queries = 300 encoder_layers = 6 encoder_ffn_dim = 2048 encoder_attention_heads = 8 decoder_layers = 6 decoder_ffn_dim = 2048 decoder_attention_heads = 8 encoder_layerdrop = 0.0 decoder_layerdrop = 0.0 is_encoder_decoder = True activation_function = 'prelu' d_model = 256 dropout = 0.1 attention_dropout = 0.0 activation_dropout = 0.0 init_std = 0.02 init_xavier_std = 1.0 auxiliary_loss = False position_embedding_type = 'sine' dilation = False class_cost = 2 bbox_cost = 5 giou_cost = 2 cls_loss_coefficient = 2 bbox_loss_coefficient = 5 giou_loss_coefficient = 2 focal_alpha = 0.25 do_use_self_attn_decoder = True decoder_modulate_hw_attn = True temperature_height = 20 temperature_width = 20 iter_update = True query_dim = 4 bbox_embed_diff_each_layer = False decoder_bbox_embed_diff_each_layer = False random_refpoints_xy = False keep_query_pos = False query_scale_type = 'cond_elewise' num_patterns = 0 normalize_before = False sine_position_embedding_normalize = True sine_position_embedding_scale = None initializer_bias_prior_prob = None **kwargs )
Parameters
bool
, optional, defaults to True
) —
Whether or not to use the timm
library for the backbone. If set to False
, will use the AutoBackbone
API. PretrainedConfig
or dict
, optional) —
The configuration of the backbone model. Only used in case use_timm_backbone
is set to False
in which
case it will default to ResNetConfig()
. str
, optional, defaults to "resnet50"
) —
Name of backbone to use when backbone_config
is None
. If use_pretrained_backbone
is True
, this
will load the corresponding pretrained weights from the timm or transformers library. If use_pretrained_backbone
is False
, this loads the backbone’s config and uses that to initialize the backbone with random weights. bool
, optional, defaults to True
) —
Whether to use pretrained weights for the backbone. dict
, optional) —
Keyword arguments to be passed to AutoBackbone when loading from a checkpoint
e.g. {'out_indices': (0, 1, 2, 3)}
. Cannot be specified if backbone_config
is set. int
, optional, defaults to 300) —
Number of object queries, i.e. detection slots. This is the maximal number of objects
DABDETRModel can detect in a single image. For COCO, we recommend 100 queries. int
, optional, defaults to 6) —
Number of encoder layers. int
, optional, defaults to 2048) —
Dimension of the “intermediate” (often named feed-forward) layer in encoder. int
, optional, defaults to 8) —
Number of attention heads for each attention layer in the Transformer encoder. int
, optional, defaults to 6) —
Number of decoder layers. int
, optional, defaults to 2048) —
Dimension of the “intermediate” (often named feed-forward) layer in decoder. int
, optional, defaults to 8) —
Number of attention heads for each attention layer in the Transformer decoder. float
, optional, defaults to 0.0) —
The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
for more details. float
, optional, defaults to 0.0) —
The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
for more details. bool
, optional, defaults to True
) —
Indicates whether the transformer model architecture is an encoder-decoder or not. str
or function
, optional, defaults to "prelu"
) —
The non-linear activation function (function or string) in the encoder and pooler. If string, "gelu"
,
"relu"
, "silu"
and "gelu_new"
are supported. int
, optional, defaults to 256) —
This parameter is a general dimension parameter, defining dimensions for components such as the encoder layer and projection parameters in the decoder layer, among others. float
, optional, defaults to 0.1) —
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. float
, optional, defaults to 0.0) —
The dropout ratio for the attention probabilities. float
, optional, defaults to 0.0) —
The dropout ratio for activations inside the fully connected layer. float
, optional, defaults to 0.02) —
The standard deviation of the truncated_normal_initializer for initializing all weight matrices. float
, optional, defaults to 1.0) —
The scaling factor used for the Xavier initialization gain in the HM Attention map module. bool
, optional, defaults to False
) —
Whether auxiliary decoding losses (loss at each decoder layer) are to be used. str
, optional, defaults to "sine"
) —
Type of position embeddings to be used on top of the image features. One of "sine"
or "learned"
. bool
, optional, defaults to False
) —
Whether to replace stride with dilation in the last convolutional block (DC5). Only supported when use_timm_backbone
= True
. float
, optional, defaults to 2) —
Relative weight of the classification error in the Hungarian matching cost. float
, optional, defaults to 5) —
Relative weight of the L1 error of the bounding box coordinates in the Hungarian matching cost. float
, optional, defaults to 2) —
Relative weight of the generalized IoU loss of the bounding box in the Hungarian matching cost. float
, optional, defaults to 2) —
Relative weight of the classification loss in the object detection loss function. float
, optional, defaults to 5) —
Relative weight of the L1 bounding box loss in the object detection loss. float
, optional, defaults to 2) —
Relative weight of the generalized IoU loss in the object detection loss. float
, optional, defaults to 0.25) —
Alpha parameter in the focal loss. bool
, optional, defaults to True
) —
Whether to use self-attention module in decoder layers. bool
, optional, defaults to True
) —
Whether to modulate the positional attention map using the box width and height information. int
, optional, defaults to 20) —
Temperature parameter to tune the flatness of positional attention (HEIGHT) int
, optional, defaults to 20) —
Temperature parameter to tune the flatness of positional attention (WIDTH) bool
, optional, defaults to True
) —
Whether to use dynamic iterative anchor updates. int
, optional, defaults to 4) —
Query dimension parameter represents the size of the output vector. bool
, optional, defaults to False
) —
Whether to perform layer-by-layer bounding box embedding refinement. bool
, optional, defaults to False
) —
Whether to perform layer-by-layer bounding box embedding refinement. bool
, optional, defaults to False
) —
Whether to fix the x and y coordinates of the anchor boxes with random initialization. bool
, optional, defaults to False
) —
Whether to concatenate the projected positional embedding from the object query into the original query (key) in every decoder layer. str
, optional, defaults to "cond_elewise"
) —
Scale type options:int
, optional, defaults to 0) —
Number of pattern embeddings. bool
, optional, defaults to False
) —
Whether we use a normalization layer in the Encoder or not. bool
, optional, defaults to True
) —
Whether the positional embeddings are normalized and scaled by sine_position_embedding_scale value. float
, optional, defaults to ‘None’) —
Scaling factor applied to the normalized positional encodings. float
, optional) —
The prior probability used by the bias initializer to initialize biases for enc_score_head
and class_embed
.
If None
, prior_prob
computed as prior_prob = 1 / (num_labels + 1)
while initializing model weights. This is the configuration class to store the configuration of a DABDETRModel. It is used to instantiate a DAB-DETR model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the DAB-DETR IDEA-Research/dab_detr-base architecture.
Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the documentation from PretrainedConfig for more information.
Examples:
>>> from transformers import DABDETRConfig, DABDETRModel
>>> # Initializing a DAB-DETR IDEA-Research/dab_detr-base style configuration
>>> configuration = DABDETRConfig()
>>> # Initializing a model (with random weights) from the IDEA-Research/dab_detr-base style configuration
>>> model = DABDETRModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
( format: Union = <AnnotationFormat.COCO_DETECTION: 'coco_detection'> do_resize: bool = True size: Dict = None resample: Resampling = <Resampling.BILINEAR: 2> do_rescale: bool = True rescale_factor: Union = 0.00392156862745098 do_normalize: bool = True image_mean: Union = None image_std: Union = None do_convert_annotations: Optional = None do_pad: bool = True pad_size: Optional = None **kwargs )
Parameters
str
, optional, defaults to AnnotationFormat.COCO_DETECTION
) —
Data format of the annotations. One of “coco_detection” or “coco_panoptic”. bool
, optional, defaults to True
) —
Controls whether to resize the image’s (height, width) dimensions to the specified size
. Can be
overridden by the do_resize
parameter in the preprocess
method. Dict[str, int]
optional, defaults to {"shortest_edge" -- 800, "longest_edge": 1333}
):
Size of the image’s (height, width)
dimensions after resizing. Can be overridden by the size
parameter
in the preprocess
method. Available options are:{"height": int, "width": int}
: The image will be resized to the exact size (height, width)
.
Do NOT keep the aspect ratio.{"shortest_edge": int, "longest_edge": int}
: The image will be resized to a maximum size respecting
the aspect ratio and keeping the shortest edge less or equal to shortest_edge
and the longest edge
less or equal to longest_edge
.{"max_height": int, "max_width": int}
: The image will be resized to the maximum size respecting the
aspect ratio and keeping the height less or equal to max_height
and the width less or equal to
max_width
.PILImageResampling
, optional, defaults to PILImageResampling.BILINEAR
) —
Resampling filter to use if resizing the image. bool
, optional, defaults to True
) —
Controls whether to rescale the image by the specified scale rescale_factor
. Can be overridden by the
do_rescale
parameter in the preprocess
method. int
or float
, optional, defaults to 1/255
) —
Scale factor to use if rescaling the image. Can be overridden by the rescale_factor
parameter in the
preprocess
method. bool
, optional, defaults to True
) —
Controls whether to normalize the image. Can be overridden by the do_normalize
parameter in the
preprocess
method. float
or List[float]
, optional, defaults to IMAGENET_DEFAULT_MEAN
) —
Mean values to use when normalizing the image. Can be a single value or a list of values, one for each
channel. Can be overridden by the image_mean
parameter in the preprocess
method. float
or List[float]
, optional, defaults to IMAGENET_DEFAULT_STD
) —
Standard deviation values to use when normalizing the image. Can be a single value or a list of values, one
for each channel. Can be overridden by the image_std
parameter in the preprocess
method. bool
, optional, defaults to True
) —
Controls whether to convert the annotations to the format expected by the DETR model. Converts the
bounding boxes to the format (center_x, center_y, width, height)
and in the range [0, 1]
.
Can be overridden by the do_convert_annotations
parameter in the preprocess
method. bool
, optional, defaults to True
) —
Controls whether to pad the image. Can be overridden by the do_pad
parameter in the preprocess
method. If True
, padding will be applied to the bottom and right of the image with zeros.
If pad_size
is provided, the image will be padded to the specified dimensions.
Otherwise, the image will be padded to the maximum height and width of the batch. Dict[str, int]
, optional) —
The size {"height": int, "width" int}
to pad the images to. Must be larger than any image size
provided for preprocessing. If pad_size
is not provided, images will be padded to the largest
height and width in the batch. Constructs a Conditional Detr image processor.
( images: Union annotations: Union = None return_segmentation_masks: bool = None masks_path: Union = None do_resize: Optional = None size: Optional = None resample = None do_rescale: Optional = None rescale_factor: Union = None do_normalize: Optional = None do_convert_annotations: Optional = None image_mean: Union = None image_std: Union = None do_pad: Optional = None format: Union = None return_tensors: Union = None data_format: Union = <ChannelDimension.FIRST: 'channels_first'> input_data_format: Union = None pad_size: Optional = None **kwargs )
Parameters
ImageInput
) —
Image or batch of images to preprocess. Expects a single or batch of images with pixel values ranging
from 0 to 255. If passing in images with pixel values between 0 and 1, set do_rescale=False
. AnnotationType
or List[AnnotationType]
, optional) —
List of annotations associated with the image or batch of images. If annotation is for object
detection, the annotations should be a dictionary with the following keys:int
): The image id.List[Dict]
): List of annotations for an image. Each annotation should be a
dictionary. An image can have no annotations, in which case the list should be empty.
If annotation is for segmentation, the annotations should be a dictionary with the following keys:int
): The image id.List[Dict]
): List of segments for an image. Each segment should be a dictionary.
An image can have no segments, in which case the list should be empty.str
): The file name of the image.bool
, optional, defaults to self.return_segmentation_masks) —
Whether to return segmentation masks. str
or pathlib.Path
, optional) —
Path to the directory containing the segmentation masks. bool
, optional, defaults to self.do_resize) —
Whether to resize the image. Dict[str, int]
, optional, defaults to self.size) —
Size of the image’s (height, width)
dimensions after resizing. Available options are:{"height": int, "width": int}
: The image will be resized to the exact size (height, width)
.
Do NOT keep the aspect ratio.{"shortest_edge": int, "longest_edge": int}
: The image will be resized to a maximum size respecting
the aspect ratio and keeping the shortest edge less or equal to shortest_edge
and the longest edge
less or equal to longest_edge
.{"max_height": int, "max_width": int}
: The image will be resized to the maximum size respecting the
aspect ratio and keeping the height less or equal to max_height
and the width less or equal to
max_width
.PILImageResampling
, optional, defaults to self.resample) —
Resampling filter to use when resizing the image. bool
, optional, defaults to self.do_rescale) —
Whether to rescale the image. float
, optional, defaults to self.rescale_factor) —
Rescale factor to use when rescaling the image. bool
, optional, defaults to self.do_normalize) —
Whether to normalize the image. bool
, optional, defaults to self.do_convert_annotations) —
Whether to convert the annotations to the format expected by the model. Converts the bounding
boxes from the format (top_left_x, top_left_y, width, height)
to (center_x, center_y, width, height)
and in relative coordinates. float
or List[float]
, optional, defaults to self.image_mean) —
Mean to use when normalizing the image. float
or List[float]
, optional, defaults to self.image_std) —
Standard deviation to use when normalizing the image. bool
, optional, defaults to self.do_pad) —
Whether to pad the image. If True
, padding will be applied to the bottom and right of
the image with zeros. If pad_size
is provided, the image will be padded to the specified
dimensions. Otherwise, the image will be padded to the maximum height and width of the batch. str
or AnnotationFormat
, optional, defaults to self.format) —
Format of the annotations. str
or TensorType
, optional, defaults to self.return_tensors) —
Type of tensors to return. If None
, will return the list of images. ChannelDimension
or str
, optional, defaults to ChannelDimension.FIRST
) —
The channel dimension format for the output image. Can be one of:"channels_first"
or ChannelDimension.FIRST
: image in (num_channels, height, width) format."channels_last"
or ChannelDimension.LAST
: image in (height, width, num_channels) format.ChannelDimension
or str
, optional) —
The channel dimension format for the input image. If unset, the channel dimension format is inferred
from the input image. Can be one of:"channels_first"
or ChannelDimension.FIRST
: image in (num_channels, height, width) format."channels_last"
or ChannelDimension.LAST
: image in (height, width, num_channels) format."none"
or ChannelDimension.NONE
: image in (height, width) format.Dict[str, int]
, optional) —
The size {"height": int, "width" int}
to pad the images to. Must be larger than any image size
provided for preprocessing. If pad_size
is not provided, images will be padded to the largest
height and width in the batch. Preprocess an image or a batch of images so that it can be used by the model.
( outputs threshold: float = 0.5 target_sizes: Union = None top_k: int = 100 ) → List[Dict]
Parameters
DetrObjectDetectionOutput
) —
Raw outputs of the model. float
, optional) —
Score threshold to keep object detection predictions. torch.Tensor
or List[Tuple[int, int]]
, optional) —
Tensor of shape (batch_size, 2)
or list of tuples (Tuple[int, int]
) containing the target size
(height, width) of each image in the batch. If left to None, predictions will not be resized. int
, optional, defaults to 100) —
Keep only top k bounding boxes before filtering by thresholding. Returns
List[Dict]
A list of dictionaries, each dictionary containing the scores, labels and boxes for an image in the batch as predicted by the model.
Converts the raw output of DABDETRForObjectDetection into final bounding boxes in (top_left_x, top_left_y, bottom_right_x, bottom_right_y) format. Only supports PyTorch.
( config: DABDETRConfig )
Parameters
The bare DAB-DETR Model (consisting of a backbone and encoder-decoder Transformer) outputting raw hidden-states, intermediate hidden states, reference points, output coordinates without any specific head on top.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
( pixel_values: FloatTensor pixel_mask: Optional = None decoder_attention_mask: Optional = None encoder_outputs: Optional = None inputs_embeds: Optional = None decoder_inputs_embeds: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None ) → transformers.models.dab_detr.modeling_dab_detr.DABDETRModelOutput
or tuple(torch.FloatTensor)
Parameters
torch.FloatTensor
of shape (batch_size, num_channels, height, width)
) —
Pixel values. Padding will be ignored by default should you provide it.
Pixel values can be obtained using AutoImageProcessor. See DABDetrImageProcessor.__call__
for details.
torch.LongTensor
of shape (batch_size, height, width)
, optional) —
Mask to avoid performing attention on padding pixel values. Mask values selected in [0, 1]
:
torch.FloatTensor
of shape (batch_size, num_queries)
, optional) —
Not used by default. Can be used to mask object queries. tuple(tuple(torch.FloatTensor)
, optional) —
Tuple consists of (last_hidden_state
, optional: hidden_states
, optional: attentions
)
last_hidden_state
of shape (batch_size, sequence_length, hidden_size)
, optional) is a sequence of
hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder. torch.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
, optional) —
Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
can choose to directly pass a flattened representation of an image. torch.FloatTensor
of shape (batch_size, num_queries, hidden_size)
, optional) —
Optionally, instead of initializing the queries with a tensor of zeros, you can choose to directly pass an
embedded representation. bool
, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions
under returned
tensors for more detail. bool
, optional) —
Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for
more detail. bool
, optional) —
Whether or not to return a ModelOutput instead of a plain tuple. Returns
transformers.models.dab_detr.modeling_dab_detr.DABDETRModelOutput
or tuple(torch.FloatTensor)
A transformers.models.dab_detr.modeling_dab_detr.DABDETRModelOutput
or a tuple of
torch.FloatTensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various
elements depending on the configuration (DABDETRConfig) and inputs.
torch.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
) — Sequence of hidden-states at the output of the last layer of the decoder of the model.tuple(torch.FloatTensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) — Tuple of torch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of
shape (batch_size, sequence_length, hidden_size)
. Hidden-states of the decoder at the output of each
layer plus the initial embedding outputs.tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of torch.FloatTensor
(one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights of the decoder, after the attention softmax, used to compute the
weighted average in the self-attention heads.tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of torch.FloatTensor
(one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights of the decoder’s cross-attention layer, after the attention softmax,
used to compute the weighted average in the cross-attention heads.torch.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
, optional) — Sequence of hidden-states at the output of the last layer of the encoder of the model.tuple(torch.FloatTensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) — Tuple of torch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of
shape (batch_size, sequence_length, hidden_size)
. Hidden-states of the encoder at the output of each
layer plus the initial embedding outputs.tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of torch.FloatTensor
(one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights of the encoder, after the attention softmax, used to compute the
weighted average in the self-attention heads.torch.FloatTensor
of shape (config.decoder_layers, batch_size, sequence_length, hidden_size)
, optional, returned when config.auxiliary_loss=True
) — Intermediate decoder activations, i.e. the output of each decoder layer, each of them gone through a
layernorm.torch.FloatTensor
of shape (config.decoder_layers, batch_size, num_queries, 2 (anchor points))
) — Reference points (reference points of each layer of the decoder).The DABDETRModel forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Examples:
>>> from transformers import AutoImageProcessor, AutoModel
>>> 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("IDEA-Research/dab_detr-base")
>>> model = AutoModel.from_pretrained("IDEA-Research/dab_detr-base")
>>> # 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]
( config: DABDETRConfig )
Parameters
DAB_DETR Model (consisting of a backbone and encoder-decoder Transformer) with object detection heads on top, for tasks such as COCO detection.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
( pixel_values: FloatTensor pixel_mask: Optional = None decoder_attention_mask: Optional = None encoder_outputs: Optional = None inputs_embeds: Optional = None decoder_inputs_embeds: Optional = None labels: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None ) → transformers.models.dab_detr.modeling_dab_detr.DABDETRObjectDetectionOutput
or tuple(torch.FloatTensor)
Parameters
torch.FloatTensor
of shape (batch_size, num_channels, height, width)
) —
Pixel values. Padding will be ignored by default should you provide it.
Pixel values can be obtained using AutoImageProcessor. See DABDetrImageProcessor.__call__
for details.
torch.LongTensor
of shape (batch_size, height, width)
, optional) —
Mask to avoid performing attention on padding pixel values. Mask values selected in [0, 1]
:
torch.FloatTensor
of shape (batch_size, num_queries)
, optional) —
Not used by default. Can be used to mask object queries. tuple(tuple(torch.FloatTensor)
, optional) —
Tuple consists of (last_hidden_state
, optional: hidden_states
, optional: attentions
)
last_hidden_state
of shape (batch_size, sequence_length, hidden_size)
, optional) is a sequence of
hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder. torch.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
, optional) —
Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
can choose to directly pass a flattened representation of an image. torch.FloatTensor
of shape (batch_size, num_queries, hidden_size)
, optional) —
Optionally, instead of initializing the queries with a tensor of zeros, you can choose to directly pass an
embedded representation. bool
, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions
under returned
tensors for more detail. bool
, optional) —
Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for
more detail. bool
, optional) —
Whether or not to return a ModelOutput instead of a plain tuple. List[Dict]
of len (batch_size,)
, optional) —
Labels for computing the bipartite matching loss. List of dicts, each dictionary containing at least the
following 2 keys: ‘class_labels’ and ‘boxes’ (the class labels and bounding boxes of an image in the batch
respectively). The class labels themselves should be a torch.LongTensor
of len (number of bounding boxes in the image,)
and the boxes a torch.FloatTensor
of shape (number of bounding boxes in the image, 4)
. Returns
transformers.models.dab_detr.modeling_dab_detr.DABDETRObjectDetectionOutput
or tuple(torch.FloatTensor)
A transformers.models.dab_detr.modeling_dab_detr.DABDETRObjectDetectionOutput
or a tuple of
torch.FloatTensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various
elements depending on the configuration (DABDETRConfig) and inputs.
torch.FloatTensor
of shape (1,)
, optional, returned when labels
are provided)) — Total loss as a linear combination of a negative log-likehood (cross-entropy) for class prediction and a
bounding box loss. The latter is defined as a linear combination of the L1 loss and the generalized
scale-invariant IoU loss.Dict
, optional) — A dictionary containing the individual losses. Useful for logging.torch.FloatTensor
of shape (batch_size, num_queries, num_classes + 1)
) — Classification logits (including no-object) for all queries.torch.FloatTensor
of shape (batch_size, num_queries, 4)
) — Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These
values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding
possible padding). You can use post_process_object_detection() to retrieve the
unnormalized bounding boxes.list[Dict]
, optional) — Optional, only returned when auxilary losses are activated (i.e. config.auxiliary_loss
is set to True
)
and labels are provided. It is a list of dictionaries containing the two above keys (logits
and
pred_boxes
) for each decoder layer.torch.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
, optional) — Sequence of hidden-states at the output of the last layer of the decoder of the model.tuple(torch.FloatTensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) — Tuple of torch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of
shape (batch_size, sequence_length, hidden_size)
. Hidden-states of the decoder at the output of each
layer plus the initial embedding outputs.tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of torch.FloatTensor
(one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights of the decoder, after the attention softmax, used to compute the
weighted average in the self-attention heads.tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of torch.FloatTensor
(one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights of the decoder’s cross-attention layer, after the attention softmax,
used to compute the weighted average in the cross-attention heads.torch.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
, optional) — Sequence of hidden-states at the output of the last layer of the encoder of the model.tuple(torch.FloatTensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) — Tuple of torch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of
shape (batch_size, sequence_length, hidden_size)
. Hidden-states of the encoder at the output of each
layer plus the initial embedding outputs.tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of torch.FloatTensor
(one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights of the encoder, after the attention softmax, used to compute the
weighted average in the self-attention heads.The DABDETRForObjectDetection forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Examples:
>>> from transformers import AutoImageProcessor, AutoModelForObjectDetection
>>> 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("IDEA-Research/dab_detr-base")
>>> model = AutoModelForObjectDetection.from_pretrained("IDEA-Research/dab_detr-base")
>>> 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]