# OmDet-Turbo

## 概要

OmDet-Turboモデルは、Tiancheng Zhao、Peng Liu、Xuan He、Lu Zhang、Kyusong Lee による [Real-time Transformer-based Open-Vocabulary Detection with Efficient Fusion Head](https://huggingface.co/papers/2403.06892) で提案されました。OmDet-Turbo は RT-DETR のコンポーネントを取り入れ、高速なマルチモーダル融合モジュールを導入することで、高精度を維持しながらリアルタイムのオープンボキャブラリー物体検出を実現します。ベースモデルは、COCO のゼロショット設定で最大 100.2 FPS および 53.4 AP の性能を達成します。

論文の抄録は以下の通りです。

*エンドツーエンドのTransformerベースの検出器（DETR）は、言語モダリティの統合により、クローズドセットおよびオープンボキャブラリーの物体検出（OVD）タスクの両方で卓越した性能を示しています。しかし、その高い計算要件は、リアルタイム物体検出（OD）シナリオでの実用的な応用を妨げてきました。本論文では、OVDEvalベンチマークにおける2つの主要モデルであるOmDetとGrounding-DINOの限界を精査し、OmDet-Turboを提案します。この新しいTransformerベースのリアルタイムOVDモデルは、OmDetとGrounding-DINOで観察されたボトルネックを軽減するために設計された革新的なEfficient Fusion Head（EFH）モジュールを備えています。特に、OmDet-Turbo-Baseは、TensorRTと言語キャッシュ技術の適用により、100.2フレーム/秒（FPS）を実現しています。さらに、COCOおよびLVISデータセットにおけるゼロショットシナリオにおいて、OmDet-Turboは現在の最先端の教師ありモデルにほぼ匹敵する性能レベルを達成しています。加えて、ODinWとOVDEvalにおいて新たな最先端ベンチマークを樹立し、それぞれAP 30.1、NMS-AP 26.86を誇っています。OmDet-Turboの産業応用における実用性は、ベンチマークデータセットでの卓越した性能と優れた推論速度によって裏付けられており、リアルタイム物体検出タスクにおいて魅力的な選択肢として位置づけられています。*

 OmDet-Turboのアーキテクチャ概要。元の論文より引用。

このモデルは [yonigozlan](https://huggingface.co/yonigozlan) によって提供されました。元のコードは [こちら](https://github.com/om-ai-lab/OmDet) で確認できます。

## 使用のコツ

[Grounding DINO](grounding-dino)などのゼロショット物体検出モデルと比較して、OmDet-Turboに特有の性質として、テキスト埋め込みのキャッシュを可能にする、クラスとプロンプト埋め込みの分離構造があります。これにより、モデルにはクラスとタスクの両方が入力として必要になります。ここで、クラスは検出対象とするオブジェクトのリスト、タスクはオープンボキャブラリー検出を導くためのグラウンデッドテキストです。このアプローチはオープンボキャブラリー検出の範囲を限定し、デコーディング処理を高速化します。

[OmDetTurboProcessor](/docs/transformers/main/ja/model_doc/omdet-turbo#transformers.OmDetTurboProcessor) は、クラス、タスク、画像のトリプレットを準備するために使用されます。タスク入力は任意であり、指定されない場合は `"Detect [class1], [class2], [class3], ..."` がデフォルトとして使用されます。モデルの結果を処理するには、[OmDetTurboProcessor](/docs/transformers/main/ja/model_doc/omdet-turbo#transformers.OmDetTurboProcessor) の `post_process_grounded_object_detection` を使用できます。特筆すべき点として、この関数は入力クラスを受け取ります。他のゼロショット物体検出モデルとは異なり、クラスとタスクの埋め込みが分離されているため、後処理ステップで予測されたクラス埋め込みのデコードは不要であり、予測されたクラスを入力されたクラスと直接照合できます。

## 使用例

### 単一画像の推論

ゼロショット物体検出を単一の画像に対して実行するために、モデルを読み込み、入力を準備する方法を以下に示します。

```python
import torch
import requests
from PIL import Image

from transformers import AutoProcessor, OmDetTurboForObjectDetection

processor = AutoProcessor.from_pretrained("omlab/omdet-turbo-swin-tiny-hf")
model = OmDetTurboForObjectDetection.from_pretrained("omlab/omdet-turbo-swin-tiny-hf", device_map="auto")

url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)
text_labels = ["cat", "remote"]
inputs = processor(image, text=text_labels, return_tensors="pt").to(model.device)

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

# convert outputs (bounding boxes and class logits)
results = processor.post_process_grounded_object_detection(
    outputs,
    target_sizes=[(image.height, image.width)],
    text_labels=text_labels,
    threshold=0.3,
    nms_threshold=0.3,
)
result = results[0]
boxes, scores, text_labels = result["boxes"], result["scores"], result["text_labels"]
for box, score, text_label in zip(boxes, scores, text_labels):
    box = [round(i, 2) for i in box.tolist()]
    print(f"Detected {text_label} with confidence {round(score.item(), 3)} at location {box}")
Detected remote with confidence 0.768 at location [39.89, 70.35, 176.74, 118.04]
Detected cat with confidence 0.72 at location [11.6, 54.19, 314.8, 473.95]
Detected remote with confidence 0.563 at location [333.38, 75.77, 370.7, 187.03]
Detected cat with confidence 0.552 at location [345.15, 23.95, 639.75, 371.67]
```

### 複数画像の推論

OmDet-Turboは、バッチ内の異なるテキストプロンプトやクラスをサポートしながら、バッチ化された複数画像の推論を実行できます。

```python
import torch
import requests
from io import BytesIO
from PIL import Image
from transformers import AutoProcessor, OmDetTurboForObjectDetection

processor = AutoProcessor.from_pretrained("omlab/omdet-turbo-swin-tiny-hf")
model = OmDetTurboForObjectDetection.from_pretrained("omlab/omdet-turbo-swin-tiny-hf", device_map="auto")

url1 = "http://images.cocodataset.org/val2017/000000039769.jpg"
image1 = Image.open(BytesIO(requests.get(url1).content)).convert("RGB")
text_labels1 = ["cat", "remote"]
task1 = "Detect {}.".format(", ".join(text_labels1))

url2 = "http://images.cocodataset.org/train2017/000000257813.jpg"
image2 = Image.open(BytesIO(requests.get(url2).content)).convert("RGB")
text_labels2 = ["boat"]
task2 = "Detect everything that looks like a boat."

url3 = "https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/statue_of_liberty.jpg"
image3 = Image.open(BytesIO(requests.get(url3).content)).convert("RGB")
text_labels3 = ["statue", "trees"]
task3 = "Focus on the foreground, detect statue and trees."

inputs = processor(
    images=[image1, image2, image3],
    text=[text_labels1, text_labels2, text_labels3],
    task=[task1, task2, task3],
    return_tensors="pt",
)

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

# convert outputs (bounding boxes and class logits)
results = processor.post_process_grounded_object_detection(
    outputs,
    text_labels=[text_labels1, text_labels2, text_labels3],
    target_sizes=[(image.height, image.width) for image in [image1, image2, image3]],
    threshold=0.2,
    nms_threshold=0.3,
)

for i, result in enumerate(results):
    for score, text_label, box in zip(
        result["scores"], result["text_labels"], result["boxes"]
    ):
        box = [round(i, 1) for i in box.tolist()]
        print(
            f"Detected {text_label} with confidence "
            f"{round(score.item(), 2)} at location {box} in image {i}"
        )
Detected remote with confidence 0.77 at location [39.9, 70.4, 176.7, 118.0] in image 0
Detected cat with confidence 0.72 at location [11.6, 54.2, 314.8, 474.0] in image 0
Detected remote with confidence 0.56 at location [333.4, 75.8, 370.7, 187.0] in image 0
Detected cat with confidence 0.55 at location [345.2, 24.0, 639.8, 371.7] in image 0
Detected boat with confidence 0.32 at location [146.9, 219.8, 209.6, 250.7] in image 1
Detected boat with confidence 0.3 at location [319.1, 223.2, 403.2, 238.4] in image 1
Detected boat with confidence 0.27 at location [37.7, 220.3, 84.0, 235.9] in image 1
Detected boat with confidence 0.22 at location [407.9, 207.0, 441.7, 220.2] in image 1
Detected statue with confidence 0.73 at location [544.7, 210.2, 651.9, 502.8] in image 2
Detected trees with confidence 0.25 at location [3.9, 584.3, 391.4, 785.6] in image 2
Detected trees with confidence 0.25 at location [1.4, 621.2, 118.2, 787.8] in image 2
Detected statue with confidence 0.2 at location [428.1, 205.5, 767.3, 759.5] in image 2

```

## OmDetTurboConfig[[transformers.OmDetTurboConfig]]

#### transformers.OmDetTurboConfig[[transformers.OmDetTurboConfig]]

```python
transformers.OmDetTurboConfig(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, 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, is_encoder_decoder: bool = True, text_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, backbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, apply_layernorm_after_vision_backbone: bool = True, image_size: int | list[int] | tuple[int, int] = 640, disable_custom_kernels: bool = False, layer_norm_eps: float = 1e-05, batch_norm_eps: float = 1e-05, init_std: float = 0.02, text_projection_in_dim: int = 512, text_projection_out_dim: int = 512, task_encoder_hidden_dim: int = 1024, class_embed_dim: int = 512, class_distance_type: typing.Literal['cosine', 'dot'] = 'cosine', num_queries: int = 900, csp_activation: str = 'silu', conv_norm_activation: str = 'gelu', encoder_feedforward_activation: str = 'relu', encoder_feedforward_dropout: float | int = 0.0, encoder_dropout: float | int = 0.0, hidden_expansion: int = 1, encoder_hidden_dim: int = 256, vision_features_channels: list[int] | tuple[int, ...] = (256, 256, 256), encoder_in_channels: list[int] | tuple[int, ...] = (192, 384, 768), encoder_projection_indices: list[int] | tuple[int, ...] = (2,), encoder_attention_heads: int = 8, encoder_dim_feedforward: int = 2048, encoder_layers: int = 1, positional_encoding_temperature: int = 10000, num_feature_levels: int = 3, decoder_hidden_dim: int = 256, decoder_num_heads: int = 8, decoder_num_layers: int = 6, decoder_activation: str = 'relu', decoder_dim_feedforward: int = 2048, decoder_num_points: int = 4, decoder_dropout: float | int = 0.0, eval_size: int | None = None, learn_initial_query: bool = False, cache_size: int = 100)
```

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

**パラメータ:**

is_encoder_decoder (`bool`、*任意*、デフォルトは`True`) : モデルがエンコーダー/デコーダーとして使用されるかどうかを示します。

text_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`, *任意*) : テキストバックボーンの config オブジェクトまたは辞書。

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

apply_layernorm_after_vision_backbone (`bool`, *任意*, デフォルトは `True`) : ビジョンバックボーンの出力である特徴マップにレイヤーノルマイズを適用するかどうか。

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

disable_custom_kernels (`bool`, *任意*, デフォルトは `False`) : カスタムカーネルを無効にするかどうか。

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

batch_norm_eps (`float`、*任意*、デフォルトは`1e-05`) : バッチ正規化レイヤーで使用するepsilonです。

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

text_projection_in_dim (`int`、*optional*、デフォルトは 512) : テキスト投影の入力次元です。

text_projection_out_dim (`int`, *optional*, デフォルトは 512) : テキスト投影の出力次元です。

task_encoder_hidden_dim (`int`、*optional*、デフォルトは 1024) : タスクエンコーダーのフィードフォワード次元数です。

class_embed_dim (`int`、*optional*、デフォルトは 512) : クラス埋め込みの次元数。

class_distance_type (`str`、*任意*、デフォルトは`"cosine"`) : 予測クラスと射影クラス埋め込みを比較するための距離の種類。`"cosine"`または`"dot"`を指定できます。

num_queries (`int`、*任意*、デフォルトは 900) : クエリの数。

csp_activation (`str`、*任意*、デフォルトは`"silu"`) : エンコーダーのCross Stage Partial (CSP)ネットワークの活性化関数。

conv_norm_activation (`str`、*任意*、デフォルトは`"gelu"`) : エンコーダーのConvNormLayer層の活性化関数。

encoder_feedforward_activation (`str`、*任意*、デフォルトは`"relu"`) : エンコーダーのフィードフォワードネットワークに使用される活性化関数。

encoder_feedforward_dropout (`float`、*optional*、デフォルトは 0.0) : エンコーダーのフィードフォワードネットワークの活性化関数の後に適用される dropout レート。

encoder_dropout (`Union[float, int]`、*任意*、デフォルトは`0.0`) : すべての dropout レイヤーの比率。

hidden_expansion (`int`、*optional*、デフォルトは 1) : エンコーダー内の CSP ネットワークの隠れ層の拡張係数。

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

vision_features_channels (`tuple(int)`, *optional*, デフォルトは`[256, 256, 256]`) : デコーダーの入力として使用される、投影されたビジョン特徴のチャネル数。

encoder_in_channels (`List(int)`、*任意*、デフォルトは`[192, 384, 768]`) : エンコーダーの入力チャネル数。

encoder_projection_indices (`List(int)`、*任意*、デフォルトは`[2]`) : 各レイヤーによって射影される入力特徴量のインデックス。

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

encoder_dim_feedforward (`int`、*optional*、デフォルトは 2048) : エンコーダーのフィードフォワード次元です。

encoder_layers (`int`、*任意*、デフォルトは`1`) : Transformerエンコーダーの隠れ層の数。設定されていない場合は、`num_layers`と同じ値が使用されます。

positional_encoding_temperature (`int`、*optional*、デフォルトは 10000) : エンコーダーにおける位置エンコーディングの温度です。

num_feature_levels (`int`、*optional*、デフォルトは 3) : デコーダーのマルチスケール変形アテンションモジュールのフィーチャーレベル数。

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

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

decoder_num_layers (`int`、*任意*、デフォルトは`6`) : Transformer デコーダーの隠れ層の数。設定されていない場合は、`num_layers` と同じ値が使用されます。

decoder_activation (`str`、*任意*、デフォルトは`"relu"`) : デコーダーの活性化関数。

decoder_dim_feedforward (`int`、*optional*、デフォルトは 2048) : デコーダーのフィードフォワード次元です。

decoder_num_points (`int`, *任意*, デフォルトは 4) : デコーダーのマルチスケール変形アテンションモジュールでサンプリングされる点の数。

decoder_dropout (`float`、*optional*、デフォルトは 0.0) : デコーダーの dropout 率です。

eval_size (`tuple[int, int]`、*任意*) : stride を考慮した後に、位置埋め込みの有効な高さおよび幅を計算するために使用される高さおよび幅（RTDetr を参照）。

learn_initial_query (`bool`、*任意*、デフォルトは`False`) : 初期クエリを学習するかどうか。

cache_size (`int`、*optional*、デフォルトは 100) : クラスとプロンプトのキャッシュのサイズです。

これは Omdet TurboModel の設定を保存するための設定クラスです。指定された引数に基づいて Omdet Turbo モデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[omlab/omdet-turbo-swin-tiny-hf](https://huggingface.co/omlab/omdet-turbo-swin-tiny-hf) と同様の設定が得られます。

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

例:

```python
>>> from transformers import OmDetTurboConfig, OmDetTurboForObjectDetection

>>> # Initializing a OmDet-Turbo omlab/omdet-turbo-swin-tiny-hf style configuration
>>> configuration = OmDetTurboConfig()

>>> # Initializing a model (with random weights) from the omlab/omdet-turbo-swin-tiny-hf style configuration
>>> model = OmDetTurboForObjectDetection(configuration)

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

## OmDetTurboProcessor[[transformers.OmDetTurboProcessor]]

#### transformers.OmDetTurboProcessor[[transformers.OmDetTurboProcessor]]

```python
transformers.OmDetTurboProcessor(image_processor, tokenizer)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/omdet_turbo/processing_omdet_turbo.py#L190)

**パラメータ:**

image_processor (`DetrImageProcessor`) : 画像プロセッサは必須の入力です。

tokenizer (`CLIPTokenizer`) : トークナイザーは必須の入力です。

OmDetTurboProcessor を構築します。画像プロセッサとトークナイザーを単一のプロセッサにラップします。

[OmDetTurboProcessor](/docs/transformers/main/ja/model_doc/omdet-turbo#transformers.OmDetTurboProcessor) は、[DetrImageProcessor](/docs/transformers/main/ja/model_doc/detr#transformers.DetrImageProcessor) と [CLIPTokenizer](/docs/transformers/main/ja/model_doc/clip#transformers.CLIPTokenizer) のすべての機能を提供します。詳細については、[~DetrImageProcessor](/docs/transformers/main/ja/model_doc/detr#transformers.DetrImageProcessor) および [~CLIPTokenizer](/docs/transformers/main/ja/model_doc/clip#transformers.CLIPTokenizer) を参照してください。

#### __call__[[transformers.OmDetTurboProcessor.__call__]]

```python
__call__(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, text: list[str] | list[list[str]] | None = None, **kwargs: *<class 'transformers.models.omdet_turbo.processing_omdet_turbo.OmDetTurboProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/omdet_turbo/processing_omdet_turbo.py#L196)

**パラメータ:**

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` を設定してください。

text (`Union[list[str], list[list[str]]]`, *任意*) : エンコード対象のシーケンスまたはシーケンスのバッチです。各シーケンスは、文字列または文字列のリスト（プレトークナイズ済み文字列）であることができます。プレトークナイズ済み入力を渡す場合は、バッチ入力との曖昧さを避けるために`is_split_into_words=True`を設定してください。

task (`str`、*kwargs*、`list[str]`、`TextInput`、または`PreTokenizedInput`、*optional*) : エンコードする検出タスクの説明です。指定されない場合、`text` 入力からデフォルトのタスク説明が生成されます（例: "Detect {text}."）。単一の文字列、文字列のリスト（画像ごとに1つ）、または事前トークン化済み入力として指定できます。タスク説明は、モデルが画像内でどのオブジェクトを検出すべきかを導く役割を果たします。

return_tensors (`str` または [TensorType](/docs/transformers/main/ja/internal/file_utils#transformers.TensorType)、*optional*) : 設定されている場合、特定のフレームワークのテンソルを返します。受け入れ可能な値は以下の通りです:  - `'pt'`: PyTorch の `torch.Tensor` オブジェクトを返します。 - `'np'`: NumPy の `np.ndarray` オブジェクトを返します。

- ****kwargs** ([ProcessingKwargs](/docs/transformers/main/ja/main_classes/processors#transformers.ProcessingKwargs), *optional*) : 各モダリティ（テキスト、画像、動画、音声）の追加処理オプション。モデル固有のパラメータは上記にリストされています。サポートされている引数の完全なリストについては、TypedDict クラスを参照してください。

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

- **data** (`dict`, *任意*) -- __call__/pad メソッドによって返されるリスト/配列/テンソルの辞書（'input_values'、'attention_mask' など）。
- **tensor_type** (`Union[None, str, TensorType]`、*省略可*) -- 初期化時に PyTorch/Numpy の Tensor 内の整数リストを変換するために、ここで tensor_type を指定できます。
- **skip_tensor_conversion** (`list[str]` または `set[str]`、*任意*) -- `tensor_type` が指定されている場合でも、テンソルに変換すべきでないキーのリストまたはセット。

#### post_process_grounded_object_detection[[transformers.OmDetTurboProcessor.post_process_grounded_object_detection]]

```python
post_process_grounded_object_detection(outputs: OmDetTurboObjectDetectionOutput, text_labels: list[str] | list[list[str]] | None = None, threshold: float = 0.3, nms_threshold: float = 0.5, target_sizes: transformers.utils.generic.TensorType | list[tuple] | None = None, max_num_det: int | None = None)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/omdet_turbo/processing_omdet_turbo.py#L266)

**パラメータ:**

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

text_labels (Union[list[str], list[list[str]]], *optional*) : 入力クラスの名称です。指定されない場合、`outputs` 内の `text_labels` は `None` に設定されます。

threshold (float, デフォルト値は 0.3) : この閾値を超える信頼度スコアを持つ検出のみを返します。

nms_threshold (float, デフォルトは 0.5) : ボックスの非最大値抑制に使用する閾値。値は [0, 1] の範囲です。

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

max_num_det (`int`, *任意*) : 返す検出の最大数。

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

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

[OmDetTurboForObjectDetection](/docs/transformers/main/ja/model_doc/omdet-turbo#transformers.OmDetTurboForObjectDetection)の生出力を、(top_left_x, top_left_y, bottom_right_x, bottom_right_y)形式の最終的なバウンディングボックスに変換し、関連するテキストクラスを取得します。

## OmDetTurboForObjectDetection[[transformers.OmDetTurboForObjectDetection]]

#### transformers.OmDetTurboForObjectDetection[[transformers.OmDetTurboForObjectDetection]]

```python
transformers.OmDetTurboForObjectDetection(config: OmDetTurboConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/omdet_turbo/modeling_omdet_turbo.py#L1464)

**パラメータ:**

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

OmDetTurbo Model（ビジョンバックボーンとテキストバックボーン、およびエンコーダー・デコーダーアーキテクチャで構成され、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.OmDetTurboForObjectDetection.forward]]

```python
forward(pixel_values: FloatTensor, classes_input_ids: LongTensor, classes_attention_mask: LongTensor, tasks_input_ids: LongTensor, tasks_attention_mask: LongTensor, classes_structure: LongTensor, labels: typing.Optional[torch.LongTensor] = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/omdet_turbo/modeling_omdet_turbo.py#L1494)

**パラメータ:**

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

classes_input_ids (`torch.LongTensor`、shape `(total_classes (>= batch_size), sequence_length)`) : 言語モデルの語彙における入力クラスシーケンストークンのインデックス。各タスクに対して複数のクラスを指定できるため、トークン化されたクラスはフラット化され、クラスの構造は`classes_structure`引数で提供されます。インデックスは[OmDetTurboProcessor](/docs/transformers/main/ja/model_doc/omdet-turbo#transformers.OmDetTurboProcessor)を使用して取得できます。詳細は[OmDetTurboProcessor.__call__()](/docs/transformers/main/ja/model_doc/omdet-turbo#transformers.OmDetTurboProcessor.__call__)を参照してください。[入力IDとは何ですか？](../glossary#input-ids)

classes_attention_mask (`torch.BoolTensor`、shape `(total_classes (>= batch_size), num_classes, sequence_length)`) : クラス用のアテンションマスクです。これはバイナリマスクであり、どのトークンにアテンションを向けるべきか、向けないべきかを示します。

tasks_input_ids (`torch.LongTensor`、形状 `(batch_size, sequence_length)`) : 言語モデルの語彙における入力タスクシーケンスのトークンインデックスです。インデックスは [OmDetTurboProcessor](/docs/transformers/main/ja/model_doc/omdet-turbo#transformers.OmDetTurboProcessor) を使用して取得できます。詳細は [OmDetTurboProcessor.__call__()](/docs/transformers/main/ja/model_doc/omdet-turbo#transformers.OmDetTurboProcessor.__call__) を参照してください。 [入力IDとは何ですか？](../glossary#input-ids)

tasks_attention_mask (`torch.BoolTensor`、形状 `(batch_size, sequence_length)`) : タスク用のアテンションマスクです。どのトークンにアテンションを適用し、どのトークンに適用しないかを示すバイナリマスクです。

classes_structure (`torch.LongTensor`、shape `(batch_size)`) : クラスの構造。このテンソルは、各タスクのクラス数を示します。

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.FloatTensor` である必要があります。

output_attentions (`bool`, *任意*) : すべてのアテンション層のアテンションテンソルを返すかどうか。詳細は、返されるテンソルの `attentions` を参照してください。

output_hidden_states (`bool`, *任意*) : 全レイヤーの hidden states を返すかどうかを指定します。詳細は、返されるテンソルの `hidden_states` を参照してください。

return_dict (`bool`, *任意*) : プレーンなタプルではなく [ModelOutput](/docs/transformers/main/ja/main_classes/output#transformers.utils.ModelOutput) を返すかどうか。

**戻り値:** `OmDetTurboObjectDetectionOutput` または `tuple(torch.FloatTensor)`

`OmDetTurboObjectDetectionOutput`、または`torch.FloatTensor`のタプル（`return_dict=False`が渡された場合、または`config.return_dict=False`の場合）。設定（[OmDetTurboConfig](/docs/transformers/main/ja/model_doc/omdet-turbo#transformers.OmDetTurboConfig)）と入力に応じて、さまざまな要素で構成されます。

[OmDetTurboForObjectDetection](/docs/transformers/main/ja/model_doc/omdet-turbo#transformers.OmDetTurboForObjectDetection)のforwardメソッドは、`__call__`特殊メソッドをオーバーライドします。

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

- **loss** (`torch.FloatTensor`, *オプション*) -- 損失値。
- **decoder_coord_logits** (`torch.FloatTensor`、形状 `(batch_size, num_queries, 4)`) -- 対象物の予測座標ロジット。
- **decoder_class_logits** (`torch.FloatTensor`、shape `(batch_size, num_queries, num_classes)`) -- 対象物の予測クラス。
- **init_reference_points** (`torch.FloatTensor`、shape `(batch_size, num_queries, 4)`) -- 初期の参照点。
- **intermediate_reference_points** (`tuple[tuple[torch.FloatTensor]]`、*任意*) -- 中間参照点です。
- **encoder_coord_logits** (`torch.FloatTensor`、shape `(batch_size, num_queries, 4)`) -- エンコーダーによるオブジェクトの予測座標。
- **encoder_class_logits** (`tuple[torch.FloatTensor]`、*optional*) -- エンコーダーによるオブジェクトの予測クラス。
- **encoder_extracted_states** (`torch.FloatTensor`、*任意*) -- エンコーダーの Feature Pyramid Network (FPN) と Path Aggregation Network (PAN) から抽出された状態です。
- **decoder_hidden_states** (`tuple[torch.FloatTensor]`、*optional*) -- `torch.FloatTensor` のタプル（埋め込みの出力用 1 つ + 各層の出力用 1 つ）で、形状は `(batch_size, sequence_length, hidden_size)` です。各層の出力におけるモデルの隠れ状態と、初期埋め込みの出力を含みます。
- **decoder_attentions** (`tuple[tuple[torch.FloatTensor]]`, *オプション*) -- 各層の注意機構に対応する `torch.FloatTensor` のタプルのタプルで、形状は `(batch_size, num_heads, sequence_length, sequence_length)` です。注意機構の softmax 後の重みであり、自己注意、クロス注意、マルチスケール変形注意ヘッドにおける加重平均の計算に使用されます。
- **encoder_hidden_states** (`tuple[torch.FloatTensor]`、*optional*) -- `torch.FloatTensor` のタプル（埋め込みの出力用 1 つと、各層の出力用 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。各層の出力におけるモデルの隠れ状態と、初期埋め込みの出力です。
- **encoder_attentions** (`tuple[tuple[torch.FloatTensor]]`, *optional*) -- `torch.FloatTensor` のタプルのタプル（各レイヤーの注意機構に対応する1つずつ）で、形状は `(batch_size, num_heads, sequence_length, sequence_length)` です。注意機構の softmax 後のアテンション重みで、自己注意、クロス注意、マルチスケール変形注意ヘッドにおける加重平均の計算に使用されます。
- **classes_structure** (`torch.LongTensor`, *optional*) -- 各画像についてクエリされるクラスの数。

例:

```python
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from PIL import Image

>>> from transformers import AutoProcessor, OmDetTurboForObjectDetection

>>> processor = AutoProcessor.from_pretrained("omlab/omdet-turbo-swin-tiny-hf")
>>> model = OmDetTurboForObjectDetection.from_pretrained("omlab/omdet-turbo-swin-tiny-hf")

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))
>>> classes = ["cat", "remote"]
>>> task = "Detect {}.".format(", ".join(classes))
>>> inputs = processor(image, text=classes, task=task, return_tensors="pt")

>>> outputs = model(**inputs)

>>> # convert outputs (bounding boxes and class logits)
>>> results = processor.post_process_grounded_object_detection(
...     outputs,
...     classes=classes,
...     target_sizes=[image.size[::-1]],
...     score_threshold=0.3,
...     nms_threshold=0.3,
>>> )[0]
>>> for score, class_name, box in zip(results["scores"], results["classes"], results["boxes"]):
...     box = [round(i, 1) for i in box.tolist()]
...     print(
...         f"Detected {class_name} with confidence "
...         f"{round(score.item(), 2)} at location {box}"
...     )
Detected remote with confidence 0.76 at location [39.9, 71.3, 176.5, 117.9]
Detected cat with confidence 0.72 at location [345.1, 22.5, 639.7, 371.9]
Detected cat with confidence 0.65 at location [12.7, 53.8, 315.5, 475.3]
Detected remote with confidence 0.57 at location [333.4, 75.6, 370.7, 187.0]
```

