Transformers documentation

OmDet-Turbo

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

このモデルは2024年3月11日にHF papersで公開され、2024年9月25日にHugging Face Transformersに貢献されました。

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 で提案されました。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の産業応用における実用性は、ベンチマークデータセットでの卓越した性能と優れた推論速度によって裏付けられており、リアルタイム物体検出タスクにおいて魅力的な選択肢として位置づけられています。

drawing OmDet-Turbo architecture overview. Taken from the original paper.

このモデルは yonigozlan によって提供されました。 元のコードは こちら で確認できます。

使用のコツ

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

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

使用例

単一画像の推論

単一の画像でゼロショットオブジェクト検出を実行するために、モデルを読み込み、入力を準備する方法は以下の通りです。

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

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

class transformers.OmDetTurboConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0id2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Noneis_encoder_decoder: bool = Truetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonebackbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneapply_layernorm_after_vision_backbone: bool = Trueimage_size: int | list[int] | tuple[int, int] = 640disable_custom_kernels: bool = Falselayer_norm_eps: float = 1e-05batch_norm_eps: float = 1e-05init_std: float = 0.02text_projection_in_dim: int = 512text_projection_out_dim: int = 512task_encoder_hidden_dim: int = 1024class_embed_dim: int = 512class_distance_type: typing.Literal['cosine', 'dot'] = 'cosine'num_queries: int = 900csp_activation: str = 'silu'conv_norm_activation: str = 'gelu'encoder_feedforward_activation: str = 'relu'encoder_feedforward_dropout: float | int = 0.0encoder_dropout: float | int = 0.0hidden_expansion: int = 1encoder_hidden_dim: int = 256vision_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 = 8encoder_dim_feedforward: int = 2048encoder_layers: int = 1positional_encoding_temperature: int = 10000num_feature_levels: int = 3decoder_hidden_dim: int = 256decoder_num_heads: int = 8decoder_num_layers: int = 6decoder_activation: str = 'relu'decoder_dim_feedforward: int = 2048decoder_num_points: int = 4decoder_dropout: float | int = 0.0eval_size: int | None = Nonelearn_initial_query: bool = Falsecache_size: int = 100 )

パラメータ

  • is_encoder_decoder (bool、任意、デフォルトはTrue) — モデルがエンコーダー/デコーダーとして使用されるかどうかを示します。
  • text_config (Union[dict, ~configuration_utils.PreTrainedConfig]、省略可) — テキストバックボーンの設定オブジェクトまたは辞書。
  • backbone_config (Union[dict, ~configuration_utils.PreTrainedConfig], 任意) — バックボーンモデルの設定です。
  • 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) — レイヤーノーマル層で使用する epsilon です。
  • batch_norm_eps (float、任意、デフォルトは 1e-05) — バッチ正規化レイヤーで使用する epsilon です。
  • init_std (float、任意、デフォルトは 0.02) — すべての重み行列を初期化するための truncated_normal_initializer の標準偏差です。
  • 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 (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、任意、デフォルト値は 0.0) — エンコーダーのフィードフォワードネットワークの活性化関数の後に適用される dropout レートです。
  • encoder_dropout (Union[float, int]、任意、デフォルトは 0.0) — すべての dropout レイヤーの比率です。
  • hidden_expansion (int、任意、デフォルト値は 1) — エンコーダー内の CSP ネットワークの隠れ層の拡張係数です。
  • encoder_hidden_dim (int、任意、デフォルトは256) — 隠れ表現の次元数。
  • vision_features_channels (tuple(int)、任意、デフォルトは [256, 256, 256]) — デコーダーの入力として使用される、射影されたビジョン特徴のチャネル数。
  • encoder_in_channels (List(int)、任意、デフォルトは [192, 384, 768]) — エンコーダーの入力チャネル数です。
  • encoder_projection_indices (List(int)、任意、デフォルトは [2]) — 各レイヤーによって射影される入力特徴量のインデックスです。
  • encoder_attention_heads (int、任意、デフォルトは 8) — Transformer エンコーダーの各アテンション層におけるアテンションヘッドの数。
  • encoder_dim_feedforward (int、任意、デフォルトは 2048) — エンコーダーのフィードフォワード次元です。
  • encoder_layers (int、任意、デフォルトは 1) — Transformer エンコーダーの隠れ層の数です。設定されていない場合は、num_layers と同じ値が使用されます。
  • positional_encoding_temperature (int、任意、デフォルト値は 10000) — エンコーダーにおける位置エンコーディングの温度です。
  • num_feature_levels (int, 任意、デフォルトは 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、任意、デフォルトは 2048) — デコーダーのフィードフォワード次元です。
  • decoder_num_points (int、省略可、デフォルトは 4) — デコーダーのマルチスケール変形アテンションモジュールでサンプリングされる点の数を指定します。
  • decoder_dropout (float、任意、デフォルトは 0.0) — デコーダーの dropout レートです。
  • eval_size (tuple[int, int]、省略可) — stride を考慮した後に、position embeddings の実効的な高さおよび幅を計算するために使用される高さと幅です(RTDetr を参照)。
  • learn_initial_query (bool、省略可、デフォルトはFalse) — 初期クエリを学習するかどうかを指定します。
  • cache_size (int、任意、デフォルトは 100)— クラスおよびプロンプトのキャッシュのサイズです。

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

設定オブジェクトはPreTrainedConfigを継承し、モデルの出力を制御するために使用できます。詳細については、PreTrainedConfigのドキュメントを参照してください。

例:

>>> 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

class transformers.OmDetTurboProcessor

< >

( image_processortokenizer )

パラメータ

  • image_processor (DetrImageProcessor) — 画像プロセッサは必須の入力です。
  • tokenizer (CLIPTokenizer) — トークナイザーは必須の入力です。

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

OmDetTurboProcessor は、DetrImageProcessor と CLIPTokenizer のすべての機能を提供します。詳細については、~DetrImageProcessor および ~CLIPTokenizer を参照してください。

__call__

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Nonetext: list[str] | list[list[str]] | None = Nonetask: str | list[str] | None = None**kwargs: *<class 'transformers.processing_utils.ProcessingKwargs'> ) → ~feature_extraction_utils.BatchFeature

パラメータ

  • 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、list[str]、TextInput、または PreTokenizedInput、任意) — エンコードする検出タスクの説明です。指定されない場合、text 入力からデフォルトのタスク説明が生成されます(例: “Detect {text}.”)。単一の文字列、文字列のリスト(画像ごとに1つ)、または事前トークン化済み入力として指定できます。タスク説明は、モデルが画像内でどのようなオブジェクトを検出すべきかを導く役割を果たします。
  • return_mm_token_type_ids (bool, kwargs) — マルチモーダルプレースホルダトークンの位置を示すマルチモーダルトークンタイプIDを返すかどうか。
  • return_text_replacement_offsets (bool, kwargs) — 各マルチモーダルプレースホルダーとその置換文字列の文字オフセットを返すかどうかを指定します。
  • return_tensors (str または TensorType, 省略可) — 設定すると、特定のフレームワークのテンソルを返します。使用可能な値は以下の通りです:
    • 'pt': PyTorchのtorch.Tensorオブジェクトを返します。
    • 'np': NumPyのnp.ndarrayオブジェクトを返します。
  • **kwargs (ProcessingKwargs、任意) — 各モダリティ(テキスト、画像、動画、音声)の追加処理オプション。モデル固有のパラメータは上記にリストされています。サポートされている引数の完全なリストについては、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

< >

( outputs: OmDetTurboObjectDetectionOutputtext_labels: list[str] | list[list[str]] | None = Nonethreshold: float = 0.3nms_threshold: float = 0.5target_sizes: transformers.utils.generic.TensorType | list[tuple] | None = Nonemax_num_det: int | None = None ) → list[Dict]

パラメータ

  • outputs (OmDetTurboObjectDetectionOutput) — モデルの生出力です。
  • text_labels (Union[list[str], list[list[str]]], 省略可) — 入力クラスの名称です。指定しない場合、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の生出力を、(top_left_x, top_left_y, bottom_right_x, bottom_right_y)形式の最終的なバウンディングボックスに変換し、関連するテキストクラスを取得します。

OmDetTurboForObjectDetection

クラス transformers.OmDetTurboForObjectDetection

< >

( config: OmDetTurboConfig )

パラメータ

  • config (OmDetTurboConfig) — モデルのすべてのパラメータを含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連付けられた重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、from_pretrained() メソッドを参照してください。

OmDetTurbo Model(ビジョンバックボーンとテキストバックボーン、およびエンコーダー・デコーダーアーキテクチャで構成)は、COCO検出などのタスクに対して、バウンディングボックスとクラススコアを出力します。

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

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

forward

< >

( pixel_values: Tensorclasses_input_ids: LongTensorclasses_attention_mask: LongTensortasks_input_ids: LongTensortasks_attention_mask: LongTensorclasses_structure: LongTensorlabels: typing.Optional[torch.LongTensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → OmDetTurboObjectDetectionOutput or tuple(torch.Tensor)

パラメータ

  • pixel_values (torch.Tensor、形状 (batch_size, num_channels, image_size, image_size)) — 入力画像に対応するテンソルです。ピクセル値は DetrImageProcessor を使用して取得できます。詳細は DetrImageProcessor.call() を参照してください(OmDetTurboProcessor は画像の処理に DetrImageProcessor を使用しています)。
  • classes_input_ids (torch.LongTensor の形状 (total_classes (>= batch_size), sequence_length)) — 言語モデルの語彙における入力クラスシーケンスのトークンインデックス。 各タスクに対して複数のクラスを指定できるため、トークン化されたクラスはフラット化され、クラスの構造は classes_structure 引数で指定されます。

    インデックスはOmDetTurboProcessorを使用して取得できます。詳細はOmDetTurboProcessor.call()を参照してください。

    入力IDとは何ですか?

  • classes_attention_mask (torch.BoolTensor、shape (total_classes (>= batch_size), num_classes, sequence_length)) — クラス用のアテンションマスクです。これはバイナリマスクであり、どのトークンにアテンションを適用すべきか、適用すべきでないかを示します。
  • tasks_input_ids (torch.LongTensor の形状 (batch_size, sequence_length)) — 言語モデルの語彙における入力タスクシーケンスのトークンインデックス。

    インデックスはOmDetTurboProcessorを使用して取得できます。詳細はOmDetTurboProcessor.call()を参照してください。

    入力IDとは何ですか?

  • tasks_attention_mask (torch.BoolTensor、shape (batch_size, sequence_length)) — タスク用のアテンションマスクです。これは二値マスクであり、どのトークンにアテンションを適用すべきか、適用すべきでないかを示します。
  • classes_structure (torch.LongTensor、形状 (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.Tensor である必要があります。
  • output_attentions (bool, 省略可) — すべてのアテンション層のアテンションテンソルを返すかどうかを指定します。詳細は、返されるテンソルの attentions を参照してください。
  • output_hidden_states (bool, 省略可) — すべての層の hidden states を返すかどうかを指定します。詳細は、返されるテンソルの hidden_states を参照してください。
  • return_dict (bool, 任意) — プレーンなタプルではなく ModelOutput を返すかどうか。

戻り値

OmDetTurboObjectDetectionOutput または tuple(torch.Tensor)

OmDetTurboObjectDetectionOutput、またはtorch.Tensorのタプル(return_dict=Falseが渡された場合、またはconfig.return_dict=Falseの場合)。設定(OmDetTurboConfig)や入力に応じて、さまざまな要素で構成されます。

OmDetTurboForObjectDetectionのforwardメソッドは、__call__特殊メソッドをオーバーライドします。

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

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

例:

>>> 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]
Update on GitHub