# DETR

## Overview

DETR モデルは、[Transformers を使用したエンドツーエンドのオブジェクト検出](https://huggingface.co/papers/2005.12872) で提案されました。
Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov and Sergey Zagoruyko ルイコ。 DETR
畳み込みバックボーンと、その後にエンドツーエンドでトレーニングできるエンコーダー/デコーダー Transformer で構成されます。
物体の検出。 Faster-R-CNN や Mask-R-CNN などのモデルの複雑さの多くが大幅に簡素化されます。
領域提案、非最大抑制手順、アンカー生成などです。さらに、DETR は次のようにすることもできます。
デコーダ出力の上にマスク ヘッドを追加するだけで、パノプティック セグメンテーションを実行できるように自然に拡張されています。

論文の要約は次のとおりです。

*物体検出を直接集合予測問題として見る新しい方法を紹介します。私たちのアプローチは、
検出パイプラインにより、非最大抑制などの多くの手作業で設計されたコンポーネントの必要性が効果的に排除されます。
タスクに関する事前の知識を明示的にエンコードするプロシージャまたはアンカーの生成。の主な成分は、
DEtection TRansformer または DETR と呼ばれる新しいフレームワークは、セットベースのグローバル損失であり、
二部マッチング、およびトランスフォーマー エンコーダー/デコーダー アーキテクチャ。学習されたオブジェクト クエリの固定された小さなセットが与えられると、
DETR は、オブジェクトとグローバル イメージ コンテキストの関係について推論し、最終セットを直接出力します。
並行して予想も。新しいモデルは概念的にシンプルであり、多くのモデルとは異なり、特殊なライブラリを必要としません。
他の最新の検出器。 DETR は、確立された、および同等の精度と実行時のパフォーマンスを実証します。
困難な COCO 物体検出データセットに基づく、高度に最適化された Faster RCNN ベースライン。さらに、DETR は簡単に実行できます。
統一された方法でパノプティック セグメンテーションを生成するために一般化されました。競合他社を大幅に上回るパフォーマンスを示しています
ベースライン*

このモデルは、[nielsr](https://huggingface.co/nielsr) によって提供されました。元のコードは [こちら](https://github.com/facebookresearch/detr) にあります。

## How DETR works

[DetrForObjectDetection](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForObjectDetection) がどのように機能するかを説明する TLDR は次のとおりです。

まず、事前にトレーニングされた畳み込みバックボーンを通じて画像が送信されます (論文では、著者らは次のように使用しています)。
ResNet-50/ResNet-101)。バッチ ディメンションも追加すると仮定します。これは、バックボーンへの入力が
画像に 3 つのカラー チャネル (RGB) があると仮定した場合の、形状 `(batch_size, 3, height, width)` のテンソル。 CNNのバックボーン
通常は `(batch_size, 2048, height/32, width/32)` の形状の、新しい低解像度の特徴マップを出力します。これは
次に、DETR の Transformer の隠れ次元 (デフォルトでは `256`) に一致するように投影されます。
`nn.Conv2D` レイヤー。これで、形状 `(batch_size, 256, height/32, width/32)` のテンソルが完成しました。
特徴マップは平坦化および転置され、形状 `(batch_size, seq_len, d_model)` のテンソルを取得します =
`(batch_size, width/32*height/32, 256)`。したがって、NLP モデルとの違いは、シーケンスの長さが実際には
通常よりも長くなりますが、「d_model」は小さくなります (NLP では通常 768 以上です)。

次に、これがエンコーダを介して送信され、同じ形状の `encoder_hidden_​​states` が出力されます (次のように考えることができます)。
これらは画像の特徴として）。次に、いわゆる **オブジェクト クエリ**がデコーダを通じて送信されます。これは形状のテンソルです
`(batch_size, num_queries, d_model)`。通常、`num_queries` は 100 に設定され、ゼロで初期化されます。
これらの入力埋め込みは学習された位置エンコーディングであり、作成者はこれをオブジェクト クエリと呼び、同様に
エンコーダでは、それらは各アテンション層の入力に追加されます。各オブジェクト クエリは特定のオブジェクトを検索します。
画像では。デコーダは、複数のセルフ アテンション レイヤとエンコーダ デコーダ アテンション レイヤを通じてこれらの埋め込みを更新します。
同じ形状の `decoder_hidden_​​states` を出力します: `(batch_size, num_queries, d_model)`。次に頭が２つ
オブジェクト検出のために上部に追加されます。各オブジェクト クエリをオブジェクトの 1 つに分類するための線形レイヤー、または「いいえ」
オブジェクト」、および各クエリの境界ボックスを予測する MLP。

モデルは **2 部マッチング損失**を使用してトレーニングされます。つまり、実際に行うことは、予測されたクラスを比較することです +
グラウンド トゥルース アノテーションに対する N = 100 個の各オブジェクト クエリの境界ボックス (同じ長さ N までパディング)
(したがって、画像にオブジェクトが 4 つしか含まれていない場合、96 個の注釈にはクラスとして「オブジェクトなし」、およびクラスとして「境界ボックスなし」が含まれるだけになります。
境界ボックス)。 [Hungarian matching algorithm](https://en.wikipedia.org/wiki/Hungarian_algorithm) は、検索に使用されます。
N 個のクエリのそれぞれから N 個の注釈のそれぞれへの最適な 1 対 1 のマッピング。次に、標準クロスエントロピー (
クラス)、および L1 と [generalized IoU loss](https://giou.stanford.edu/) の線形結合 (
境界ボックス) は、モデルのパラメーターを最適化するために使用されます。

DETR は、パノプティック セグメンテーション (セマンティック セグメンテーションとインスタンスを統合する) を実行するように自然に拡張できます。
セグメンテーション）。 [DetrForSegmentation](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForSegmentation) はセグメンテーション マスク ヘッドを上に追加します
[DetrForObjectDetection](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForObjectDetection)。マスク ヘッドは、共同でトレーニングすることも、2 段階のプロセスでトレーニングすることもできます。
ここで、最初に [DetrForObjectDetection](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForObjectDetection) モデルをトレーニングして、両方の周囲の境界ボックスを検出します。
「もの」（インスタンス）と「もの」（木、道路、空などの背景のもの）をすべて凍結し、すべての重みをフリーズしてのみトレーニングします。
25 エポックのマスクヘッド。実験的には、これら 2 つのアプローチは同様の結果をもたらします。ボックスの予測は
ハンガリー語のマッチングはボックス間の距離を使用して計算されるため、トレーニングを可能にするためにはこれが必要です。

## Usage tips

- DETR は、いわゆる **オブジェクト クエリ** を使用して、画像内のオブジェクトを検出します。クエリの数によって最大値が決まります
  単一の画像内で検出できるオブジェクトの数。デフォルトでは 100 に設定されます (パラメーターを参照)
  [DetrConfig](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrConfig) の `num_queries`)。ある程度の余裕があるのは良いことです (COCO では、
  著者は 100 を使用しましたが、COCO イメージ内のオブジェクトの最大数は約 70 です)。
- DETR のデコーダーは、クエリの埋め込みを並行して更新します。これは GPT-2 のような言語モデルとは異なります。
  並列ではなく自己回帰デコードを使用します。したがって、因果的注意マスクは使用されません。
- DETR は、投影前に各セルフアテンション層とクロスアテンション層の隠れ状態に位置埋め込みを追加します。
  クエリとキーに。画像の位置埋め込みについては、固定正弦波または学習済みのどちらかを選択できます。
  絶対位置埋め込み。デフォルトでは、パラメータ `position_embedding_type` は
  [DetrConfig](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrConfig) は `"sine"` に設定されます。
- DETR の作成者は、トレーニング中に、特にデコーダで補助損失を使用すると役立つことに気づきました。
  モデルは各クラスの正しい数のオブジェクトを出力します。パラメータ `auxiliary_loss` を設定すると、
  [DetrConfig](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrConfig) を`True`に設定し、フィードフォワード ニューラル ネットワークとハンガリー損失を予測します
  は各デコーダ層の後に追加されます (FFN がパラメータを共有する)。
- 複数のノードにわたる分散環境でモデルをトレーニングする場合は、
  _modeling_detr.py_ の _DetrLoss_ クラスの _num_boxes_ 変数。複数のノードでトレーニングする場合、これは次のようにする必要があります
  元の実装で見られるように、すべてのノードにわたるターゲット ボックスの平均数に設定されます [こちら](https://github.com/facebookresearch/detr/blob/a54b77800eb8e64e3ad0d8237789fcbf2f8350c5/models/detr.py#L227-L232) 。
- [DetrForObjectDetection](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForObjectDetection) および [DetrForSegmentation](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForSegmentation) は次のように初期化できます。
  [timm ライブラリ](https://github.com/rwightman/pytorch-image-models) で利用可能な畳み込みバックボーン。
  たとえば、MobileNet バックボーンを使用した初期化は、次の `backbone` 属性を設定することで実行できます。
  [DetrConfig](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrConfig) を `"tf_mobilenetv3_small_075"` に設定し、それを使用してモデルを初期化します。
  構成。
- DETR は、最短辺が一定のピクセル数以上になり、最長辺が一定量以上になるように入力画像のサイズを変更します。
  最大 1333 ピクセル。トレーニング時に、最短辺がランダムに に設定されるようにスケール拡張が使用されます。
  最小 480、最大 800 ピクセル。推論時には、最短辺が 800 に設定されます。

使用できます
  [DetrImageProcessor](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrImageProcessor) 用の画像 (およびオプションの COCO 形式の注釈) を準備します。
  モデル。このサイズ変更により、バッチ内の画像のサイズが異なる場合があります。 DETR は、画像を最大までパディングすることでこの問題を解決します。
  どのピクセルが実数でどのピクセルがパディングであるかを示すピクセル マスクを作成することによって、バッチ内の最大サイズを決定します。
  あるいは、画像をバッチ処理するためにカスタムの `collat​​e_fn` を定義することもできます。
  `~transformers.DetrImageProcessor.pad_and_create_pixel_mask`。
- 画像のサイズによって使用されるメモリの量が決まり、したがって「batch_size」も決まります。
  GPU あたり 2 のバッチ サイズを使用することをお勧めします。詳細については、[この Github スレッド](https://github.com/facebookresearch/detr/issues/150) を参照してください。

DETR モデルをインスタンス化するには 3 つの方法があります (好みに応じて)。

オプション 1: モデル全体の事前トレーニングされた重みを使用して DETR をインスタンス化する

```py
>>> from transformers import DetrForObjectDetection

>>> model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
```

オプション 2: Transformer についてはランダムに初期化された重みを使用して DETR をインスタンス化しますが、バックボーンについては事前にトレーニングされた重みを使用します

```py
>>> from transformers import DetrConfig, DetrForObjectDetection

>>> config = DetrConfig()
>>> model = DetrForObjectDetection(config)
```

オプション 3: バックボーン + トランスフォーマーのランダムに初期化された重みを使用して DETR をインスタンス化します。

```py
>>> config = DetrConfig(use_pretrained_backbone=False)
>>> model = DetrForObjectDetection(config)
```

| Task | Object detection | Instance segmentation | Panoptic segmentation |
|------|------------------|-----------------------|-----------------------|
| **Description** |画像内のオブジェクトの周囲の境界ボックスとクラス ラベルを予測する | 画像内のオブジェクト (つまりインスタンス) の周囲のマスクを予測する | 画像内のオブジェクト (インスタンス) と「もの」 (木や道路などの背景) の両方の周囲のマスクを予測します |
| **Model** | [DetrForObjectDetection](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForObjectDetection) | [DetrForSegmentation](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForSegmentation) | [DetrForSegmentation](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForSegmentation) |
| **Example dataset** | COCO detection | COCO detection, COCO panoptic | COCO panoptic  |                                                                        |
| **Format of annotations to provide to**  [DetrImageProcessor](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrImageProcessor) | {'image_id': `int`, 'annotations': `list[Dict]`} each Dict being a COCO object annotation  | {'image_id': `int`, 'annotations': `list[Dict]`}  (in case of COCO detection) or {'file_name': `str`, 'image_id': `int`, 'segments_info': `list[Dict]`} (in case of COCO panoptic) | {'file_name': `str`, 'image_id': `int`, 'segments_info': `list[Dict]`} and masks_path (path to directory containing PNG files of the masks) |
| **Postprocessing** (i.e. converting the output of the model to Pascal VOC format) | `post_process()` | `post_process_segmentation()` | `post_process_segmentation()`, `post_process_panoptic()` |
| **evaluators** | `CocoEvaluator` with `iou_types="bbox"` | `CocoEvaluator` with `iou_types="bbox"` or `"segm"` | `CocoEvaluator` with `iou_tupes="bbox"` or `"segm"`, `PanopticEvaluator` |

つまり、COCO 検出または COCO パノプティック形式でデータを準備してから、次を使用する必要があります。
[DetrImageProcessor](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrImageProcessor) `pixel_values`、`pixel_mask`、およびオプションを作成します。
「ラベル」。これを使用してモデルをトレーニング (または微調整) できます。評価するには、まず、
[DetrImageProcessor](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrImageProcessor) の後処理メソッドの 1 つを使用したモデルの出力。これらはできます
`CocoEvaluator` または `PanopticEvaluator` のいずれかに提供され、次のようなメトリクスを計算できます。
平均平均精度 (mAP) とパノラマ品質 (PQ)。後者のオブジェクトは [元のリポジトリ](https://github.com/facebookresearch/detr) に実装されています。評価の詳細については、[サンプル ノートブック](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/DETR) を参照してください。

## Resources

DETR の使用を開始するのに役立つ公式 Hugging Face およびコミュニティ (🌎 で示されている) リソースのリスト。

<PipelineTag pipeline="object-detection"/>

- カスタム データセットの [DetrForObjectDetection](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForObjectDetection) と [DetrForSegmentation](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForSegmentation) の微調整を説明するすべてのサンプル ノートブックは、[こちら](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/DETR) で見つけることができます。 。
- 参照: [オブジェクト検出タスク ガイド](../tasks/object_detection)

ここに含めるリソースの送信に興味がある場合は、お気軽にプル リクエストを開いてください。審査させていただきます。リソースは、既存のリソースを複製するのではなく、何か新しいものを示すことが理想的です。

## DetrConfig[[transformers.DetrConfig]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class transformers.DetrConfig</name><anchor>transformers.DetrConfig</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/detr/configuration_detr.py#L32</source><parameters>[{"name": "use_timm_backbone", "val": " = True"}, {"name": "backbone_config", "val": " = None"}, {"name": "num_channels", "val": " = 3"}, {"name": "num_queries", "val": " = 100"}, {"name": "encoder_layers", "val": " = 6"}, {"name": "encoder_ffn_dim", "val": " = 2048"}, {"name": "encoder_attention_heads", "val": " = 8"}, {"name": "decoder_layers", "val": " = 6"}, {"name": "decoder_ffn_dim", "val": " = 2048"}, {"name": "decoder_attention_heads", "val": " = 8"}, {"name": "encoder_layerdrop", "val": " = 0.0"}, {"name": "decoder_layerdrop", "val": " = 0.0"}, {"name": "is_encoder_decoder", "val": " = True"}, {"name": "activation_function", "val": " = 'relu'"}, {"name": "d_model", "val": " = 256"}, {"name": "dropout", "val": " = 0.1"}, {"name": "attention_dropout", "val": " = 0.0"}, {"name": "activation_dropout", "val": " = 0.0"}, {"name": "init_std", "val": " = 0.02"}, {"name": "init_xavier_std", "val": " = 1.0"}, {"name": "auxiliary_loss", "val": " = False"}, {"name": "position_embedding_type", "val": " = 'sine'"}, {"name": "backbone", "val": " = 'resnet50'"}, {"name": "use_pretrained_backbone", "val": " = True"}, {"name": "backbone_kwargs", "val": " = None"}, {"name": "dilation", "val": " = False"}, {"name": "class_cost", "val": " = 1"}, {"name": "bbox_cost", "val": " = 5"}, {"name": "giou_cost", "val": " = 2"}, {"name": "mask_loss_coefficient", "val": " = 1"}, {"name": "dice_loss_coefficient", "val": " = 1"}, {"name": "bbox_loss_coefficient", "val": " = 5"}, {"name": "giou_loss_coefficient", "val": " = 2"}, {"name": "eos_coefficient", "val": " = 0.1"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **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 [DetrModel](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrModel) can
  detect in a single image. For COCO, we recommend 100 queries.
- **d_model** (`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.
- **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://huggingface.co/papers/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://huggingface.co/papers/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 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.
- **use_pretrained_backbone** (`bool`, *optional*, `True`) --
  Whether to use pretrained weights for the backbone.
- **backbone_kwargs** (`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.
- **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.</paramsdesc><paramgroups>0</paramgroups></docstring>

This is the configuration class to store the configuration of a [DetrModel](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrModel). It is used to instantiate a 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 DETR
[facebook/detr-resnet-50](https://huggingface.co/facebook/detr-resnet-50) architecture.

Configuration objects inherit from [PretrainedConfig](/docs/transformers/v4.57.0/ja/main_classes/configuration#transformers.PretrainedConfig) and can be used to control the model outputs. Read the
documentation from [PretrainedConfig](/docs/transformers/v4.57.0/ja/main_classes/configuration#transformers.PretrainedConfig) for more information.



<ExampleCodeBlock anchor="transformers.DetrConfig.example">

Examples:

```python
>>> from transformers import DetrConfig, DetrModel

>>> # Initializing a DETR facebook/detr-resnet-50 style configuration
>>> configuration = DetrConfig()

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

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

</ExampleCodeBlock>


<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>from_backbone_config</name><anchor>transformers.DetrConfig.from_backbone_config</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/detr/configuration_detr.py#L263</source><parameters>[{"name": "backbone_config", "val": ": PretrainedConfig"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **backbone_config** ([PretrainedConfig](/docs/transformers/v4.57.0/ja/main_classes/configuration#transformers.PretrainedConfig)) --
  The backbone configuration.</paramsdesc><paramgroups>0</paramgroups><rettype>[DetrConfig](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrConfig)</rettype><retdesc>An instance of a configuration object</retdesc></docstring>
Instantiate a [DetrConfig](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrConfig) (or a derived class) from a pre-trained backbone model configuration.








</div></div>

## DetrImageProcessor[[transformers.DetrImageProcessor]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class transformers.DetrImageProcessor</name><anchor>transformers.DetrImageProcessor</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/detr/image_processing_detr.py#L790</source><parameters>[{"name": "format", "val": ": typing.Union[str, transformers.image_utils.AnnotationFormat] = <AnnotationFormat.COCO_DETECTION: 'coco_detection'>"}, {"name": "do_resize", "val": ": bool = True"}, {"name": "size", "val": ": typing.Optional[dict[str, int]] = None"}, {"name": "resample", "val": ": Resampling = <Resampling.BILINEAR: 2>"}, {"name": "do_rescale", "val": ": bool = True"}, {"name": "rescale_factor", "val": ": typing.Union[int, float] = 0.00392156862745098"}, {"name": "do_normalize", "val": ": bool = True"}, {"name": "image_mean", "val": ": typing.Union[float, list[float], NoneType] = None"}, {"name": "image_std", "val": ": typing.Union[float, list[float], NoneType] = None"}, {"name": "do_convert_annotations", "val": ": typing.Optional[bool] = None"}, {"name": "do_pad", "val": ": bool = True"}, {"name": "pad_size", "val": ": typing.Optional[dict[str, int]] = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **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. 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`.
- **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** (`bool`, *optional*, defaults to True) --
  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_convert_annotations** (`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.
- **do_pad** (`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.
- **pad_size** (`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.</paramsdesc><paramgroups>0</paramgroups></docstring>

Constructs a Detr image processor.





<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>preprocess</name><anchor>transformers.DetrImageProcessor.preprocess</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/detr/image_processing_detr.py#L1239</source><parameters>[{"name": "images", "val": ": typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]"}, {"name": "annotations", "val": ": typing.Union[dict[str, typing.Union[int, str, list[dict]]], list[dict[str, typing.Union[int, str, list[dict]]]], NoneType] = None"}, {"name": "return_segmentation_masks", "val": ": typing.Optional[bool] = None"}, {"name": "masks_path", "val": ": typing.Union[str, pathlib.Path, NoneType] = None"}, {"name": "do_resize", "val": ": typing.Optional[bool] = None"}, {"name": "size", "val": ": typing.Optional[dict[str, int]] = None"}, {"name": "resample", "val": " = None"}, {"name": "do_rescale", "val": ": typing.Optional[bool] = None"}, {"name": "rescale_factor", "val": ": typing.Union[int, float, NoneType] = None"}, {"name": "do_normalize", "val": ": typing.Optional[bool] = None"}, {"name": "do_convert_annotations", "val": ": typing.Optional[bool] = None"}, {"name": "image_mean", "val": ": typing.Union[float, list[float], NoneType] = None"}, {"name": "image_std", "val": ": typing.Union[float, list[float], NoneType] = None"}, {"name": "do_pad", "val": ": typing.Optional[bool] = None"}, {"name": "format", "val": ": typing.Union[str, transformers.image_utils.AnnotationFormat, NoneType] = None"}, {"name": "return_tensors", "val": ": typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None"}, {"name": "data_format", "val": ": typing.Union[str, transformers.image_utils.ChannelDimension] = <ChannelDimension.FIRST: 'channels_first'>"}, {"name": "input_data_format", "val": ": typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None"}, {"name": "pad_size", "val": ": typing.Optional[dict[str, int]] = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **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'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`.
- **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.
- **do_convert_annotations** (`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.
- **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. 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.
- **format** (`str` or `AnnotationFormat`, *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.
- **pad_size** (`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.</paramsdesc><paramgroups>0</paramgroups></docstring>

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




</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>post_process_object_detection</name><anchor>transformers.DetrImageProcessor.post_process_object_detection</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/detr/image_processing_detr.py#L1775</source><parameters>[{"name": "outputs", "val": ""}, {"name": "threshold", "val": ": float = 0.5"}, {"name": "target_sizes", "val": ": typing.Union[transformers.utils.generic.TensorType, list[tuple]] = None"}]</parameters><paramsdesc>- **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 unset, predictions will not be resized.</paramsdesc><paramgroups>0</paramgroups><rettype>`list[Dict]`</rettype><retdesc>A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
in the batch as predicted by the model.</retdesc></docstring>

Converts the raw output of [DetrForObjectDetection](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForObjectDetection) into final bounding boxes in (top_left_x, top_left_y,
bottom_right_x, bottom_right_y) format. Only supports PyTorch.








</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>post_process_semantic_segmentation</name><anchor>transformers.DetrImageProcessor.post_process_semantic_segmentation</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/detr/image_processing_detr.py#L1828</source><parameters>[{"name": "outputs", "val": ""}, {"name": "target_sizes", "val": ": typing.Optional[list[tuple[int, int]]] = None"}]</parameters><paramsdesc>- **outputs** ([DetrForSegmentation](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForSegmentation)) --
  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.</paramsdesc><paramgroups>0</paramgroups><rettype>`list[torch.Tensor]`</rettype><retdesc>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.</retdesc></docstring>

Converts the output of [DetrForSegmentation](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForSegmentation) into semantic segmentation maps. Only supports PyTorch.








</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>post_process_instance_segmentation</name><anchor>transformers.DetrImageProcessor.post_process_instance_segmentation</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/detr/image_processing_detr.py#L1876</source><parameters>[{"name": "outputs", "val": ""}, {"name": "threshold", "val": ": float = 0.5"}, {"name": "mask_threshold", "val": ": float = 0.5"}, {"name": "overlap_mask_area_threshold", "val": ": float = 0.8"}, {"name": "target_sizes", "val": ": typing.Optional[list[tuple[int, int]]] = None"}, {"name": "return_coco_annotation", "val": ": typing.Optional[bool] = False"}]</parameters><paramsdesc>- **outputs** ([DetrForSegmentation](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForSegmentation)) --
  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.</paramsdesc><paramgroups>0</paramgroups><rettype>`list[Dict]`</rettype><retdesc>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`.</retdesc></docstring>

Converts the output of [DetrForSegmentation](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForSegmentation) into instance segmentation predictions. Only supports PyTorch.








</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>post_process_panoptic_segmentation</name><anchor>transformers.DetrImageProcessor.post_process_panoptic_segmentation</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/detr/image_processing_detr.py#L1960</source><parameters>[{"name": "outputs", "val": ""}, {"name": "threshold", "val": ": float = 0.5"}, {"name": "mask_threshold", "val": ": float = 0.5"}, {"name": "overlap_mask_area_threshold", "val": ": float = 0.8"}, {"name": "label_ids_to_fuse", "val": ": typing.Optional[set[int]] = None"}, {"name": "target_sizes", "val": ": typing.Optional[list[tuple[int, int]]] = None"}]</parameters><paramsdesc>- **outputs** ([DetrForSegmentation](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForSegmentation)) --
  The outputs from [DetrForSegmentation](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForSegmentation).
- **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.</paramsdesc><paramgroups>0</paramgroups><rettype>`list[Dict]`</rettype><retdesc>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`.</retdesc></docstring>

Converts the output of [DetrForSegmentation](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForSegmentation) into image panoptic segmentation predictions. Only supports
PyTorch.








</div></div>

## DetrImageProcessorFast[[transformers.DetrImageProcessorFast]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class transformers.DetrImageProcessorFast</name><anchor>transformers.DetrImageProcessorFast</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/detr/image_processing_detr_fast.py#L285</source><parameters>[{"name": "**kwargs", "val": ": typing_extensions.Unpack[transformers.models.detr.image_processing_detr_fast.DetrFastImageProcessorKwargs]"}]</parameters></docstring>

Constructs a fast Detr image processor.



<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>preprocess</name><anchor>transformers.DetrImageProcessorFast.preprocess</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/detr/image_processing_detr_fast.py#L557</source><parameters>[{"name": "images", "val": ": typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]"}, {"name": "annotations", "val": ": typing.Union[dict[str, typing.Union[int, str, list[dict]]], list[dict[str, typing.Union[int, str, list[dict]]]], NoneType] = None"}, {"name": "masks_path", "val": ": typing.Union[str, pathlib.Path, NoneType] = None"}, {"name": "**kwargs", "val": ": typing_extensions.Unpack[transformers.models.detr.image_processing_detr_fast.DetrFastImageProcessorKwargs]"}]</parameters><paramsdesc>- **images** (`Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]`) --
  Image 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.
- **masks_path** (`str` or `pathlib.Path`, *optional*) --
  Path to the directory containing the segmentation masks.
- **do_resize** (`bool`, *optional*) --
  Whether to resize the image.
- **size** (`dict[str, int]`, *optional*) --
  Describes the maximum input dimensions to the model.
- **default_to_square** (`bool`, *optional*) --
  Whether to default to a square image when resizing, if size is an int.
- **resample** (`Union[PILImageResampling, F.InterpolationMode, NoneType]`) --
  Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
  has an effect if `do_resize` is set to `True`.
- **do_center_crop** (`bool`, *optional*) --
  Whether to center crop the image.
- **crop_size** (`dict[str, int]`, *optional*) --
  Size of the output image after applying `center_crop`.
- **do_rescale** (`bool`, *optional*) --
  Whether to rescale the image.
- **rescale_factor** (`Union[int, float, NoneType]`) --
  Rescale factor to rescale the image by if `do_rescale` is set to `True`.
- **do_normalize** (`bool`, *optional*) --
  Whether to normalize the image.
- **image_mean** (`Union[float, list[float], NoneType]`) --
  Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
- **image_std** (`Union[float, list[float], NoneType]`) --
  Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
  `True`.
- **do_pad** (`bool`, *optional*) --
  Whether to pad the image. Padding is done either to the largest size in the batch
  or to a fixed square size per image. The exact padding strategy depends on the model.
- **pad_size** (`dict[str, int]`, *optional*) --
  The size in `{"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. Applied only when `do_pad=True.`
- **do_convert_rgb** (`bool`, *optional*) --
  Whether to convert the image to RGB.
- **return_tensors** (`Union[str, ~utils.generic.TensorType, NoneType]`) --
  Returns stacked tensors if set to `pt, otherwise returns a list of tensors.
- **data_format** (`~image_utils.ChannelDimension`, *optional*) --
  Only `ChannelDimension.FIRST` is supported. Added for compatibility with slow processors.
- **input_data_format** (`Union[str, ~image_utils.ChannelDimension, NoneType]`) --
  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.
- **device** (`torch.device`, *optional*) --
  The device to process the images on. If unset, the device is inferred from the input images.
- **disable_grouping** (`bool`, *optional*) --
  Whether to disable grouping of images by size to process them individually and not in batches.
  If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on
  empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157
- **format** (`str`, *optional*, defaults to `AnnotationFormat.COCO_DETECTION`) --
  Data format of the annotations. One of "coco_detection" or "coco_panoptic".
- **do_convert_annotations** (`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.
- **return_segmentation_masks** (`bool`, *optional*, defaults to `False`) --
  Whether to return segmentation masks.</paramsdesc><paramgroups>0</paramgroups><rettype>`<class 'transformers.image_processing_base.BatchFeature'>`</rettype><retdesc>- **data** (`dict`) -- Dictionary of lists/arrays/tensors returned by the __call__ method ('pixel_values', etc.).
- **tensor_type** (`Union[None, str, TensorType]`, *optional*) -- You can give a tensor_type here to convert the lists of integers in PyTorch/TensorFlow/Numpy Tensors at
  initialization.</retdesc></docstring>







</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>post_process_object_detection</name><anchor>transformers.DetrImageProcessorFast.post_process_object_detection</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/detr/image_processing_detr_fast.py#L984</source><parameters>[{"name": "outputs", "val": ""}, {"name": "threshold", "val": ": float = 0.5"}, {"name": "target_sizes", "val": ": typing.Union[transformers.utils.generic.TensorType, list[tuple]] = None"}]</parameters><paramsdesc>- **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 unset, predictions will not be resized.</paramsdesc><paramgroups>0</paramgroups><rettype>`list[Dict]`</rettype><retdesc>A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
in the batch as predicted by the model.</retdesc></docstring>

Converts the raw output of [DetrForObjectDetection](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForObjectDetection) into final bounding boxes in (top_left_x, top_left_y,
bottom_right_x, bottom_right_y) format. Only supports PyTorch.








</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>post_process_semantic_segmentation</name><anchor>transformers.DetrImageProcessorFast.post_process_semantic_segmentation</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/detr/image_processing_detr_fast.py#L1038</source><parameters>[{"name": "outputs", "val": ""}, {"name": "target_sizes", "val": ": typing.Optional[list[tuple[int, int]]] = None"}]</parameters><paramsdesc>- **outputs** ([DetrForSegmentation](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForSegmentation)) --
  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.</paramsdesc><paramgroups>0</paramgroups><rettype>`list[torch.Tensor]`</rettype><retdesc>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.</retdesc></docstring>

Converts the output of [DetrForSegmentation](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForSegmentation) into semantic segmentation maps. Only supports PyTorch.








</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>post_process_instance_segmentation</name><anchor>transformers.DetrImageProcessorFast.post_process_instance_segmentation</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/detr/image_processing_detr_fast.py#L1086</source><parameters>[{"name": "outputs", "val": ""}, {"name": "threshold", "val": ": float = 0.5"}, {"name": "mask_threshold", "val": ": float = 0.5"}, {"name": "overlap_mask_area_threshold", "val": ": float = 0.8"}, {"name": "target_sizes", "val": ": typing.Optional[list[tuple[int, int]]] = None"}, {"name": "return_coco_annotation", "val": ": typing.Optional[bool] = False"}]</parameters><paramsdesc>- **outputs** ([DetrForSegmentation](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForSegmentation)) --
  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.</paramsdesc><paramgroups>0</paramgroups><rettype>`list[Dict]`</rettype><retdesc>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`.</retdesc></docstring>

Converts the output of [DetrForSegmentation](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForSegmentation) into instance segmentation predictions. Only supports PyTorch.








</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>post_process_panoptic_segmentation</name><anchor>transformers.DetrImageProcessorFast.post_process_panoptic_segmentation</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/detr/image_processing_detr_fast.py#L1170</source><parameters>[{"name": "outputs", "val": ""}, {"name": "threshold", "val": ": float = 0.5"}, {"name": "mask_threshold", "val": ": float = 0.5"}, {"name": "overlap_mask_area_threshold", "val": ": float = 0.8"}, {"name": "label_ids_to_fuse", "val": ": typing.Optional[set[int]] = None"}, {"name": "target_sizes", "val": ": typing.Optional[list[tuple[int, int]]] = None"}]</parameters><paramsdesc>- **outputs** ([DetrForSegmentation](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForSegmentation)) --
  The outputs from [DetrForSegmentation](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForSegmentation).
- **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.</paramsdesc><paramgroups>0</paramgroups><rettype>`list[Dict]`</rettype><retdesc>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`.</retdesc></docstring>

Converts the output of [DetrForSegmentation](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForSegmentation) into image panoptic segmentation predictions. Only supports
PyTorch.








</div></div>

## DetrFeatureExtractor[[transformers.DetrFeatureExtractor]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class transformers.DetrFeatureExtractor</name><anchor>transformers.DetrFeatureExtractor</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/detr/feature_extraction_detr.py#L38</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters></docstring>



<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>__call__</name><anchor>transformers.DetrFeatureExtractor.__call__</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/image_processing_utils.py#L49</source><parameters>[{"name": "images", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters></docstring>
Preprocess an image or a batch of images.

</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>post_process_object_detection</name><anchor>transformers.DetrFeatureExtractor.post_process_object_detection</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/detr/image_processing_detr.py#L1775</source><parameters>[{"name": "outputs", "val": ""}, {"name": "threshold", "val": ": float = 0.5"}, {"name": "target_sizes", "val": ": typing.Union[transformers.utils.generic.TensorType, list[tuple]] = None"}]</parameters><paramsdesc>- **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 unset, predictions will not be resized.</paramsdesc><paramgroups>0</paramgroups><rettype>`list[Dict]`</rettype><retdesc>A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
in the batch as predicted by the model.</retdesc></docstring>

Converts the raw output of [DetrForObjectDetection](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForObjectDetection) into final bounding boxes in (top_left_x, top_left_y,
bottom_right_x, bottom_right_y) format. Only supports PyTorch.








</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>post_process_semantic_segmentation</name><anchor>transformers.DetrFeatureExtractor.post_process_semantic_segmentation</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/detr/image_processing_detr.py#L1828</source><parameters>[{"name": "outputs", "val": ""}, {"name": "target_sizes", "val": ": typing.Optional[list[tuple[int, int]]] = None"}]</parameters><paramsdesc>- **outputs** ([DetrForSegmentation](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForSegmentation)) --
  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.</paramsdesc><paramgroups>0</paramgroups><rettype>`list[torch.Tensor]`</rettype><retdesc>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.</retdesc></docstring>

Converts the output of [DetrForSegmentation](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForSegmentation) into semantic segmentation maps. Only supports PyTorch.








</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>post_process_instance_segmentation</name><anchor>transformers.DetrFeatureExtractor.post_process_instance_segmentation</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/detr/image_processing_detr.py#L1876</source><parameters>[{"name": "outputs", "val": ""}, {"name": "threshold", "val": ": float = 0.5"}, {"name": "mask_threshold", "val": ": float = 0.5"}, {"name": "overlap_mask_area_threshold", "val": ": float = 0.8"}, {"name": "target_sizes", "val": ": typing.Optional[list[tuple[int, int]]] = None"}, {"name": "return_coco_annotation", "val": ": typing.Optional[bool] = False"}]</parameters><paramsdesc>- **outputs** ([DetrForSegmentation](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForSegmentation)) --
  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.</paramsdesc><paramgroups>0</paramgroups><rettype>`list[Dict]`</rettype><retdesc>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`.</retdesc></docstring>

Converts the output of [DetrForSegmentation](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForSegmentation) into instance segmentation predictions. Only supports PyTorch.








</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>post_process_panoptic_segmentation</name><anchor>transformers.DetrFeatureExtractor.post_process_panoptic_segmentation</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/detr/image_processing_detr.py#L1960</source><parameters>[{"name": "outputs", "val": ""}, {"name": "threshold", "val": ": float = 0.5"}, {"name": "mask_threshold", "val": ": float = 0.5"}, {"name": "overlap_mask_area_threshold", "val": ": float = 0.8"}, {"name": "label_ids_to_fuse", "val": ": typing.Optional[set[int]] = None"}, {"name": "target_sizes", "val": ": typing.Optional[list[tuple[int, int]]] = None"}]</parameters><paramsdesc>- **outputs** ([DetrForSegmentation](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForSegmentation)) --
  The outputs from [DetrForSegmentation](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForSegmentation).
- **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.</paramsdesc><paramgroups>0</paramgroups><rettype>`list[Dict]`</rettype><retdesc>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`.</retdesc></docstring>

Converts the output of [DetrForSegmentation](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForSegmentation) into image panoptic segmentation predictions. Only supports
PyTorch.








</div></div>

## DETR specific outputs[[transformers.models.detr.modeling_detr.DetrModelOutput]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class transformers.models.detr.modeling_detr.DetrModelOutput</name><anchor>transformers.models.detr.modeling_detr.DetrModelOutput</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/detr/modeling_detr.py#L77</source><parameters>[{"name": "last_hidden_state", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "past_key_values", "val": ": typing.Optional[transformers.cache_utils.EncoderDecoderCache] = None"}, {"name": "decoder_hidden_states", "val": ": typing.Optional[tuple[torch.FloatTensor, ...]] = None"}, {"name": "decoder_attentions", "val": ": typing.Optional[tuple[torch.FloatTensor, ...]] = None"}, {"name": "cross_attentions", "val": ": typing.Optional[tuple[torch.FloatTensor, ...]] = None"}, {"name": "encoder_last_hidden_state", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "encoder_hidden_states", "val": ": typing.Optional[tuple[torch.FloatTensor, ...]] = None"}, {"name": "encoder_attentions", "val": ": typing.Optional[tuple[torch.FloatTensor, ...]] = None"}, {"name": "intermediate_hidden_states", "val": ": typing.Optional[torch.FloatTensor] = None"}]</parameters><paramsdesc>- **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.
- **past_key_values** (`~cache_utils.EncoderDecoderCache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) --
  It is a `Cache` instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).

  Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
  `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values`
  input) to speed up sequential decoding.
- **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, if the model has an embedding layer, +
  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, if the model has an embedding layer, +
  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.</paramsdesc><paramgroups>0</paramgroups></docstring>

Base class for outputs of the DETR encoder-decoder model. This class adds one attribute to Seq2SeqModelOutput,
namely an optional stack of intermediate decoder activations, i.e. the output of each decoder layer, each of them
gone through a layernorm. This is useful when training the model with auxiliary decoding losses.



</div>

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class transformers.models.detr.modeling_detr.DetrObjectDetectionOutput</name><anchor>transformers.models.detr.modeling_detr.DetrObjectDetectionOutput</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/detr/modeling_detr.py#L95</source><parameters>[{"name": "loss", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "loss_dict", "val": ": typing.Optional[dict] = None"}, {"name": "logits", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "pred_boxes", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "auxiliary_outputs", "val": ": typing.Optional[list[dict]] = None"}, {"name": "last_hidden_state", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "decoder_hidden_states", "val": ": typing.Optional[tuple[torch.FloatTensor]] = None"}, {"name": "decoder_attentions", "val": ": typing.Optional[tuple[torch.FloatTensor]] = None"}, {"name": "cross_attentions", "val": ": typing.Optional[tuple[torch.FloatTensor]] = None"}, {"name": "encoder_last_hidden_state", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "encoder_hidden_states", "val": ": typing.Optional[tuple[torch.FloatTensor]] = None"}, {"name": "encoder_attentions", "val": ": typing.Optional[tuple[torch.FloatTensor]] = None"}]</parameters><paramsdesc>- **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()](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrImageProcessor.post_process_object_detection) to retrieve the
  unnormalized bounding boxes.
- **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, if the model has an embedding layer, +
  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*, defaults to `None`) --
  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, if the model has an embedding layer, +
  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.</paramsdesc><paramgroups>0</paramgroups></docstring>

Output type of [DetrForObjectDetection](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForObjectDetection).



</div>

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class transformers.models.detr.modeling_detr.DetrSegmentationOutput</name><anchor>transformers.models.detr.modeling_detr.DetrSegmentationOutput</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/detr/modeling_detr.py#L138</source><parameters>[{"name": "loss", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "loss_dict", "val": ": typing.Optional[dict] = None"}, {"name": "logits", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "pred_boxes", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "pred_masks", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "auxiliary_outputs", "val": ": typing.Optional[list[dict]] = None"}, {"name": "last_hidden_state", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "decoder_hidden_states", "val": ": typing.Optional[tuple[torch.FloatTensor]] = None"}, {"name": "decoder_attentions", "val": ": typing.Optional[tuple[torch.FloatTensor]] = None"}, {"name": "cross_attentions", "val": ": typing.Optional[tuple[torch.FloatTensor]] = None"}, {"name": "encoder_last_hidden_state", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "encoder_hidden_states", "val": ": typing.Optional[tuple[torch.FloatTensor]] = None"}, {"name": "encoder_attentions", "val": ": typing.Optional[tuple[torch.FloatTensor]] = None"}]</parameters><paramsdesc>- **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()](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrImageProcessor.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()](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrImageProcessor.post_process_semantic_segmentation) or
  [post_process_instance_segmentation()](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrImageProcessor.post_process_instance_segmentation)
  [post_process_panoptic_segmentation()](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrImageProcessor.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, if the model has an embedding layer, +
  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*, defaults to `None`) --
  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, if the model has an embedding layer, +
  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.</paramsdesc><paramgroups>0</paramgroups></docstring>

Output type of [DetrForSegmentation](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForSegmentation).



</div>

## DetrModel[[transformers.DetrModel]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class transformers.DetrModel</name><anchor>transformers.DetrModel</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/detr/modeling_detr.py#L1039</source><parameters>[{"name": "config", "val": ": DetrConfig"}]</parameters><paramsdesc>- **config** ([DetrConfig](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrConfig)) --
  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()](/docs/transformers/v4.57.0/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.</paramsdesc><paramgroups>0</paramgroups></docstring>

The bare 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](/docs/transformers/v4.57.0/ja/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.





<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>forward</name><anchor>transformers.DetrModel.forward</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/detr/modeling_detr.py#L1070</source><parameters>[{"name": "pixel_values", "val": ": FloatTensor"}, {"name": "pixel_mask", "val": ": typing.Optional[torch.LongTensor] = None"}, {"name": "decoder_attention_mask", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "encoder_outputs", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "inputs_embeds", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "decoder_inputs_embeds", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "output_attentions", "val": ": typing.Optional[bool] = None"}, {"name": "output_hidden_states", "val": ": typing.Optional[bool] = None"}, {"name": "return_dict", "val": ": typing.Optional[bool] = None"}]</parameters><paramsdesc>- **pixel_values** (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`) --
  The tensors corresponding to the input images. Pixel values can be obtained using
  [DetrImageProcessor](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrImageProcessor). See [DetrImageProcessor.__call__()](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrFeatureExtractor.__call__) for details (`processor_class` uses
  [DetrImageProcessor](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrImageProcessor) for processing images).
- **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?](../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** (`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](/docs/transformers/v4.57.0/ja/main_classes/output#transformers.utils.ModelOutput) instead of a plain tuple.</paramsdesc><paramgroups>0</paramgroups><rettype>[transformers.models.detr.modeling_detr.DetrModelOutput](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.models.detr.modeling_detr.DetrModelOutput) or `tuple(torch.FloatTensor)`</rettype><retdesc>A [transformers.models.detr.modeling_detr.DetrModelOutput](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.models.detr.modeling_detr.DetrModelOutput) 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 ([DetrConfig](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrConfig)) 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.
- **past_key_values** (`~cache_utils.EncoderDecoderCache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) -- It is a `Cache` instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).

  Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
  `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values`
  input) to speed up sequential decoding.
- **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, if the model has an embedding layer, +
  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, if the model has an embedding layer, +
  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.</retdesc></docstring>
The [DetrModel](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrModel) forward method, overrides the `__call__` special method.

<Tip>

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.

</Tip>







<ExampleCodeBlock anchor="transformers.DetrModel.forward.example">

Examples:

```python
>>> from transformers import AutoImageProcessor, DetrModel
>>> 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("facebook/detr-resnet-50")
>>> model = DetrModel.from_pretrained("facebook/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, 100, 256]
```

</ExampleCodeBlock>

</div></div>

## DetrForObjectDetection[[transformers.DetrForObjectDetection]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class transformers.DetrForObjectDetection</name><anchor>transformers.DetrForObjectDetection</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/detr/modeling_detr.py#L1231</source><parameters>[{"name": "config", "val": ": DetrConfig"}]</parameters><paramsdesc>- **config** ([DetrConfig](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrConfig)) --
  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()](/docs/transformers/v4.57.0/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.</paramsdesc><paramgroups>0</paramgroups></docstring>

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](/docs/transformers/v4.57.0/ja/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.





<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>forward</name><anchor>transformers.DetrForObjectDetection.forward</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/detr/modeling_detr.py#L1249</source><parameters>[{"name": "pixel_values", "val": ": FloatTensor"}, {"name": "pixel_mask", "val": ": typing.Optional[torch.LongTensor] = None"}, {"name": "decoder_attention_mask", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "encoder_outputs", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "inputs_embeds", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "decoder_inputs_embeds", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "labels", "val": ": typing.Optional[list[dict]] = None"}, {"name": "output_attentions", "val": ": typing.Optional[bool] = None"}, {"name": "output_hidden_states", "val": ": typing.Optional[bool] = None"}, {"name": "return_dict", "val": ": typing.Optional[bool] = None"}]</parameters><paramsdesc>- **pixel_values** (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`) --
  The tensors corresponding to the input images. Pixel values can be obtained using
  [DetrImageProcessor](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrImageProcessor). See [DetrImageProcessor.__call__()](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrFeatureExtractor.__call__) for details (`processor_class` uses
  [DetrImageProcessor](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrImageProcessor) for processing images).
- **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?](../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** (`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.
- **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)`.
- **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](/docs/transformers/v4.57.0/ja/main_classes/output#transformers.utils.ModelOutput) instead of a plain tuple.</paramsdesc><paramgroups>0</paramgroups><rettype>[transformers.models.detr.modeling_detr.DetrObjectDetectionOutput](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.models.detr.modeling_detr.DetrObjectDetectionOutput) or `tuple(torch.FloatTensor)`</rettype><retdesc>A [transformers.models.detr.modeling_detr.DetrObjectDetectionOutput](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.models.detr.modeling_detr.DetrObjectDetectionOutput) 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 ([DetrConfig](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrConfig)) 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()](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrImageProcessor.post_process_object_detection) to retrieve the
  unnormalized bounding boxes.
- **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, if the model has an embedding layer, +
  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*, defaults to `None`) -- 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, if the model has an embedding layer, +
  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.</retdesc></docstring>
The [DetrForObjectDetection](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForObjectDetection) forward method, overrides the `__call__` special method.

<Tip>

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.

</Tip>







<ExampleCodeBlock anchor="transformers.DetrForObjectDetection.forward.example">

Examples:

```python
>>> from transformers import AutoImageProcessor, DetrForObjectDetection
>>> import torch
>>> from PIL import Image
>>> import requests

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

>>> image_processor = AutoImageProcessor.from_pretrained("facebook/detr-resnet-50")
>>> model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")

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

>>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
>>> target_sizes = torch.tensor([image.size[::-1]])
>>> results = image_processor.post_process_object_detection(outputs, threshold=0.9, target_sizes=target_sizes)[
...     0
... ]

>>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
...     box = [round(i, 2) for i in box.tolist()]
...     print(
...         f"Detected {model.config.id2label[label.item()]} with confidence "
...         f"{round(score.item(), 3)} at location {box}"
...     )
Detected remote with confidence 0.998 at location [40.16, 70.81, 175.55, 117.98]
Detected remote with confidence 0.996 at location [333.24, 72.55, 368.33, 187.66]
Detected couch with confidence 0.995 at location [-0.02, 1.15, 639.73, 473.76]
Detected cat with confidence 0.999 at location [13.24, 52.05, 314.02, 470.93]
Detected cat with confidence 0.999 at location [345.4, 23.85, 640.37, 368.72]
```

</ExampleCodeBlock>

</div></div>

## DetrForSegmentation[[transformers.DetrForSegmentation]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class transformers.DetrForSegmentation</name><anchor>transformers.DetrForSegmentation</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/detr/modeling_detr.py#L1374</source><parameters>[{"name": "config", "val": ": DetrConfig"}]</parameters><paramsdesc>- **config** ([DetrConfig](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrConfig)) --
  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()](/docs/transformers/v4.57.0/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.</paramsdesc><paramgroups>0</paramgroups></docstring>

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](/docs/transformers/v4.57.0/ja/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.





<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>forward</name><anchor>transformers.DetrForSegmentation.forward</anchor><source>https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/detr/modeling_detr.py#L1395</source><parameters>[{"name": "pixel_values", "val": ": FloatTensor"}, {"name": "pixel_mask", "val": ": typing.Optional[torch.LongTensor] = None"}, {"name": "decoder_attention_mask", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "encoder_outputs", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "inputs_embeds", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "decoder_inputs_embeds", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "labels", "val": ": typing.Optional[list[dict]] = None"}, {"name": "output_attentions", "val": ": typing.Optional[bool] = None"}, {"name": "output_hidden_states", "val": ": typing.Optional[bool] = None"}, {"name": "return_dict", "val": ": typing.Optional[bool] = None"}]</parameters><paramsdesc>- **pixel_values** (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`) --
  The tensors corresponding to the input images. Pixel values can be obtained using
  [DetrImageProcessor](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrImageProcessor). See [DetrImageProcessor.__call__()](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrFeatureExtractor.__call__) for details (`processor_class` uses
  [DetrImageProcessor](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrImageProcessor) for processing images).
- **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?](../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** (`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.
- **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)`.
- **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](/docs/transformers/v4.57.0/ja/main_classes/output#transformers.utils.ModelOutput) instead of a plain tuple.</paramsdesc><paramgroups>0</paramgroups><rettype>[transformers.models.detr.modeling_detr.DetrSegmentationOutput](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.models.detr.modeling_detr.DetrSegmentationOutput) or `tuple(torch.FloatTensor)`</rettype><retdesc>A [transformers.models.detr.modeling_detr.DetrSegmentationOutput](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.models.detr.modeling_detr.DetrSegmentationOutput) 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 ([DetrConfig](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrConfig)) 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()](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrImageProcessor.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()](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrImageProcessor.post_process_semantic_segmentation) or
  [post_process_instance_segmentation()](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrImageProcessor.post_process_instance_segmentation)
  [post_process_panoptic_segmentation()](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrImageProcessor.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, if the model has an embedding layer, +
  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*, defaults to `None`) -- 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, if the model has an embedding layer, +
  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.</retdesc></docstring>
The [DetrForSegmentation](/docs/transformers/v4.57.0/ja/model_doc/detr#transformers.DetrForSegmentation) forward method, overrides the `__call__` special method.

<Tip>

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.

</Tip>







<ExampleCodeBlock anchor="transformers.DetrForSegmentation.forward.example">

Examples:

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

>>> from transformers import AutoImageProcessor, DetrForSegmentation
>>> 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("facebook/detr-resnet-50-panoptic")
>>> model = DetrForSegmentation.from_pretrained("facebook/detr-resnet-50-panoptic")

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

</ExampleCodeBlock>

</div></div>

<EditOnGithub source="https://github.com/huggingface/transformers/blob/main/docs/source/ja/model_doc/detr.md" />