# RF-DETR

[RF-DETR](https://github.com/roboflow/rf-detr)は、リアルタイム物体検出において支配的なYOLOシリーズと競い、それを上回ることを目的に設計されたReceptive Field Detection Transformer (DETR) アーキテクチャを提案しています。最新のTransformerの進歩と効率的な設計選択を組み合わせることで、速度（レイテンシ）と精度（mAP）の間の新たな最良のバランスを実現しています。

RF-DETRアーキテクチャは、シンプルで効率的な構造が特徴です。DINOv2バックボーン、プロジェクター、そして浅いDETRデコーダーで構成されています。以下のコアな変更により、DETRアーキテクチャの効率性と速度を向上させています。

1. **DINOv2 Backbone**: 強力な DINOv2 バックボーンを使用して、堅牢な特徴量抽出を行います。
2. **Group DETR Training**: 学習時にGroup-Wise One-to-Many Assignmentを利用することで、収束を高速化します。
3. **より豊富な入力**: バックボーンから多層の特徴量を集約し、YOLOv8と同様にC2f Projectorを使用してマルチスケールの特徴量を伝達します。
4. **Faster Decoder**: 低レイテンシを実現するために、変形クロスアテンションを備えた浅い3層のDETRデコーダーを採用しています。
5. **最適化されたクエリ**: 学習可能なコンテンツクエリと生成された空間クエリを組み合わせた混合クエリ方式を使用します。

利用可能なRF-DETRのチェックポイントはすべて、[Roboflow](https://huggingface.co/Roboflow)組織の下で確認できます。元のコードは[こちら](https://github.com/roboflow/rf-detr)で確認できます。

重み変換マッピングのおかげで、RfDetr は元の [rf-detr](https://github.com/roboflow/rf-detr) ライブラリのモデルだけでなく、[Roboflow](https://roboflow.com/) プラットフォームで学習したモデルにも対応しています。つまり、Roboflow プラットフォームでモデルを学習し、`transformers` の `RfDetr` を使って重みをインポートして、どこでもモデルをデプロイできます。

> [!TIP]
>
> 右側のサイドバーにあるRF-DETRモデルをクリックすると、RF-DETRをさまざまな物体検出タスクに適用する方法の例をさらに確認できます。

以下の例では、[Pipeline](/docs/transformers/main/ja/main_classes/pipelines#transformers.Pipeline)と[AutoModel](/docs/transformers/main/ja/model_doc/auto#transformers.AutoModel)クラスを使用してオブジェクト検出を実行する方法を示しています。

```python
from transformers import pipeline
import torch

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

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

```python
from transformers import AutoImageProcessor, AutoModelForObjectDetection
from PIL import Image
from huggingface_hub.utils import httpx
from io import BytesIO
import torch

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

image_processor = AutoImageProcessor.from_pretrained("Roboflow/rf-detr-medium")
model = AutoModelForObjectDetection.from_pretrained("Roboflow/rf-detr-medium", device_map="auto")

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

with torch.no_grad():
    outputs = model(**inputs)

results = image_processor.post_process_object_detection(outputs, target_sizes=torch.tensor([image.size[::-1]]), threshold=0.3)

for result in results:
    for score, label_id, box in zip(result["scores"], result["labels"], result["boxes"]):
        score, label = score.item(), label_id.item()
        box = [round(i, 2) for i in box.tolist()]
        print(f"{model.config.id2label[label]}: {score:.2f} {box}")
```

### 監督付きで結果を可視化

[supervision](https://github.com/roboflow/supervision) ライブラリを使用して、検出およびセグメンテーションの結果を可視化できます。`pip install supervision` を実行してインストールしてください。

```python
from transformers import AutoImageProcessor, AutoModelForObjectDetection
from PIL import Image
import supervision as sv

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

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

image_processor = AutoImageProcessor.from_pretrained("Roboflow/rf-detr-medium")
model = AutoModelForObjectDetection.from_pretrained("Roboflow/rf-detr-medium", device_map="auto")

inputs = image_processor(images=image, return_tensors="pt").to(model.device)

with torch.no_grad():
    outputs = model(**inputs)

results = image_processor.post_process_object_detection(
    outputs, target_sizes=torch.tensor([image.height, image.width]), threshold=0.3
)[0]

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

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

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

sv.plot_image(annotated_image)
```

```python
from transformers import AutoImageProcessor, AutoModelForInstanceSegmentation
from PIL import Image
import supervision as sv
from huggingface_hub.utils import httpx
from io import BytesIO
import torch

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

image_processor = AutoImageProcessor.from_pretrained("Roboflow/rf-detr-seg-medium")
model = AutoModelForInstanceSegmentation.from_pretrained("Roboflow/rf-detr-seg-medium", device_map="auto")

inputs = image_processor(images=image, return_tensors="pt").to(model.device)

with torch.no_grad():
    outputs = model(**inputs)

results = image_processor.post_process_instance_segmentation(
    outputs, target_sizes=[image.size[::-1]], threshold=0.3
)[0]

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

mask_annotator = sv.MaskAnnotator()
label_annotator = sv.LabelAnnotator()

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

sv.plot_image(annotated_image)
```

## リソース

- 関連項目: [オブジェクト検出タスクガイド](../tasks/object_detection)。

## RfDetrConfig[[transformers.RfDetrConfig]]

#### transformers.RfDetrConfig[[transformers.RfDetrConfig]]

```python
transformers.RfDetrConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, backbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, hidden_expansion: float = 0.5, c2f_num_blocks: int = 3, activation_function: str = 'silu', dropout: float = 0.1, decoder_ffn_dim: int = 2048, decoder_n_points: int = 4, decoder_layers: int = 3, decoder_self_attention_heads: int = 8, decoder_cross_attention_heads: int = 16, decoder_activation_function: str = 'relu', num_queries: int = 300, attention_bias: bool = True, attention_dropout: float | int = 0.0, activation_dropout: float | int = 0.0, group_detr: int = 13, init_std: float = 0.02, disable_custom_kernels: bool = True, class_cost: int | float = 2, bbox_cost: int | float = 5, giou_cost: int | float = 2, class_loss_coefficient: int | float = 1, dice_loss_coefficient: int | float = 1, bbox_loss_coefficient: int | float = 5, giou_loss_coefficient: int | float = 2, eos_coefficient: float = 0.1, focal_alpha: float = 0.25, auxiliary_loss: bool = True, d_model: int = 256, layer_norm_eps: float = 1e-05, num_feature_levels: int = 1, mask_loss_coefficient: int | float = 1, mask_point_sample_ratio: int = 16, mask_downsample_ratio: int = 4, mask_class_loss_coefficient: int | float = 5.0, mask_dice_loss_coefficient: int | float = 5.0, segmentation_head_activation_function: str = 'gelu', intermediate_size: int = 1024)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rf_detr/configuration_rf_detr.py#L103)

**パラメータ:**

backbone_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`、*optional*) : バックボーンモデルの設定です。

hidden_expansion (`float`、*任意*、デフォルトは 0.5) : プロジェクター層の隠れ次元の拡張係数。

c2f_num_blocks (`int`、*optional*、デフォルトは 3) : C2F レイヤーのブロック数。

activation_function (`str`、*任意*、デフォルトは`"silu"`) : プロジェクターで使用する非線形活性化関数。サポートされる値は`"silu"`、`"relu"`、`"gelu"`です。

dropout (`float`、*任意*、デフォルトは`0.1`) : 全 dropout 層の比率。

decoder_ffn_dim (`int`、*任意*、デフォルトは `2048`) : デコーダー内の「intermediate」（feed-forward と呼ばれることが多い）層の次元数。

decoder_n_points (`int`、*optional*、デフォルトは 4) : デコーダーの各アテンションヘッドにおける、各特徴レベルでサンプリングされるキーの数。

decoder_layers (`int`、*任意*、デフォルトは 3) : Transformer のデコーダー層数。

decoder_self_attention_heads (`int`、*optional*、デフォルトは 8) : デコーダーの自己注意層における各注意層のアテンションヘッド数。

decoder_cross_attention_heads (`int`、*optional*、デフォルトは 16) : デコーダーのクロスアテンションにおける各アテンション層のアテンションヘッド数。

decoder_activation_function (`str`、*任意*、デフォルトは`"relu"`) : デコーダーで使用する非線形活性化関数。サポートされる値は`"relu"`、`"silu"`、`"gelu"`です。

num_queries (`int`、*optional*、デフォルトは 300) : オブジェクトクエリ数、すなわち検出スロットの数です。これは、[RfDetrModel](/docs/transformers/main/ja/model_doc/rf_detr#transformers.RfDetrModel) が 1 枚の画像内で検出できるオブジェクトの最大数を表します。

attention_bias (`bool`, *任意*, デフォルトは `True`) : セルフアテンションにおいて、クエリ、キー、バリュー、出力の投影層にバイアスを使用するかどうか。

attention_dropout (`Union[float, int]`、*任意*、デフォルトは`0.0`) : 注意確率のドロップアウト率。

activation_dropout (`Union[float, int]`、*任意*、デフォルトは`0.0`) : 全結合層内の活性化に対する dropout 率。

group_detr (`int`、*optional*、デフォルトは 13) : Group DETR 注意機構のグループ数です。計算複雑性を低減するのに役立ちます。

init_std (`float`、*任意*、デフォルトは`0.02`) : すべての重み行列を初期化するためのtruncated_normal_initializerの標準偏差です。

disable_custom_kernels (`bool`、*任意*、デフォルトは`True`) : カスタム CUDA カーネルおよび CPU カーネルの使用を無効にします。PyTorch の ONNX エクスポートではカスタムカーネルがサポートされていないため、ONNX エクスポートを行うにはこのオプションが必要です。

class_cost (`Union[int, float]`、*任意*、デフォルトは `2`) : ハンガリアンマッチングのコストにおける分類誤りの相対的な重み。

bbox_cost (`Union[int, float]`、*任意*、デフォルトは`5`) : ハンガリアンマッチングのコストにおける L1 バウンディングボックス誤差の相対的な重み。

giou_cost (`Union[int, float]`、*任意*、デフォルトは `2`) : ハンガリアンマッチングのコストにおける汎化 IoU ロスの相対的な重み。

class_loss_coefficient (`float`、*任意*、デフォルト値は 1) : ハンガリアンマッチングのコストにおける分類損失の相対的な重み。

dice_loss_coefficient (`float`、*任意*、デフォルトは 1) : オブジェクト検出損失における DICE/F-1 損失の相対的な重み。

bbox_loss_coefficient (`float`, *optional*, デフォルト値は 5) : オブジェクト検出損失における L1 バウンディングボックス損失の相対的な重み。

giou_loss_coefficient (`float`、*任意*、デフォルトは 2) : オブジェクト検出損失における汎化 IoU 損失の相対的な重み。

eos_coefficient (`float`、*任意*、デフォルトは`0.1`) : オブジェクト検出損失における「no-object」クラスの相対的な分類重み。

focal_alpha (`float`、*任意*、デフォルトは `0.25`) : focal loss の Alpha パラメータです。

auxiliary_loss (`bool`, *任意*, デフォルトは `True`) : 補助的なデコーディング損失（各デコーダ層での損失）を使用するかどうかを指定します。

d_model (`int`、*任意*、デフォルトは`256`) : エンコーダ層とプーラー層のサイズ。

layer_norm_eps (`float`、*任意*、デフォルトは`1e-05`) : Layer Normalization 層で使用する epsilon。

num_feature_levels (`int`、*optional*、デフォルトは 1) : マルチスケール変形アテンションで使用される特徴レベルの数。

mask_loss_coefficient (`float`, *optional*, デフォルトは 1) : インスタンスセグメンテーションのマスク損失における Focal loss の相対的な重み。

mask_point_sample_ratio (`int`、*optional*、デフォルトは 16) : マスク損失の計算用にサンプリングする点の比率です。

mask_downsample_ratio (`int`, *optional*, デフォルトは 4) : 入力画像の解像度に対するセグメンテーションマスクのダウンサンプル比率。

mask_class_loss_coefficient (`float`, *optional*, デフォルト値は 5.0) : インスタンスセグメンテーション損失における Focal loss の相対的な重み。

mask_dice_loss_coefficient (`float`, *optional*, デフォルト値は 5.0) : インスタンスセグメンテーション損失における DICE/F-1 損失の相対的な重み。

segmentation_head_activation_function (`str`、*任意*、デフォルトは`"gelu"`) : セグメンテーションヘッドで使用される非線形活性化関数。サポートされる値は`"relu"`、`"silu"`、`"gelu"`です。

intermediate_size (`int`、*任意*、デフォルトは`1024`) : MLP 表現の次元数。

これはRfDetrModelの設定を保存するための設定クラスです。指定された引数に基づいてRf Detrモデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[Roboflow/rf-detr-base](https://huggingface.co/Roboflow/rf-detr-base)と類似した設定が得られます。

設定オブジェクトは [PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) を継承し、モデルの出力を制御するために使用できます。詳細については、[PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) のドキュメントを参照してください。

例:

```python
>>> from transformers import RfDetrConfig, RfDetrModel

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

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

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

## RfDetrDinov2Config[[transformers.RfDetrDinov2Config]]

#### transformers.RfDetrDinov2Config[[transformers.RfDetrDinov2Config]]

```python
transformers.RfDetrDinov2Config(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, hidden_size: int = 768, num_hidden_layers: int = 12, num_attention_heads: int = 12, mlp_ratio: int = 4, hidden_act: str = 'gelu', hidden_dropout_prob: float | int = 0.0, attention_probs_dropout_prob: float | int = 0.0, initializer_range: float = 0.02, layer_norm_eps: float = 1e-06, image_size: int | list[int] | tuple[int, int] = 224, patch_size: int | list[int] | tuple[int, int] = 14, num_channels: int = 3, qkv_bias: bool = True, layerscale_value: float = 1.0, drop_path_rate: float | int = 0.0, use_swiglu_ffn: bool = False, _out_features: list[str] | None = None, _out_indices: list[int] | None = None, apply_layernorm: bool = True, reshape_hidden_states: bool = True, use_mask_token: bool = True, num_windows: int = 4)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rf_detr/configuration_rf_detr.py#L30)

**パラメータ:**

hidden_size (`int`、*任意*、デフォルトは`768`) : 隠れ表現の次元数。

num_hidden_layers (`int`, *任意*, デフォルトは `12`) : Transformer デコーダーの隠れ層の数。

num_attention_heads (`int`、*任意*、デフォルトは `12`) : Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。

mlp_ratio (`int`、*任意*、デフォルトは`4`) : MLPの隠れ層次元と埋め込み次元の比率。

hidden_act (`str`、*任意*、デフォルトは`gelu`) : デコーダーで使用する非線形活性化関数（関数または文字列）。例えば、`"gelu"`、`"relu"`、`"silu"`など。

hidden_dropout_prob (`Union[float, int]`、*任意*、デフォルトは`0.0`) : embeddings、encoder、pooler 内のすべての全結合層における dropout 確率。

attention_probs_dropout_prob (`Union[float, int]`、*任意*、デフォルトは`0.0`) : 注意確率のドロップアウト率。

initializer_range (`float`、*任意*、デフォルトは`0.02`) : すべての重み行列を初期化するためのtruncated_normal_initializerの標準偏差です。

layer_norm_eps (`float`、*任意*、デフォルトは`1e-06`) : Layer Normalization 層で使用する epsilon です。

image_size (`Union[int, list[int], tuple[int, int]]`、*任意*、デフォルトは`224`) : 各画像のサイズ（解像度）。

patch_size (`Union[int, list[int], tuple[int, int]]`、*任意*、デフォルトは`14`) : 各パッチのサイズ（解像度）。

num_channels (`int`、*任意*、デフォルトは`3`) : 入力チャネル数。

qkv_bias (`bool`, *任意*, デフォルトは `True`) : クエリ、キー、バリューにバイアスを追加するかどうか。

layerscale_value (`float`、*任意*、デフォルト値は 1.0) : layer scale に使用する初期値。

drop_path_rate (`float`, *optional*, デフォルトは 0.0) : サンプルごとの Stochastic depth レート（残差層のメインパスに適用される場合）。

use_swiglu_ffn (`bool`, *任意*, デフォルトは `False`) : SwiGLUフィードフォワードニューラルネットワークを使用するかどうか。

apply_layernorm (`bool`、*任意*、デフォルトは`True`) : モデルがバックボーンとして使用される場合、特徴量マップにレイヤーノルマイズを適用するかどうかを指定します。

reshape_hidden_states (`bool`, *任意*, デフォルトは `True`) : モデルがバックボーンとして使用される場合、特徴マップを `(batch_size, d_model, height, width)` の形状の4次元テンソルにリシェープするかどうか。`False` の場合、特徴マップは `(batch_size, seq_len, d_model)` の形状の3次元テンソルになります。

use_mask_token (`bool`、*任意*、デフォルトは`True`) : embeddings で mask_token を使用するかどうか。

num_windows (`int`, *optional*, デフォルトは 4) : ウィンドウ付きアテンションに使用するウィンドウの数です。1 の場合は、ウィンドウ付きアテンションは使用されません。

これはRfDetrModelの設定を保存するための設定クラスです。指定された引数に基づいてRf Detrモデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[Roboflow/rf-detr-base](https://huggingface.co/Roboflow/rf-detr-base)と類似した設定が得られます。

設定オブジェクトは [PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) を継承し、モデルの出力を制御するために使用できます。詳細については、[PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) のドキュメントを参照してください。

例:

```python
>>> from transformers import RfDetrDinov2Config, RfDetrDinov2Backbone

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

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

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

## RfDetrImageProcessor[[transformers.RfDetrImageProcessor]]

#### transformers.RfDetrImageProcessor[[transformers.RfDetrImageProcessor]]

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

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rf_detr/image_processing_rf_detr.py#L218)

**パラメータ:**

do_convert_rgb (`bool`, *kwargs*, *optional*) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *任意*, デフォルトは `True`) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*、デフォルトは `{'shortest_edge' : 800, 'longest_edge': 1333}`): モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *optional*, デフォルトは `False`) : size が int の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `center_crop` を適用した後の出力画像のサイズ。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*、デフォルト値は`2`) : 画像のリサイズ時に使用するリサンプリングフィルタです。これは列挙型`PILImageResampling`のいずれかになります。`do_resize`が`True`に設定されている場合のみ、効果が現れます。

do_rescale (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*, デフォルトは `0.00392156862745098`) : `do_rescale` が `True` に設定されている場合、画像をリスケールするための係数。

do_normalize (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.485, 0.456, 0.406]`) : 正規化に使用する画像の平均値です。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.229, 0.224, 0.225]`) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_pad (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 画像をパディングするサイズを`{"height": int, "width" int}`で指定します。前処理に提供されたすべての画像サイズより大きい必要があります。`pad_size`が指定されない場合、バッチ内の最大の幅と高さにパディングされます。`do_pad=True.`の場合にのみ適用されます。

do_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。

disable_grouping (`bool`, *kwargs*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

image_seq_length (`int`, *kwargs*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

format (`str`、*kwargs*、*任意*、デフォルトは`AnnotationFormat.COCO_DETECTION`) : アノテーションのデータ形式。"coco_detection"または"coco_panoptic"のいずれかです。

do_convert_annotations (`bool`, *kwargs*, *optional*, デフォルトは `True`) : アノテーションを RF_DETR モデルが期待する形式に変換するかどうかを制御します。バウンディングボックスを `(center_x, center_y, width, height)` の形式に変換し、値の範囲を `[0, 1]` にします。`preprocess` メソッドの `do_convert_annotations` パラメータによって上書きできます。

RfDetrImageProcessor 画像プロセッサを構築します。

#### preprocess[[transformers.RfDetrImageProcessor.preprocess]]

```python
preprocess(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']], annotations: dict[str, int | str | list[dict]] | list[dict[str, int | str | list[dict]]] | None = None, return_segmentation_masks: bool | None = None, masks_path: str | pathlib.Path | None = None, **kwargs: *<class 'transformers.models.rf_detr.image_processing_rf_detr.RfDetrImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rf_detr/image_processing_rf_detr.py#L464)

**パラメータ:**

images (`Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]`) : 前処理対象の画像。ピクセル値が 0 から 255 の範囲にある単一の画像またはバッチの画像を想定しています。ピクセル値が 0 から 1 の範囲にある画像を渡す場合は、`do_rescale=False` を設定してください。

annotations (`AnnotationType` または `list[AnnotationType]`、*任意*) : 画像に適用されるパディングに従って変換するアノテーション。

return_segmentation_masks (`bool`、*任意*、デフォルトは `self.return_segmentation_masks`) : セグメンテーションマスクを返すかどうか。

masks_path (`str` または `pathlib.Path`、*省略可能*) : セグメンテーションマスクを含むディレクトリへのパス。

do_convert_rgb (`bool`, *kwargs*, *optional*) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *optional*) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *optional*) : size が int の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `center_crop` を適用した後の出力画像のサイズ。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*) : 画像をリサイズする場合に使用するリサンプリングフィルタ。`PILImageResampling` の列挙型のいずれかです。`do_resize` が `True` に設定されている場合のみ有効です。

do_rescale (`bool`, *kwargs*, *任意*) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*) : `do_rescale` が `True` に設定されている場合、画像をリサイズするためのリスケール係数。

do_normalize (`bool`, *kwargs*, *optional*) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の平均値。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_pad (`bool`, *kwargs*, *任意*) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 画像をパディングするサイズを`{"height": int, "width" int}`で指定します。前処理に提供されたすべての画像サイズより大きい必要があります。`pad_size`が指定されない場合、バッチ内の最大の幅と高さにパディングされます。`do_pad=True.`の場合にのみ適用されます。

do_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。

disable_grouping (`bool`, *kwargs*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

image_seq_length (`int`, *kwargs*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

format (`str`、*kwargs*、*任意*、デフォルトは`AnnotationFormat.COCO_DETECTION`) : アノテーションのデータ形式。"coco_detection"または"coco_panoptic"のいずれかです。

do_convert_annotations (`bool`, *kwargs*, *optional*, デフォルトは `True`) : アノテーションを RF_DETR モデルが期待する形式に変換するかどうかを制御します。バウンディングボックスを `(center_x, center_y, width, height)` の形式に変換し、値の範囲を `[0, 1]` にします。`preprocess` メソッドの `do_convert_annotations` パラメータによって上書きできます。

**戻り値:** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- __call__ メソッドによって返されるリスト/配列/テンソルの辞書（'pixel_values' など）。
- **tensor_type** (`Union[None, str, TensorType]`、*省略可*) -- 初期化時に PyTorch/Numpy の Tensor 内の整数リストを変換するために、ここで tensor_type を指定できます。

#### post_process_object_detection[[transformers.RfDetrImageProcessor.post_process_object_detection]]

```python
post_process_object_detection(outputs, threshold: float = 0.5, target_sizes: transformers.utils.generic.TensorType | list[tuple] | None = None, top_k: int | None = None)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rf_detr/image_processing_rf_detr.py#L606)

**パラメータ:**

outputs (`RfDetrObjectDetectionOutput`) : モデルの生出力。

threshold (`float`, *任意*) : オブジェクト検出の予測を保持するためのスコアしきい値。

target_sizes (`torch.Tensor` または `list[tuple[int, int]]`、*任意*) : 形状が `(batch_size, 2)` の Tensor、またはバッチ内の各画像のターゲットサイズ `(height, width)` を含むタプルのリスト (`tuple[int, int]`)。未設定の場合、予測結果はリサイズされません。

**戻り値:** `list[Dict]`

モデルが予測した、バッチ内の各画像のスコア、ラベル、ボックスをそれぞれ含む辞書のリスト。

[RfDetrForObjectDetection](/docs/transformers/main/ja/model_doc/rf_detr#transformers.RfDetrForObjectDetection)の生出力を、(top_left_x, top_left_y, bottom_right_x, bottom_right_y)形式の最終的なバウンディングボックスに変換します。PyTorchのみサポートしています。

#### post_process_instance_segmentation[[transformers.RfDetrImageProcessor.post_process_instance_segmentation]]

```python
post_process_instance_segmentation(outputs, threshold: float = 0.5, mask_threshold: float = 0.0, target_sizes: list[tuple[int, int]] | None = None, return_coco_annotation: bool = False, return_binary_maps: bool = False, top_k: int | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rf_detr/image_processing_rf_detr.py#L660)

**パラメータ:**

outputs ([*RfDetrInstanceSegmentationOutput*]) : モデルの生出力。

threshold (*float*、*optional*、デフォルトは 0.5) : 予測されたインスタンスマスクを保持するためのスコアしきい値。

mask_threshold (*float*、*optional*、デフォルト値は 0.0) : 予測されたマスクをバイナリ化するための閾値。

target_sizes (*list[tuple[int, int]]*, *optional*) : 各画像のターゲット`(height, width)`。未設定の場合、マスクはリサイズされません。

return_coco_annotation (*bool*、*optional*、デフォルトは *False*) : *True* の場合、テンソルではなく COCO のランレングス符号化としてセグメンテーションマップを返します。*return_binary_maps* とは排他的です。

return_binary_maps (*bool*、*optional*、デフォルトは *False*) : *True* の場合、重複の解決を行わず、検出された各インスタンスに対応するバイナリインスタンスマスクのスタックされたテンソルとしてセグメンテーションマップを返します。これは元の `rfdetr` パッケージの出力形式と一致します。*return_coco_annotation* とは排他的です。

top_k (*int*, *optional*) : スコアの閾値処理の前に評価される候補クエリの最大数。デフォルトでは、クエリの総数になります。

**戻り値:** *list[dict]*

画像ごとに1つのdictで、キーは以下の通りです:
- **segmentation** -- `int32` のセグメント ID(`-1` = 背景)の *Tensor[H, W]*、*return_binary_maps=True* の場合は bool 型バイナリマスクの *Tensor[num_instances, H, W]*、*return_coco_annotation=True* の場合は RLE 符号化のリスト。
- **segments_info** -- キーが`id`、`label_id`、`score`の辞書のリスト。

[*RfDetrForInstanceSegmentation*] の出力をインスタンスセグメンテーションの予測に変換します。

## RfDetrModel[[transformers.RfDetrModel]]

#### transformers.RfDetrModel[[transformers.RfDetrModel]]

```python
transformers.RfDetrModel(config: RfDetrConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rf_detr/modeling_rf_detr.py#L1328)

**パラメータ:**

config ([RfDetrConfig](/docs/transformers/main/ja/model_doc/rf_detr#transformers.RfDetrConfig)) : モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、[from_pretrained()](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) メソッドを確認してください。

裸の LW Detr Model（バックボーンとデコーダー Transformer で構成）は、上部に特定のヘッドを持たず、生の hidden-states を出力します。

このモデルは [PreTrainedModel](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel) を継承しています。ライブラリがすべてのモデルに対して実装している汎用的なメソッド（ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど）については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchの[torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)のサブクラスでもあります。通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

#### forward[[transformers.RfDetrModel.forward]]

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

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rf_detr/modeling_rf_detr.py#L1435)

**パラメータ:**

pixel_values (`torch.Tensor`、形状 `(batch_size, num_channels, image_size, image_size)`) : 入力画像に対応するテンソルです。ピクセル値は [RfDetrImageProcessor](/docs/transformers/main/ja/model_doc/rf_detr#transformers.RfDetrImageProcessor) を使用して取得できます。詳細は [RfDetrImageProcessor.__call__()](/docs/transformers/main/ja/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) を参照してください（`processor_class` は画像の処理に [RfDetrImageProcessor](/docs/transformers/main/ja/model_doc/rf_detr#transformers.RfDetrImageProcessor) を使用します）。

pixel_mask (`torch.LongTensor`、形状 `(batch_size, height, width)`、*任意*) : パディングピクセル値に対するアテンションの実行を回避するためのマスク。`[0, 1]` から選択されるマスク値:  - 実在するピクセル（つまり **マスクされていない**）は 1、 - パディングのピクセル（つまり **マスクされている**）は 0。  [アテンションマスクとは何ですか？](../glossary#attention-mask)

**戻り値:** `RfDetrModelOutput` または `tuple(torch.Tensor)`

`RfDetrModelOutput`、または`torch.Tensor`のタプル（`return_dict=False`が渡された場合、または`config.return_dict=False`の場合）。[RfDetrConfig](/docs/transformers/main/ja/model_doc/rf_detr#transformers.RfDetrConfig)および入力に応じて、さまざまな要素で構成されます。

RF-DETRモデルのフォワードパス。パイプラインは以下の手順で進行します。

1. バックボーンのフラット化された出力から、初期のオブジェクトクエリ埋め込みと空間位置の提案を生成します。
2. リファインされたエンコーダ段階の予測値のストレージを初期化し（マルチグループのクエリ構造に対応）、各クエリグループについてオブジェクトクエリとその座標を反復的にリファインすることで、エンコーダ段階から最も信頼度の高い候補を取得します。
3. 学習可能なクエリ特徴量と空間参照点を初期化します（推論時には効率化のため、プライマリグループに制限します）。
4. バッチ全体にわたってベースの参照点を射影し、予測された座標の補正でそれらを洗練化（デコード前に、発見されたオブジェクトの位置にアテンションをシフトさせます）、そしてターゲットクエリの特徴量をバッチの次元に一致させるように拡張します。
5. 洗練されたクエリと更新された参照点をTransformerデコーダーに渡し、マルチスケール特徴から詳細な空間コンテキストを集約します。

- **last_hidden_state** (`torch.Tensor`、形状 `(batch_size, sequence_length, hidden_size)`、*任意*) -- モデルの最終層の出力における隠れ状態のシーケンス。
- **init_reference_points** (`torch.Tensor`、形状 `(batch_size, num_queries, 4)`) -- Transformerデコーダーに渡される初期の参照点。
- **intermediate_hidden_states** (`torch.Tensor`、形状 `(batch_size, config.decoder_layers, num_queries, d_model)`) -- 中間隠れ状態のスタック（デコーダーの各層の出力）。
- **intermediate_reference_points** (`torch.Tensor`、形状 `(batch_size, config.decoder_layers, num_queries, 4)`) -- 中間参照点のスタック（デコーダーの各層の参照点）。
- **enc_outputs_class** (`torch.Tensor`、形状 `(batch_size, sequence_length, config.num_labels)`、*任意*、`config.with_box_refine=True` かつ `config.two_stage=True` の場合に返されます) -- 第1段階でスコア上位の `config.two_stage_num_proposals` 個のバウンディングボックスがリージョンプロポーザルとして選択される、予測されたバウンディングボックスのスコアです。バウンディングボックスの二値分類（すなわちフォアグラウンドとバックグラウンド）の出力です。
- **enc_outputs_coord_logits** (`torch.Tensor`、形状 `(batch_size, sequence_length, 4)`、*任意*、`config.with_box_refine=True` かつ `config.two_stage=True` の場合に返されます) -- 第1段階で予測されるバウンディングボックス座標のロジット。
- **hidden_states** (`tuple[torch.Tensor, ...]`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.Tensor` のタプル（埋め込み層を持つモデルの場合、埋め込みの出力用が 1 つ、各層の出力用が 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

  各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。
- **attentions** (`tuple[torch.Tensor, ...]`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)` です。

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
- **cross_attentions** (`tuple[torch.Tensor, ...]`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。

  クロスアテンション層のアテンション重みは、アテンションのsoftmax適用後に計算され、クロスアテンションヘッドにおける加重平均の計算に使用されます。
- **backbone_features** (`list` of `torch.Tensor` of shape `(batch_size, config.num_channels, config.image_size, config.image_size)`) -- バックボーンからの特徴量。

例:

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

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

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

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

>>> outputs = model(**inputs)

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

## RfDetrForObjectDetection[[transformers.RfDetrForObjectDetection]]

#### transformers.RfDetrForObjectDetection[[transformers.RfDetrForObjectDetection]]

```python
transformers.RfDetrForObjectDetection(config: RfDetrConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rf_detr/modeling_rf_detr.py#L1676)

**パラメータ:**

config ([RfDetrConfig](/docs/transformers/main/ja/model_doc/rf_detr#transformers.RfDetrConfig)) : モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、[from_pretrained()](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) メソッドを確認してください。

LW DETR モデル（バックボーンとデコーダーの Transformer で構成）の上部にオブジェクト検出ヘッドを備え、COCO 検出などのタスクに対応します。

このモデルは [PreTrainedModel](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel) を継承しています。ライブラリがすべてのモデルに対して実装している汎用的なメソッド（ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど）については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchの[torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)のサブクラスでもあります。通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

#### forward[[transformers.RfDetrForObjectDetection.forward]]

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

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rf_detr/modeling_rf_detr.py#L1690)

**パラメータ:**

pixel_values (`torch.Tensor`、形状 `(batch_size, num_channels, image_size, image_size)`、*任意*) : 入力画像に対応するテンソルです。ピクセル値は [RfDetrImageProcessor](/docs/transformers/main/ja/model_doc/rf_detr#transformers.RfDetrImageProcessor) を使用して取得できます。詳細は [RfDetrImageProcessor.__call__()](/docs/transformers/main/ja/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) を参照してください（`processor_class` は画像の処理に [RfDetrImageProcessor](/docs/transformers/main/ja/model_doc/rf_detr#transformers.RfDetrImageProcessor) を使用します）。

pixel_mask (`torch.LongTensor`、形状 `(batch_size, height, width)`、*任意*) : パディングピクセル値に対するアテンションの実行を回避するためのマスク。`[0, 1]` から選択されるマスク値:  - 実在するピクセル（つまり **マスクされていない**）は 1、 - パディングのピクセル（つまり **マスクされている**）は 0。  [アテンションマスクとは何ですか？](../glossary#attention-mask)

labels (`list[Dict]`、長さ `(batch_size,)`、*任意*) : 二部マッチング損失を計算するためのラベル。辞書のリストで、各辞書には少なくとも以下の 2 つのキーが含まれます: 'class_labels' と 'boxes' (それぞれバッチ内の画像のクラスラベルとバウンディングボックス)。クラスラベル自体は長さ `(number of bounding boxes in the image,)` の `torch.LongTensor` であり、ボックスは形状 `(number of bounding boxes in the image, 4)` の `torch.Tensor` である必要があります。

**戻り値:** `RfDetrObjectDetectionOutput` または `tuple(torch.Tensor)`

`RfDetrObjectDetectionOutput` または `torch.Tensor` のタプル（`return_dict=False` が渡された場合、または `config.return_dict=False` の場合）。[RfDetrConfig](/docs/transformers/main/ja/model_doc/rf_detr#transformers.RfDetrConfig) や入力に応じて、さまざまな要素で構成されます。

フォワードパスは次のように進行します:

1. ベースのRF-DETRモデルで視覚入力を処理し、transformerの最終隠れ状態と参照点の最終シーケンスを取得します。
2. 第一段階: エンコーダーが提案するオブジェクトクエリ埋め込みから、分類ロジットを生成します。
3. 第2段階: デコーダーの最終的な隠れ状態と最新の参照点を使用して、最終的な分類ラベルと洗練されたバウンディングボックスを予測します。

- **loss** (`torch.Tensor`、形状 `(1,)`、*任意*、`labels` が提供された場合に返されます) -- クラス予測の負の対数尤度（クロスエントロピー）とバウンディングボックス損失の線形結合としての総損失。後者は、L1損失と汎用スケール不変IoU損失の線形結合として定義されます。
- **loss_dict** (`Dict`, *任意*) -- 個別の損失を含む辞書です。ログ出力に便利です。
- **logits** (`torch.Tensor`、形状 `(batch_size, num_queries, num_classes + 1)`) -- すべてのクエリに対する分類 logits（no-object を含む）。
- **pred_boxes** (`torch.Tensor`、shape `(batch_size, num_queries, 4)`) -- すべてのクエリに対する正規化されたボックス座標。(center_x, center_y, width, height) で表されます。これらの値は、バッチ内の各画像のサイズに対して [0, 1] の範囲で正規化されています（パディングは考慮されません）。正規化されていないバウンディングボックスを取得するには、`~DeformableDetrProcessor.post_process_object_detection` を使用できます。
- **auxiliary_outputs** (`list[Dict]`, *optional*) -- 任意。補助損失が有効化されている場合（つまり `config.auxiliary_loss` が `True` に設定されている場合）かつラベルが提供されている場合にのみ返されます。各デコーダ層について、上記の 2 つのキー（`logits` と `pred_boxes`）を含む辞書のリストです。
- **init_reference_points** (`torch.Tensor`、形状 `(batch_size, num_queries, 4)`) -- Transformerデコーダーに渡される初期の参照点。
- **last_hidden_state** (`torch.Tensor`、形状 `(batch_size, sequence_length, hidden_size)`、*任意*) -- モデルの最終層の出力における隠れ状態のシーケンス。
- **intermediate_hidden_states** (`torch.Tensor`、形状 `(batch_size, config.decoder_layers, num_queries, d_model)`) -- 中間隠れ状態のスタック（デコーダーの各層の出力）。
- **intermediate_reference_points** (`torch.Tensor`、形状 `(batch_size, config.decoder_layers, num_queries, 4)`) -- 中間参照点のスタック（デコーダーの各層の参照点）。
- **enc_outputs_class** (`torch.Tensor`、形状 `(batch_size, sequence_length, config.num_labels)`、*任意*、`config.with_box_refine=True` かつ `config.two_stage=True` の場合に返されます) -- 第1段階でスコア上位の `config.two_stage_num_proposals` 個のバウンディングボックスがリージョンプロポーザルとして選択される、予測されたバウンディングボックスのスコアです。バウンディングボックスの二値分類（すなわちフォアグラウンドとバックグラウンド）の出力です。
- **enc_outputs_coord_logits** (`torch.Tensor`、形状 `(batch_size, sequence_length, 4)`、*任意*、`config.with_box_refine=True` かつ `config.two_stage=True` の場合に返されます) -- 第1段階で予測されるバウンディングボックス座標のロジット。
- **hidden_states** (`tuple[torch.Tensor, ...]`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.Tensor` のタプル（埋め込み層を持つモデルの場合、埋め込みの出力用が 1 つ、各層の出力用が 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

  各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。
- **attentions** (`tuple[torch.Tensor, ...]`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)` です。

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
- **cross_attentions** (`tuple[torch.Tensor, ...]`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。

  クロスアテンション層のアテンション重みは、アテンションのsoftmax適用後に計算され、クロスアテンションヘッドにおける加重平均の計算に使用されます。
- **backbone_features** (`list` of `torch.Tensor` of shape `(batch_size, config.num_channels, config.image_size, config.image_size)`) -- バックボーンからの特徴量。

例:

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

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

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

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

>>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
>>> target_sizes = torch.tensor([image.size[::-1]])
>>> results = image_processor.post_process_object_detection(outputs, threshold=0.5, target_sizes=target_sizes)[
...     0
... ]
>>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
...     box = [round(i, 2) for i in box.tolist()]
...     print(
...         f"Detected {model.config.id2label[label.item()]} with confidence "
...         f"{round(score.item(), 3)} at location {box}"
...     )
Detected cat with confidence 0.8 at location [16.5, 52.84, 318.25, 470.78]
Detected cat with confidence 0.789 at location [342.19, 24.3, 640.02, 372.25]
Detected remote with confidence 0.633 at location [40.79, 72.78, 176.76, 117.25]
```

## RfDetrForInstanceSegmentation[[transformers.RfDetrForInstanceSegmentation]]

#### transformers.RfDetrForInstanceSegmentation[[transformers.RfDetrForInstanceSegmentation]]

```python
transformers.RfDetrForInstanceSegmentation(config: RfDetrConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rf_detr/modeling_rf_detr.py#L1936)

#### forward[[transformers.RfDetrForInstanceSegmentation.forward]]

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

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rf_detr/modeling_rf_detr.py#L2018)

**パラメータ:**

pixel_values (`torch.Tensor`、形状 `(batch_size, num_channels, image_size, image_size)`、*任意*) : 入力画像に対応するテンソルです。ピクセル値は [RfDetrImageProcessor](/docs/transformers/main/ja/model_doc/rf_detr#transformers.RfDetrImageProcessor) を使用して取得できます。詳細は [RfDetrImageProcessor.__call__()](/docs/transformers/main/ja/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) を参照してください（`processor_class` は画像の処理に [RfDetrImageProcessor](/docs/transformers/main/ja/model_doc/rf_detr#transformers.RfDetrImageProcessor) を使用します）。

pixel_mask (`torch.LongTensor`、形状 `(batch_size, height, width)`、*任意*) : パディングピクセル値に対するアテンションの実行を回避するためのマスク。`[0, 1]` から選択されるマスク値:  - 実在するピクセル（つまり **マスクされていない**）は 1、 - パディングのピクセル（つまり **マスクされている**）は 0。  [アテンションマスクとは何ですか？](../glossary#attention-mask)

labels (`list[Dict]`、長さ `(batch_size,)`、*任意*) : 二部マッチング損失を計算するためのラベル。辞書のリストで、各辞書には少なくとも以下の 2 つのキーが含まれます: 'class_labels' と 'boxes' (それぞれバッチ内の画像のクラスラベルとバウンディングボックス)。クラスラベル自体は長さ `(number of bounding boxes in the image,)` の `torch.LongTensor` であり、ボックスは形状 `(number of bounding boxes in the image, 4)` の `torch.Tensor` である必要があります。

**戻り値:**

`dict[str, torch.Tensor]`

RF-DETRモデルのインスタンスセグメンテーションにおけるフォワードパス。パイプラインは以下の手順で進行します。

1. ベースのRF-DETRモデルで視覚入力を処理し、マルチスケールの空間特徴、クエリ埋め込み、およびそれらの変換履歴を取得します。
2. エンコーダーが提案するオブジェクトクエリ埋め込みから、分類ロジストおよび初期セグメンテーションマスクを生成します（第1段階）。
3. デコーダーの最後の隠れ状態（第2段階）を使用して、最終的な分類ラベルと改善されたバウンディングボックスを予測します。
4. 高解像度の空間的特徴とクエリ隠れ状態をセグメンテーションヘッドに渡して、最終的な詳細なインスタンスマスクを生成します。

## RfDetrDinov2Backbone[[transformers.RfDetrDinov2Backbone]]

#### transformers.RfDetrDinov2Backbone[[transformers.RfDetrDinov2Backbone]]

```python
transformers.RfDetrDinov2Backbone(config: RfDetrDinov2Config)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rf_detr/modeling_rf_detr.py#L472)

**パラメータ:**

config ([RfDetrDinov2Config](/docs/transformers/main/ja/model_doc/rf_detr#transformers.RfDetrDinov2Config)) : モデルのすべてのパラメータを含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、[from_pretrained()](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) メソッドを確認してください。

DETRやMaskFormerなどのフレームワークと組み合わせて使用するRfDetrDinov2バックボーン。

このモデルは [PreTrainedModel](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel) を継承しています。ライブラリがすべてのモデルに対して実装している汎用的なメソッド（ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど）については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchの[torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)のサブクラスでもあります。通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

#### forward[[transformers.RfDetrDinov2Backbone.forward]]

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

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rf_detr/modeling_rf_detr.py#L481)

**パラメータ:**

pixel_values (`torch.Tensor`、形状 `(batch_size, num_channels, image_size, image_size)`) : 入力画像に対応するテンソルです。ピクセル値は [RfDetrImageProcessor](/docs/transformers/main/ja/model_doc/rf_detr#transformers.RfDetrImageProcessor) を使用して取得できます。詳細は [RfDetrImageProcessor.__call__()](/docs/transformers/main/ja/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) を参照してください（`processor_class` は画像の処理に [RfDetrImageProcessor](/docs/transformers/main/ja/model_doc/rf_detr#transformers.RfDetrImageProcessor) を使用します）。

**戻り値:** `BackboneOutput` または `tuple(torch.Tensor)`

`BackboneOutput`または`torch.Tensor`のタプル（`return_dict=False`が渡された場合、または`config.return_dict=False`の場合）。[RfDetrConfig](/docs/transformers/main/ja/model_doc/rf_detr#transformers.RfDetrConfig)や入力に応じて、さまざまな要素で構成されます。

[RfDetrDinov2Backbone](/docs/transformers/main/ja/model_doc/rf_detr#transformers.RfDetrDinov2Backbone) の forward メソッドは、`__call__` という特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく`Module`インスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを無視してしまいます。

- **feature_maps** (`tuple(torch.Tensor)`、形状 `(batch_size, num_channels, height, width)`) -- 各ステージのフィーチャマップ。
- **hidden_states** (`tuple(torch.Tensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.Tensor` のタプル（埋め込みの出力用 1 つ + 各レイヤーの出力用 1 つ）。形状は `(batch_size, sequence_length, hidden_size)` または `(batch_size, num_channels, height, width)` で、バックボーンによって異なります。

  各ステージの出力におけるモデルのHidden-states、および初期の埋め込み出力。
- **attentions** (`tuple(torch.Tensor)`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。バックボーンがアテンションを使用する場合にのみ適用されます。

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

例:

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

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

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

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

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

