# Conditional DETR

## Conditional DETR

### Overview

The Conditional DETR model was proposed in [Conditional DETR for Fast Training Convergence](https://arxiv.org/abs/2108.06152) by Depu Meng, Xiaokang Chen, Zejia Fan, Gang Zeng, Houqiang Li, Yuhui Yuan, Lei Sun, Jingdong Wang. Conditional DETR presents a conditional cross-attention mechanism for fast DETR training. Conditional DETR converges 6.7× to 10× faster than DETR.

The abstract from the paper is the following:

*The recently-developed DETR approach applies the transformer encoder and decoder architecture to object detection and achieves promising performance. In this paper, we handle the critical issue, slow training convergence, and present a conditional cross-attention mechanism for fast DETR training. Our approach is motivated by that the cross-attention in DETR relies highly on the content embeddings for localizing the four extremities and predicting the box, which increases the need for high-quality content embeddings and thus the training difficulty. Our approach, named conditional DETR, learns a conditional spatial query from the decoder embedding for decoder multi-head cross-attention. The benefit is that through the conditional spatial query, each cross-attention head is able to attend to a band containing a distinct region, e.g., one object extremity or a region inside the object box. This narrows down the spatial range for localizing the distinct regions for object classification and box regression, thus relaxing the dependence on the content embeddings and easing the training. Empirical results show that conditional DETR converges 6.7× faster for the backbones R50 and R101 and 10× faster for stronger backbones DC5-R50 and DC5-R101. Code is available at* [*https://github.com/Atten4Vis/ConditionalDETR*](https://github.com/Atten4Vis/ConditionalDETR)*.*

![drawing](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/conditional_detr_curve.jpg)Conditional DETR shows much faster convergence compared to the original DETR. Taken from the [original paper](https://arxiv.org/abs/2108.06152).

This model was contributed by [DepuMeng](https://huggingface.co/DepuMeng). The original code can be found [here](https://github.com/Atten4Vis/ConditionalDETR).

### Documentation resources

* [Object detection task guide](https://huggingface.co/docs/transformers/tasks/object_detection)

### ConditionalDetrConfig

#### class transformers.ConditionalDetrConfig

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/conditional_detr/configuration_conditional_detr.py#L36)

( use\_timm\_backbone = Truebackbone\_config = Nonenum\_channels = 3num\_queries = 300encoder\_layers = 6encoder\_ffn\_dim = 2048encoder\_attention\_heads = 8decoder\_layers = 6decoder\_ffn\_dim = 2048decoder\_attention\_heads = 8encoder\_layerdrop = 0.0decoder\_layerdrop = 0.0is\_encoder\_decoder = Trueactivation\_function = 'relu'd\_model = 256dropout = 0.1attention\_dropout = 0.0activation\_dropout = 0.0init\_std = 0.02init\_xavier\_std = 1.0auxiliary\_loss = Falseposition\_embedding\_type = 'sine'backbone = 'resnet50'use\_pretrained\_backbone = Truedilation = Falseclass\_cost = 2bbox\_cost = 5giou\_cost = 2mask\_loss\_coefficient = 1dice\_loss\_coefficient = 1cls\_loss\_coefficient = 2bbox\_loss\_coefficient = 5giou\_loss\_coefficient = 2focal\_alpha = 0.25\*\*kwargs )

Parameters

* **use\_timm\_backbone** (`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.
* **backbone\_config** (`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()`.
* **num\_channels** (`int`, *optional*, defaults to 3) — The number of input channels.
* **num\_queries** (`int`, *optional*, defaults to 100) — Number of object queries, i.e. detection slots. This is the maximal number of objects [ConditionalDetrModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrModel) can detect in a single image. For COCO, we recommend 100 queries.
* **d\_model** (`int`, *optional*, defaults to 256) — Dimension of the layers.
* **encoder\_layers** (`int`, *optional*, defaults to 6) — Number of encoder layers.
* **decoder\_layers** (`int`, *optional*, defaults to 6) — Number of decoder layers.
* **encoder\_attention\_heads** (`int`, *optional*, defaults to 8) — Number of attention heads for each attention layer in the Transformer encoder.
* **decoder\_attention\_heads** (`int`, *optional*, defaults to 8) — Number of attention heads for each attention layer in the Transformer decoder.
* **decoder\_ffn\_dim** (`int`, *optional*, defaults to 2048) — Dimension of the “intermediate” (often named feed-forward) layer in decoder.
* **encoder\_ffn\_dim** (`int`, *optional*, defaults to 2048) — Dimension of the “intermediate” (often named feed-forward) layer in decoder.
* **activation\_function** (`str` or `function`, *optional*, defaults to `"relu"`) — The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, `"relu"`, `"silu"` and `"gelu_new"` are supported.
* **dropout** (`float`, *optional*, defaults to 0.1) — The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
* **attention\_dropout** (`float`, *optional*, defaults to 0.0) — The dropout ratio for the attention probabilities.
* **activation\_dropout** (`float`, *optional*, defaults to 0.0) — The dropout ratio for activations inside the fully connected layer.
* **init\_std** (`float`, *optional*, defaults to 0.02) — The standard deviation of the truncated\_normal\_initializer for initializing all weight matrices.
* **init\_xavier\_std** (`float`, *optional*, defaults to 1) — The scaling factor used for the Xavier initialization gain in the HM Attention map module.
* **encoder\_layerdrop** (`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.
* **decoder\_layerdrop** (`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.
* **auxiliary\_loss** (`bool`, *optional*, defaults to `False`) — Whether auxiliary decoding losses (loss at each decoder layer) are to be used.
* **position\_embedding\_type** (`str`, *optional*, defaults to `"sine"`) — Type of position embeddings to be used on top of the image features. One of `"sine"` or `"learned"`.
* **backbone** (`str`, *optional*, defaults to `"resnet50"`) — Name of convolutional backbone to use in case `use_timm_backbone` = `True`. Supports any convolutional backbone from the timm package. For a list of all available models, see [this page](https://rwightman.github.io/pytorch-image-models/#load-a-pretrained-model).
* **use\_pretrained\_backbone** (`bool`, *optional*, defaults to `True`) — Whether to use pretrained weights for the backbone. Only supported when `use_timm_backbone` = `True`.
* **dilation** (`bool`, *optional*, defaults to `False`) — Whether to replace stride with dilation in the last convolutional block (DC5). Only supported when `use_timm_backbone` = `True`.
* **class\_cost** (`float`, *optional*, defaults to 1) — Relative weight of the classification error in the Hungarian matching cost.
* **bbox\_cost** (`float`, *optional*, defaults to 5) — Relative weight of the L1 error of the bounding box coordinates in the Hungarian matching cost.
* **giou\_cost** (`float`, *optional*, defaults to 2) — Relative weight of the generalized IoU loss of the bounding box in the Hungarian matching cost.
* **mask\_loss\_coefficient** (`float`, *optional*, defaults to 1) — Relative weight of the Focal loss in the panoptic segmentation loss.
* **dice\_loss\_coefficient** (`float`, *optional*, defaults to 1) — Relative weight of the DICE/F-1 loss in the panoptic segmentation loss.
* **bbox\_loss\_coefficient** (`float`, *optional*, defaults to 5) — Relative weight of the L1 bounding box loss in the object detection loss.
* **giou\_loss\_coefficient** (`float`, *optional*, defaults to 2) — Relative weight of the generalized IoU loss in the object detection loss.
* **eos\_coefficient** (`float`, *optional*, defaults to 0.1) — Relative classification weight of the ‘no-object’ class in the object detection loss.
* **focal\_alpha** (`float`, *optional*, defaults to 0.25) — Alpha parameter in the focal loss.

This is the configuration class to store the configuration of a [ConditionalDetrModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrModel). It is used to instantiate a Conditional 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 Conditional DETR [microsoft/conditional-detr-resnet-50](https://huggingface.co/microsoft/conditional-detr-resnet-50) architecture.

Configuration objects inherit from [PretrainedConfig](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/configuration#transformers.PretrainedConfig) and can be used to control the model outputs. Read the documentation from [PretrainedConfig](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/configuration#transformers.PretrainedConfig) for more information.

Examples:

Copied

```
>>> from transformers import ConditionalDetrConfig, ConditionalDetrModel

>>> # Initializing a Conditional DETR microsoft/conditional-detr-resnet-50 style configuration
>>> configuration = ConditionalDetrConfig()

>>> # Initializing a model (with random weights) from the microsoft/conditional-detr-resnet-50 style configuration
>>> model = ConditionalDetrModel(configuration)

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

### ConditionalDetrImageProcessor

#### class transformers.ConditionalDetrImageProcessor

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/conditional_detr/image_processing_conditional_detr.py#L763)

( format: typing.Union\[str, transformers.models.conditional\_detr.image\_processing\_conditional\_detr.AnnotionFormat] = \<AnnotionFormat.COCO\_DETECTION: 'coco\_detection'>do\_resize: bool = Truesize: typing.Dict\[str, int] = Noneresample: Resampling = \<Resampling.BILINEAR: 2>do\_rescale: bool = Truerescale\_factor: typing.Union\[int, float] = 0.00392156862745098do\_normalize: bool = Trueimage\_mean: typing.Union\[float, typing.List\[float]] = Noneimage\_std: typing.Union\[float, typing.List\[float]] = Nonedo\_pad: bool = True\*\*kwargs )

Parameters

* **format** (`str`, *optional*, defaults to `"coco_detection"`) — Data format of the annotations. One of “coco\_detection” or “coco\_panoptic”.
* **do\_resize** (`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.
* **size** (`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.
* **resample** (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`) — Resampling filter to use if resizing the image.
* **do\_rescale** (`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.
* **rescale\_factor** (`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. do\_normalize — Controls whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess` method.
* **image\_mean** (`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.
* **image\_std** (`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.
* **do\_pad** (`bool`, *optional*, defaults to `True`) — Controls whether to pad the image to the largest image in a batch and create a pixel mask. Can be overridden by the `do_pad` parameter in the `preprocess` method.

Constructs a Conditional Detr image processor.

**preprocess**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/conditional_detr/image_processing_conditional_detr.py#L1104)

( images: typing.Union\[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List\[ForwardRef('PIL.Image.Image')], typing.List\[numpy.ndarray], typing.List\[ForwardRef('torch.Tensor')]]annotations: typing.Union\[typing.Dict\[str, typing.Union\[int, str, typing.List\[typing.Dict]]], typing.List\[typing.Dict\[str, typing.Union\[int, str, typing.List\[typing.Dict]]]], NoneType] = Nonereturn\_segmentation\_masks: bool = Nonemasks\_path: typing.Union\[str, pathlib.Path, NoneType] = Nonedo\_resize: typing.Optional\[bool] = Nonesize: typing.Union\[typing.Dict\[str, int], NoneType] = Noneresample = Nonedo\_rescale: typing.Optional\[bool] = Nonerescale\_factor: typing.Union\[int, float, NoneType] = Nonedo\_normalize: typing.Optional\[bool] = Noneimage\_mean: typing.Union\[float, typing.List\[float], NoneType] = Noneimage\_std: typing.Union\[float, typing.List\[float], NoneType] = Nonedo\_pad: typing.Optional\[bool] = Noneformat: typing.Union\[str, transformers.models.conditional\_detr.image\_processing\_conditional\_detr.AnnotionFormat, NoneType] = Nonereturn\_tensors: typing.Union\[str, transformers.utils.generic.TensorType, NoneType] = Nonedata\_format: typing.Union\[str, transformers.image\_utils.ChannelDimension] = \<ChannelDimension.FIRST: 'channels\_first'>input\_data\_format: typing.Union\[str, transformers.image\_utils.ChannelDimension, NoneType] = None\*\*kwargs )

Parameters

* **images** (`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`.
* **annotations** (`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:
  * “image\_id” (`int`): The image id.
  * “annotations” (`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:
  * “image\_id” (`int`): The image id.
  * “segments\_info” (`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.
  * “file\_name” (`str`): The file name of the image.
* **return\_segmentation\_masks** (`bool`, *optional*, defaults to self.return\_segmentation\_masks) — Whether to return segmentation masks.
* **masks\_path** (`str` or `pathlib.Path`, *optional*) — Path to the directory containing the segmentation masks.
* **do\_resize** (`bool`, *optional*, defaults to self.do\_resize) — Whether to resize the image.
* **size** (`Dict[str, int]`, *optional*, defaults to self.size) — Size of the image after resizing.
* **resample** (`PILImageResampling`, *optional*, defaults to self.resample) — Resampling filter to use when resizing the image.
* **do\_rescale** (`bool`, *optional*, defaults to self.do\_rescale) — Whether to rescale the image.
* **rescale\_factor** (`float`, *optional*, defaults to self.rescale\_factor) — Rescale factor to use when rescaling the image.
* **do\_normalize** (`bool`, *optional*, defaults to self.do\_normalize) — Whether to normalize the image.
* **image\_mean** (`float` or `List[float]`, *optional*, defaults to self.image\_mean) — Mean to use when normalizing the image.
* **image\_std** (`float` or `List[float]`, *optional*, defaults to self.image\_std) — Standard deviation to use when normalizing the image.
* **do\_pad** (`bool`, *optional*, defaults to self.do\_pad) — Whether to pad the image.
* **format** (`str` or `AnnotionFormat`, *optional*, defaults to self.format) — Format of the annotations.
* **return\_tensors** (`str` or `TensorType`, *optional*, defaults to self.return\_tensors) — Type of tensors to return. If `None`, will return the list of images.
* **data\_format** (`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.
  * Unset: Use the channel dimension format of the input image.
* **input\_data\_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.

Preprocess an image or a batch of images so that it can be used by the model.

**post\_process\_object\_detection**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/conditional_detr/image_processing_conditional_detr.py#L1396)

( outputsthreshold: float = 0.5target\_sizes: typing.Union\[transformers.utils.generic.TensorType, typing.List\[typing.Tuple]] = Nonetop\_k: int = 100 ) → `List[Dict]`

Parameters

* **outputs** (`DetrObjectDetectionOutput`) — Raw outputs of the model.
* **threshold** (`float`, *optional*) — Score threshold to keep object detection predictions.
* **target\_sizes** (`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.
* **top\_k** (`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 [ConditionalDetrForObjectDetection](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrForObjectDetection) into final bounding boxes in (top\_left\_x, top\_left\_y, bottom\_right\_x, bottom\_right\_y) format. Only supports PyTorch.

**post\_process\_instance\_segmentation**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/conditional_detr/image_processing_conditional_detr.py#L1504)

( outputsthreshold: float = 0.5mask\_threshold: float = 0.5overlap\_mask\_area\_threshold: float = 0.8target\_sizes: typing.Union\[typing.List\[typing.Tuple\[int, int]], NoneType] = Nonereturn\_coco\_annotation: typing.Optional\[bool] = False ) → `List[Dict]`

Parameters

* **outputs** ([ConditionalDetrForSegmentation](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrForSegmentation)) — Raw outputs of the model.
* **threshold** (`float`, *optional*, defaults to 0.5) — The probability score threshold to keep predicted instance masks.
* **mask\_threshold** (`float`, *optional*, defaults to 0.5) — Threshold to use when turning the predicted masks into binary values.
* **overlap\_mask\_area\_threshold** (`float`, *optional*, defaults to 0.8) — The overlap mask area threshold to merge or discard small disconnected parts within each binary instance mask.
* **target\_sizes** (`List[Tuple]`, *optional*) — List of length (batch\_size), where each list item (`Tuple[int, int]]`) corresponds to the requested final size (height, width) of each prediction. If unset, predictions will not be resized.
* **return\_coco\_annotation** (`bool`, *optional*) — Defaults to `False`. If set to `True`, segmentation maps are returned in COCO run-length encoding (RLE) format.

Returns

`List[Dict]`

A list of dictionaries, one per image, each dictionary containing two keys:

* **segmentation** — A tensor of shape `(height, width)` where each pixel represents a `segment_id` or `List[List]` run-length encoding (RLE) of the segmentation map if return\_coco\_annotation is set to `True`. Set to `None` if no mask if found above `threshold`.
* **segments\_info** — A dictionary that contains additional information on each segment.
  * **id** — An integer representing the `segment_id`.
  * **label\_id** — An integer representing the label / semantic class id corresponding to `segment_id`.
  * **score** — Prediction score of segment with `segment_id`.

Converts the output of [ConditionalDetrForSegmentation](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrForSegmentation) into instance segmentation predictions. Only supports PyTorch.

**post\_process\_semantic\_segmentation**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/conditional_detr/image_processing_conditional_detr.py#L1455)

( outputstarget\_sizes: typing.List\[typing.Tuple\[int, int]] = None ) → `List[torch.Tensor]`

Parameters

* **outputs** ([ConditionalDetrForSegmentation](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrForSegmentation)) — Raw outputs of the model.
* **target\_sizes** (`List[Tuple[int, int]]`, *optional*) — A list of tuples (`Tuple[int, int]`) containing the target size (height, width) of each image in the batch. If unset, predictions will not be resized.

Returns

`List[torch.Tensor]`

A list of length `batch_size`, where each item is a semantic segmentation map of shape (height, width) corresponding to the target\_sizes entry (if `target_sizes` is specified). Each entry of each `torch.Tensor` correspond to a semantic class id.

Converts the output of [ConditionalDetrForSegmentation](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrForSegmentation) into semantic segmentation maps. Only supports PyTorch.

**post\_process\_panoptic\_segmentation**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/conditional_detr/image_processing_conditional_detr.py#L1589)

( outputsthreshold: float = 0.5mask\_threshold: float = 0.5overlap\_mask\_area\_threshold: float = 0.8label\_ids\_to\_fuse: typing.Optional\[typing.Set\[int]] = Nonetarget\_sizes: typing.Union\[typing.List\[typing.Tuple\[int, int]], NoneType] = None ) → `List[Dict]`

Parameters

* **outputs** ([ConditionalDetrForSegmentation](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrForSegmentation)) — The outputs from [ConditionalDetrForSegmentation](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrForSegmentation).
* **threshold** (`float`, *optional*, defaults to 0.5) — The probability score threshold to keep predicted instance masks.
* **mask\_threshold** (`float`, *optional*, defaults to 0.5) — Threshold to use when turning the predicted masks into binary values.
* **overlap\_mask\_area\_threshold** (`float`, *optional*, defaults to 0.8) — The overlap mask area threshold to merge or discard small disconnected parts within each binary instance mask.
* **label\_ids\_to\_fuse** (`Set[int]`, *optional*) — The labels in this state will have all their instances be fused together. For instance we could say there can only be one sky in an image, but several persons, so the label ID for sky would be in that set, but not the one for person.
* **target\_sizes** (`List[Tuple]`, *optional*) — List of length (batch\_size), where each list item (`Tuple[int, int]]`) corresponds to the requested final size (height, width) of each prediction in batch. If unset, predictions will not be resized.

Returns

`List[Dict]`

A list of dictionaries, one per image, each dictionary containing two keys:

* **segmentation** — a tensor of shape `(height, width)` where each pixel represents a `segment_id` or `None` if no mask if found above `threshold`. If `target_sizes` is specified, segmentation is resized to the corresponding `target_sizes` entry.
* **segments\_info** — A dictionary that contains additional information on each segment.
  * **id** — an integer representing the `segment_id`.
  * **label\_id** — An integer representing the label / semantic class id corresponding to `segment_id`.
  * **was\_fused** — a boolean, `True` if `label_id` was in `label_ids_to_fuse`, `False` otherwise. Multiple instances of the same class / label were fused and assigned a single `segment_id`.
  * **score** — Prediction score of segment with `segment_id`.

Converts the output of [ConditionalDetrForSegmentation](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrForSegmentation) into image panoptic segmentation predictions. Only supports PyTorch.

### ConditionalDetrFeatureExtractor

#### class transformers.ConditionalDetrFeatureExtractor

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/conditional_detr/feature_extraction_conditional_detr.py#L26)

( \*args\*\*kwargs )

**\_\_call\_\_**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/image_processing_utils.py#L544)

( images\*\*kwargs )

Preprocess an image or a batch of images.

**post\_process\_object\_detection**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/conditional_detr/image_processing_conditional_detr.py#L1396)

( outputsthreshold: float = 0.5target\_sizes: typing.Union\[transformers.utils.generic.TensorType, typing.List\[typing.Tuple]] = Nonetop\_k: int = 100 ) → `List[Dict]`

Parameters

* **outputs** (`DetrObjectDetectionOutput`) — Raw outputs of the model.
* **threshold** (`float`, *optional*) — Score threshold to keep object detection predictions.
* **target\_sizes** (`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.
* **top\_k** (`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 [ConditionalDetrForObjectDetection](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrForObjectDetection) into final bounding boxes in (top\_left\_x, top\_left\_y, bottom\_right\_x, bottom\_right\_y) format. Only supports PyTorch.

**post\_process\_instance\_segmentation**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/conditional_detr/image_processing_conditional_detr.py#L1504)

( outputsthreshold: float = 0.5mask\_threshold: float = 0.5overlap\_mask\_area\_threshold: float = 0.8target\_sizes: typing.Union\[typing.List\[typing.Tuple\[int, int]], NoneType] = Nonereturn\_coco\_annotation: typing.Optional\[bool] = False ) → `List[Dict]`

Expand 6 parameters

Parameters

* **outputs** ([ConditionalDetrForSegmentation](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrForSegmentation)) — Raw outputs of the model.
* **threshold** (`float`, *optional*, defaults to 0.5) — The probability score threshold to keep predicted instance masks.
* **mask\_threshold** (`float`, *optional*, defaults to 0.5) — Threshold to use when turning the predicted masks into binary values.
* **overlap\_mask\_area\_threshold** (`float`, *optional*, defaults to 0.8) — The overlap mask area threshold to merge or discard small disconnected parts within each binary instance mask.
* **target\_sizes** (`List[Tuple]`, *optional*) — List of length (batch\_size), where each list item (`Tuple[int, int]]`) corresponds to the requested final size (height, width) of each prediction. If unset, predictions will not be resized.
* **return\_coco\_annotation** (`bool`, *optional*) — Defaults to `False`. If set to `True`, segmentation maps are returned in COCO run-length encoding (RLE) format.

Returns

`List[Dict]`

A list of dictionaries, one per image, each dictionary containing two keys:

* **segmentation** — A tensor of shape `(height, width)` where each pixel represents a `segment_id` or `List[List]` run-length encoding (RLE) of the segmentation map if return\_coco\_annotation is set to `True`. Set to `None` if no mask if found above `threshold`.
* **segments\_info** — A dictionary that contains additional information on each segment.
  * **id** — An integer representing the `segment_id`.
  * **label\_id** — An integer representing the label / semantic class id corresponding to `segment_id`.
  * **score** — Prediction score of segment with `segment_id`.

Converts the output of [ConditionalDetrForSegmentation](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrForSegmentation) into instance segmentation predictions. Only supports PyTorch.

**post\_process\_semantic\_segmentation**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/conditional_detr/image_processing_conditional_detr.py#L1455)

( outputstarget\_sizes: typing.List\[typing.Tuple\[int, int]] = None ) → `List[torch.Tensor]`

Parameters

* **outputs** ([ConditionalDetrForSegmentation](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrForSegmentation)) — Raw outputs of the model.
* **target\_sizes** (`List[Tuple[int, int]]`, *optional*) — A list of tuples (`Tuple[int, int]`) containing the target size (height, width) of each image in the batch. If unset, predictions will not be resized.

Returns

`List[torch.Tensor]`

A list of length `batch_size`, where each item is a semantic segmentation map of shape (height, width) corresponding to the target\_sizes entry (if `target_sizes` is specified). Each entry of each `torch.Tensor` correspond to a semantic class id.

Converts the output of [ConditionalDetrForSegmentation](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrForSegmentation) into semantic segmentation maps. Only supports PyTorch.

**post\_process\_panoptic\_segmentation**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/conditional_detr/image_processing_conditional_detr.py#L1589)

( outputsthreshold: float = 0.5mask\_threshold: float = 0.5overlap\_mask\_area\_threshold: float = 0.8label\_ids\_to\_fuse: typing.Optional\[typing.Set\[int]] = Nonetarget\_sizes: typing.Union\[typing.List\[typing.Tuple\[int, int]], NoneType] = None ) → `List[Dict]`

Parameters

* **outputs** ([ConditionalDetrForSegmentation](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrForSegmentation)) — The outputs from [ConditionalDetrForSegmentation](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrForSegmentation).
* **threshold** (`float`, *optional*, defaults to 0.5) — The probability score threshold to keep predicted instance masks.
* **mask\_threshold** (`float`, *optional*, defaults to 0.5) — Threshold to use when turning the predicted masks into binary values.
* **overlap\_mask\_area\_threshold** (`float`, *optional*, defaults to 0.8) — The overlap mask area threshold to merge or discard small disconnected parts within each binary instance mask.
* **label\_ids\_to\_fuse** (`Set[int]`, *optional*) — The labels in this state will have all their instances be fused together. For instance we could say there can only be one sky in an image, but several persons, so the label ID for sky would be in that set, but not the one for person.
* **target\_sizes** (`List[Tuple]`, *optional*) — List of length (batch\_size), where each list item (`Tuple[int, int]]`) corresponds to the requested final size (height, width) of each prediction in batch. If unset, predictions will not be resized.

Returns

`List[Dict]`

A list of dictionaries, one per image, each dictionary containing two keys:

* **segmentation** — a tensor of shape `(height, width)` where each pixel represents a `segment_id` or `None` if no mask if found above `threshold`. If `target_sizes` is specified, segmentation is resized to the corresponding `target_sizes` entry.
* **segments\_info** — A dictionary that contains additional information on each segment.
  * **id** — an integer representing the `segment_id`.
  * **label\_id** — An integer representing the label / semantic class id corresponding to `segment_id`.
  * **was\_fused** — a boolean, `True` if `label_id` was in `label_ids_to_fuse`, `False` otherwise. Multiple instances of the same class / label were fused and assigned a single `segment_id`.
  * **score** — Prediction score of segment with `segment_id`.

Converts the output of [ConditionalDetrForSegmentation](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrForSegmentation) into image panoptic segmentation predictions. Only supports PyTorch.

### ConditionalDetrModel

#### class transformers.ConditionalDetrModel

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/conditional_detr/modeling_conditional_detr.py#L1604)

( config: ConditionalDetrConfig )

Parameters

* **config** ([ConditionalDetrConfig](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

The bare Conditional DETR Model (consisting of a backbone and encoder-decoder Transformer) outputting raw hidden-states without any specific head on top.

This model inherits from [PreTrainedModel](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/model#transformers.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](https://pytorch.org/docs/stable/nn.html#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.

**forward**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/conditional_detr/modeling_conditional_detr.py#L1638)

( pixel\_values: FloatTensorpixel\_mask: typing.Optional\[torch.LongTensor] = Nonedecoder\_attention\_mask: typing.Optional\[torch.LongTensor] = Noneencoder\_outputs: typing.Optional\[torch.FloatTensor] = Noneinputs\_embeds: typing.Optional\[torch.FloatTensor] = Nonedecoder\_inputs\_embeds: typing.Optional\[torch.FloatTensor] = Noneoutput\_attentions: typing.Optional\[bool] = Noneoutput\_hidden\_states: typing.Optional\[bool] = Nonereturn\_dict: typing.Optional\[bool] = None ) → `transformers.models.conditional_detr.modeling_conditional_detr.ConditionalDetrModelOutput` or `tuple(torch.FloatTensor)`

Parameters

* **pixel\_values** (`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](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/auto#transformers.AutoImageProcessor). See [ConditionalDetrImageProcessor.**call**()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/deit#transformers.DeiTFeatureExtractor.__call__) for details.
* **pixel\_mask** (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*) — Mask to avoid performing attention on padding pixel values. Mask values selected in `[0, 1]`:

  * 1 for pixels that are real (i.e. **not masked**),
  * 0 for pixels that are padding (i.e. **masked**).

  [What are attention masks?](https://huggingface.co/docs/transformers/glossary#attention-mask)
* **decoder\_attention\_mask** (`torch.FloatTensor` of shape `(batch_size, num_queries)`, *optional*) — Not used by default. Can be used to mask object queries.
* **encoder\_outputs** (`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.
* **inputs\_embeds** (`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.
* **decoder\_inputs\_embeds** (`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.
* **output\_attentions** (`bool`, *optional*) — Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail.
* **output\_hidden\_states** (`bool`, *optional*) — Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail.
* **return\_dict** (`bool`, *optional*) — Whether or not to return a [ModelOutput](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.utils.ModelOutput) instead of a plain tuple.

Returns

`transformers.models.conditional_detr.modeling_conditional_detr.ConditionalDetrModelOutput` or `tuple(torch.FloatTensor)`

A `transformers.models.conditional_detr.modeling_conditional_detr.ConditionalDetrModelOutput` 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 ([ConditionalDetrConfig](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrConfig)) and inputs.

* **last\_hidden\_state** (`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.
* **decoder\_hidden\_states** (`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.
* **decoder\_attentions** (`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.
* **cross\_attentions** (`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.
* **encoder\_last\_hidden\_state** (`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.
* **encoder\_hidden\_states** (`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.
* **encoder\_attentions** (`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.
* **intermediate\_hidden\_states** (`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.

The [ConditionalDetrModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrModel) 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:

Copied

```
>>> 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("microsoft/conditional-detr-resnet-50")
>>> model = AutoModel.from_pretrained("microsoft/conditional-detr-resnet-50")

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

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

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

### ConditionalDetrForObjectDetection

#### class transformers.ConditionalDetrForObjectDetection

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/conditional_detr/modeling_conditional_detr.py#L1773)

( config: ConditionalDetrConfig )

Parameters

* **config** ([ConditionalDetrConfig](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

CONDITIONAL\_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](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/model#transformers.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](https://pytorch.org/docs/stable/nn.html#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.

**forward**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/conditional_detr/modeling_conditional_detr.py#L1799)

( pixel\_values: FloatTensorpixel\_mask: typing.Optional\[torch.LongTensor] = Nonedecoder\_attention\_mask: typing.Optional\[torch.LongTensor] = Noneencoder\_outputs: typing.Optional\[torch.FloatTensor] = Noneinputs\_embeds: typing.Optional\[torch.FloatTensor] = Nonedecoder\_inputs\_embeds: typing.Optional\[torch.FloatTensor] = Nonelabels: typing.Optional\[typing.List\[dict]] = Noneoutput\_attentions: typing.Optional\[bool] = Noneoutput\_hidden\_states: typing.Optional\[bool] = Nonereturn\_dict: typing.Optional\[bool] = None ) → `transformers.models.conditional_detr.modeling_conditional_detr.ConditionalDetrObjectDetectionOutput` or `tuple(torch.FloatTensor)`

Parameters

* **pixel\_values** (`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](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/auto#transformers.AutoImageProcessor). See [ConditionalDetrImageProcessor.**call**()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/deit#transformers.DeiTFeatureExtractor.__call__) for details.
* **pixel\_mask** (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*) — Mask to avoid performing attention on padding pixel values. Mask values selected in `[0, 1]`:

  * 1 for pixels that are real (i.e. **not masked**),
  * 0 for pixels that are padding (i.e. **masked**).

  [What are attention masks?](https://huggingface.co/docs/transformers/glossary#attention-mask)
* **decoder\_attention\_mask** (`torch.FloatTensor` of shape `(batch_size, num_queries)`, *optional*) — Not used by default. Can be used to mask object queries.
* **encoder\_outputs** (`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.
* **inputs\_embeds** (`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.
* **decoder\_inputs\_embeds** (`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.
* **output\_attentions** (`bool`, *optional*) — Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail.
* **output\_hidden\_states** (`bool`, *optional*) — Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail.
* **return\_dict** (`bool`, *optional*) — Whether or not to return a [ModelOutput](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.utils.ModelOutput) instead of a plain tuple.
* **labels** (`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.conditional_detr.modeling_conditional_detr.ConditionalDetrObjectDetectionOutput` or `tuple(torch.FloatTensor)`

A `transformers.models.conditional_detr.modeling_conditional_detr.ConditionalDetrObjectDetectionOutput` 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 ([ConditionalDetrConfig](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrConfig)) and inputs.

* **loss** (`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.
* **loss\_dict** (`Dict`, *optional*) — A dictionary containing the individual losses. Useful for logging.
* **logits** (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes + 1)`) — Classification logits (including no-object) for all queries.
* **pred\_boxes** (`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()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrFeatureExtractor.post_process_object_detection) to retrieve the unnormalized bounding boxes.
* **auxiliary\_outputs** (`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.
* **last\_hidden\_state** (`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.
* **decoder\_hidden\_states** (`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.
* **decoder\_attentions** (`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.
* **cross\_attentions** (`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.
* **encoder\_last\_hidden\_state** (`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.
* **encoder\_hidden\_states** (`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.
* **encoder\_attentions** (`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 [ConditionalDetrForObjectDetection](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrForObjectDetection) 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:

Copied

```
>>> 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("microsoft/conditional-detr-resnet-50")
>>> model = AutoModelForObjectDetection.from_pretrained("microsoft/conditional-detr-resnet-50")

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

>>> outputs = model(**inputs)

>>> # convert outputs (bounding boxes and class logits) to COCO API
>>> 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 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]
```

### ConditionalDetrForSegmentation

#### class transformers.ConditionalDetrForSegmentation

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/conditional_detr/modeling_conditional_detr.py#L1961)

( config: ConditionalDetrConfig )

Parameters

* **config** ([ConditionalDetrConfig](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

CONDITIONAL\_DETR Model (consisting of a backbone and encoder-decoder Transformer) with a segmentation head on top, for tasks such as COCO panoptic.

This model inherits from [PreTrainedModel](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/model#transformers.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](https://pytorch.org/docs/stable/nn.html#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.

**forward**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/conditional_detr/modeling_conditional_detr.py#L1983)

( pixel\_values: FloatTensorpixel\_mask: typing.Optional\[torch.LongTensor] = Nonedecoder\_attention\_mask: typing.Optional\[torch.FloatTensor] = Noneencoder\_outputs: typing.Optional\[torch.FloatTensor] = Noneinputs\_embeds: typing.Optional\[torch.FloatTensor] = Nonedecoder\_inputs\_embeds: typing.Optional\[torch.FloatTensor] = Nonelabels: typing.Optional\[typing.List\[dict]] = Noneoutput\_attentions: typing.Optional\[bool] = Noneoutput\_hidden\_states: typing.Optional\[bool] = Nonereturn\_dict: typing.Optional\[bool] = None ) → `transformers.models.conditional_detr.modeling_conditional_detr.ConditionalDetrSegmentationOutput` or `tuple(torch.FloatTensor)`

Parameters

* **pixel\_values** (`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](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/auto#transformers.AutoImageProcessor). See [ConditionalDetrImageProcessor.**call**()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/deit#transformers.DeiTFeatureExtractor.__call__) for details.
* **pixel\_mask** (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*) — Mask to avoid performing attention on padding pixel values. Mask values selected in `[0, 1]`:

  * 1 for pixels that are real (i.e. **not masked**),
  * 0 for pixels that are padding (i.e. **masked**).

  [What are attention masks?](https://huggingface.co/docs/transformers/glossary#attention-mask)
* **decoder\_attention\_mask** (`torch.FloatTensor` of shape `(batch_size, num_queries)`, *optional*) — Not used by default. Can be used to mask object queries.
* **encoder\_outputs** (`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.
* **inputs\_embeds** (`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.
* **decoder\_inputs\_embeds** (`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.
* **output\_attentions** (`bool`, *optional*) — Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail.
* **output\_hidden\_states** (`bool`, *optional*) — Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail.
* **return\_dict** (`bool`, *optional*) — Whether or not to return a [ModelOutput](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.utils.ModelOutput) instead of a plain tuple.
* **labels** (`List[Dict]` of len `(batch_size,)`, *optional*) — Labels for computing the bipartite matching loss, DICE/F-1 loss and Focal loss. List of dicts, each dictionary containing at least the following 3 keys: ‘class\_labels’, ‘boxes’ and ‘masks’ (the class labels, bounding boxes and segmentation masks 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,)`, the boxes a `torch.FloatTensor` of shape `(number of bounding boxes in the image, 4)` and the masks a `torch.FloatTensor` of shape `(number of bounding boxes in the image, height, width)`.

Returns

`transformers.models.conditional_detr.modeling_conditional_detr.ConditionalDetrSegmentationOutput` or `tuple(torch.FloatTensor)`

A `transformers.models.conditional_detr.modeling_conditional_detr.ConditionalDetrSegmentationOutput` 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 ([ConditionalDetrConfig](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrConfig)) and inputs.

* **loss** (`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.
* **loss\_dict** (`Dict`, *optional*) — A dictionary containing the individual losses. Useful for logging.
* **logits** (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes + 1)`) — Classification logits (including no-object) for all queries.
* **pred\_boxes** (`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()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrFeatureExtractor.post_process_object_detection) to retrieve the unnormalized bounding boxes.
* **pred\_masks** (`torch.FloatTensor` of shape `(batch_size, num_queries, height/4, width/4)`) — Segmentation masks logits for all queries. See also [post\_process\_semantic\_segmentation()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrFeatureExtractor.post_process_semantic_segmentation) or [post\_process\_instance\_segmentation()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrFeatureExtractor.post_process_instance_segmentation) [post\_process\_panoptic\_segmentation()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrFeatureExtractor.post_process_panoptic_segmentation) to evaluate semantic, instance and panoptic segmentation masks respectively.
* **auxiliary\_outputs** (`list[Dict]`, *optional*) — Optional, only returned when auxiliary 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.
* **last\_hidden\_state** (`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.
* **decoder\_hidden\_states** (`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.
* **decoder\_attentions** (`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.
* **cross\_attentions** (`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.
* **encoder\_last\_hidden\_state** (`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.
* **encoder\_hidden\_states** (`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.
* **encoder\_attentions** (`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 [ConditionalDetrForSegmentation](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/conditional_detr#transformers.ConditionalDetrForSegmentation) 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:

Copied

```
>>> import io
>>> import requests
>>> from PIL import Image
>>> import torch
>>> import numpy

>>> from transformers import (
...     AutoImageProcessor,
...     ConditionalDetrConfig,
...     ConditionalDetrForSegmentation,
... )
>>> from transformers.image_transforms import rgb_to_id

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

>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/conditional-detr-resnet-50")

>>> # randomly initialize all weights of the model
>>> config = ConditionalDetrConfig()
>>> model = ConditionalDetrForSegmentation(config)

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

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

>>> # Use the `post_process_panoptic_segmentation` method of the `image_processor` to retrieve post-processed panoptic segmentation maps
>>> # Segmentation results are returned as a list of dictionaries
>>> result = image_processor.post_process_panoptic_segmentation(outputs, target_sizes=[(300, 500)])
>>> # A tensor of shape (height, width) where each value denotes a segment id, filled with -1 if no segment is found
>>> panoptic_seg = result[0]["segmentation"]
>>> # Get prediction score and segment_id to class_id mapping of each segment
>>> panoptic_segments_info = result[0]["segments_info"]
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://boinc-ai.gitbook.io/transformers/api/models/vision-models/conditional-detr.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
