Transformers documentation

MM Grounding DINO

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

このモデルは2024年1月4日にHF papersで公開され、2025年8月1日にHugging Face Transformersに貢献されました。

MM Grounding DINO

MM Grounding DINOモデルは、Xiangyu Zhao、Yicheng Chen、Shilin Xu、Xiangtai Li、Xinjiang Wang、Yining Li、Haian Huang による An Open and Comprehensive Pipeline for Unified Object Grounding and Detection で提案されました。

MM Grounding DINO は、対比クラスヘッドの改善とデコーダーにおけるパラメータ共有の除去により、Grounding DINO を改善しています。これにより、COCO(50.6(+2.2) AP)および LVIS(31.9(+11.8) val AP および 41.4(+12.6) minival AP)の両方で、ゼロショット検出の性能が向上しました。

MM Grounding DINOコレクションに、MM Grounding DINOのすべてのオリジナルチェックポイントが格納されています。このモデルはLLMDet推論にも対応しています。LLMDetのチェックポイントはLLMDetコレクションで確認できます。

MM Grounding DINO モデルの右サイドバーをクリックすると、MM Grounding DINO をさまざまな MM Grounding DINO タスクに適用する方法の例をさらに確認できます。

以下の例では、AutoModelForZeroShotObjectDetection クラスを使用して画像に基づいてテキストを生成する方法を示しています。

AutoModel
import torch

from transformers import AutoModelForZeroShotObjectDetection, AutoProcessor
from transformers.image_utils import load_image


# Prepare processor and model
model_id = "openmmlab-community/mm_grounding_dino_tiny_o365v1_goldg_v3det"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForZeroShotObjectDetection.from_pretrained(model_id, device_map="auto")

# Prepare inputs
image_url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = load_image(image_url)
text_labels = [["a cat", "a remote control"]]
inputs = processor(images=image, text=text_labels, return_tensors="pt").to(model.device)

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

# Postprocess outputs
results = processor.post_process_grounded_object_detection(
    outputs,
    threshold=0.4,
    target_sizes=[(image.height, image.width)]
)

# Retrieve the first image result
result = results[0]
for box, score, labels in zip(result["boxes"], result["scores"], result["labels"]):
    box = [round(x, 2) for x in box.tolist()]
    print(f"Detected {labels} with confidence {round(score.item(), 3)} at location {box}")

注記

MMGroundingDinoConfig

クラス transformers.MMGroundingDinoConfig

< >

( 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 = Truebackbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonenum_queries: int = 900encoder_layers: int = 6encoder_ffn_dim: int = 2048encoder_attention_heads: int = 8decoder_layers: int = 6decoder_ffn_dim: int = 2048decoder_attention_heads: int = 8activation_function: str = 'relu'd_model: int = 256dropout: float | int = 0.1attention_dropout: float | int = 0.0activation_dropout: float | int = 0.0auxiliary_loss: bool = Falseposition_embedding_type: str = 'sine'num_feature_levels: int = 4encoder_n_points: int = 4decoder_n_points: int = 4two_stage: bool = Trueclass_cost: float = 1.0bbox_cost: float = 5.0giou_cost: float = 2.0bbox_loss_coefficient: float = 5.0giou_loss_coefficient: float = 2.0focal_alpha: float = 0.25disable_custom_kernels: bool = Falsemax_text_len: int = 256text_enhancer_dropout: float | int = 0.0fusion_droppath: float | int = 0.1fusion_dropout: float | int = 0.0embedding_init_target: bool = Truequery_dim: int = 4positional_embedding_temperature: int = 20decoder_bbox_embed_share: bool = Truedecoder_cls_embed_share: bool = Trueinit_std: float = 0.02layer_norm_eps: float = 1e-05tie_word_embeddings: bool = True )

パラメータ

  • is_encoder_decoder (bool、任意、デフォルトはTrue) — モデルがエンコーダー/デコーダーとして使用されるかどうかを示します。
  • backbone_config (Union[dict, ~configuration_utils.PreTrainedConfig], 任意) — バックボーンモデルの設定です。
  • text_config (Union[dict, ~configuration_utils.PreTrainedConfig]、省略可) — テキストバックボーンの設定オブジェクトまたは辞書。
  • num_queries (int、任意、デフォルトは 900) — オブジェクトクエリ数、すなわち検出スロットの数です。これは、MMGroundingDinoModel が 1 枚の画像内で検出できるオブジェクトの最大数を示します。
  • encoder_layers (int、任意、デフォルトは 6) — Transformer エンコーダーの隠れ層の数です。設定されていない場合は、num_layers と同じ値が使用されます。
  • encoder_ffn_dim (int、任意、デフォルトは 2048) — エンコーダー内の「中間」層(フィードフォワード層と呼ばれることが多い)の次元数。
  • encoder_attention_heads (int、任意、デフォルトは 8) — Transformer エンコーダーの各アテンション層におけるアテンションヘッドの数。
  • decoder_layers (int、任意、デフォルトは 6) — Transformer デコーダーの隠れ層の数です。設定されていない場合、num_layers と同じ値が使用されます。
  • decoder_ffn_dim (int、任意、デフォルトは 2048) — デコーダー内の「中間」(feed-forward と呼ばれることが多い) レイヤーの次元数。
  • decoder_attention_heads (int、任意、デフォルトは8) — Transformerデコーダーの各アテンション層におけるアテンションヘッドの数。
  • activation_function (str、任意、デフォルトは relu) — デコーダーで使用する非線形活性化関数(関数または文字列)。例えば、"gelu"、"relu"、"silu" など。
  • d_model (int、省略可、デフォルトは 256) — エンコーダ層とプーラ層のサイズ。
  • dropout (Union[float, int]、任意、デフォルト値は0.1) — すべての dropout レイヤーの比率です。
  • attention_dropout (Union[float, int]、任意、デフォルトは 0.0) — アテンション確率のドロップアウト率です。
  • activation_dropout (Union[float, int]、任意、デフォルトは 0.0) — 全結合層内の活性化に対する dropout 率です。
  • auxiliary_loss (bool、任意、デフォルトはFalse) — 補助デコーディング損失(各デコーダ層での損失)を使用するかどうかを指定します。
  • position_embedding_type (str, 任意、デフォルトは "sine") — 画像特徴の上に適用する位置埋め込みの種類。"sine" または "learned" のいずれかです。
  • num_feature_levels (int、任意、デフォルトは 4) — 入力特徴量のレベル数です。
  • encoder_n_points (int、省略可能、デフォルト値は 4)— エンコーダーの各アテンションヘッドにおいて、各特徴レベルでサンプリングされるキーの数を指定します。
  • decoder_n_points (int、省略可能、デフォルトは 4) — デコーダーの各アテンションヘッドにおいて、各特徴量レベルでサンプリングされるキーの数を指定します。
  • two_stage (bool、省略可、デフォルトは True) — 2段階のデフォーマブル DETR を適用するかどうか。この場合、Grounding DINO のバリアントによってリージョン提案も生成され、それらがデコーダーに渡されてバウンディングボックスの反復的な精緻化が行われます。
  • class_cost (float、任意、デフォルトは 1.0) — ハンガリー法によるマッチングコストにおける、分類誤差の相対的な重み。
  • bbox_cost (float、任意、デフォルトは 5.0) — ハンガリー法によるマッチングコストにおける、L1バウンディングボックス誤差の相対的な重み。
  • giou_cost (float、任意、デフォルトは 2.0) — ハンガリー法によるマッチングコストにおける、汎化 IoU ロスの相対的な重み。
  • bbox_loss_coefficient (float、任意、デフォルトは 5.0) — パノプティックセグメンテーション損失における L1 バウンディングボックス損失の相対的な重み。
  • giou_loss_coefficient (float、任意、デフォルトは 2.0) — パンノミックセグメンテーション損失における汎化 IoU 損失の相対的な重み。
  • focal_alpha (float、任意、デフォルトは 0.25) — focal loss の Alpha パラメータ。
  • disable_custom_kernels (bool、任意、デフォルトはFalse) — カスタム CUDA カーネルおよび CPU カーネルの使用を無効にします。このオプションは ONNX エクスポートに必要であり、カスタムカーネルは PyTorch の ONNX エクスポートではサポートされていないためです。
  • max_text_len (int、任意、デフォルトは 256) — テキスト入力の最大長です。
  • text_enhancer_dropout (float、任意、デフォルト値は 0.0) — テキストエンハンサーのドロップアウト率です。
  • fusion_droppath (float、任意、デフォルトは 0.1) — fusion モジュールの droppath 比率です。
  • fusion_dropout (float、任意、デフォルト値は 0.0) — fusion モジュールの dropout 率です。
  • embedding_init_target (bool、省略可、デフォルトは True) — Embedding の重みでターゲットを初期化するかを指定します。
  • query_dim (int、任意、デフォルトは 4) — クエリベクトルの次元数です。
  • positional_embedding_temperature (float、任意、デフォルト値は 20) — ビジョンバックボーンと併せて使用される Sine Positional Embedding の温度です。
  • decoder_bbox_embed_share (bool、任意、デフォルトは True) — すべてのデコーダー層で bbox 回帰ヘッドを共有するかどうか。
  • decoder_cls_embed_share (bool、任意、デフォルトは True) — すべてのデコーダー層でクラス埋め込みヘッドを共有するかどうかを指定します。
  • init_std (float、任意、デフォルトは 0.02) — すべての重み行列を初期化するための truncated_normal_initializer の標準偏差です。
  • layer_norm_eps (float、任意、デフォルトは 1e-05) — レイヤーノーマル層で使用する epsilon です。
  • tie_word_embeddings (bool、任意、デフォルトは True) — モデルの tied_weights_keys マッピングに従って重み埋め込みを共有するかどうかを指定します。

これは、Mm Grounding Dinoモデルの構成を保存するための設定クラスです。指定された引数に基づいて Mm Grounding Dino モデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、openmmlab-community/mm_grounding_dino_tiny_o365v1_goldg_v3det と同様の設定が得られます。

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

例:

>>> from transformers import MMGroundingDinoConfig, MMGroundingDinoModel

>>> # Initializing a MM Grounding DINO configuration
>>> configuration = MMGroundingDinoConfig()

>>> # Initializing a model (with random weights) from the configuration
>>> model = MMGroundingDinoModel(configuration)

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

MMGroundingDinoModel

クラス transformers.MMGroundingDinoModel

< >

( config: MMGroundingDinoConfig )

パラメータ

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

Grounding DINOのベースモデル(バックボーンとエンコーダー・デコーダーのTransformerで構成)は、特定のヘッドを備えずに生のhidden-statesを出力します。

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

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

forward

< >

( pixel_values: Tensorinput_ids: Tensortoken_type_ids: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonepixel_mask: typing.Optional[torch.Tensor] = Noneencoder_outputs = Noneoutput_attentions = Noneoutput_hidden_states = Nonereturn_dict = None**kwargs ) → MMGroundingDinoModelOutput or tuple(torch.FloatTensor)

パラメータ

  • pixel_values (torch.Tensor、形状 (batch_size, num_channels, image_size, image_size)) — 入力画像に対応するテンソルです。ピクセル値は GroundingDinoImageProcessor を使用して取得できます。詳細については GroundingDinoImageProcessor.call() を参照してください(GroundingDinoProcessor は画像の処理に GroundingDinoImageProcessor を使用します)。
  • input_ids (torch.LongTensor の形状 (batch_size, text_sequence_length)) — 語彙における入力シーケンスのトークンインデックスです。パディングが提供された場合、デフォルトでは無視されます。

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

  • token_type_ids (torch.LongTensor の形状 (batch_size, text_sequence_length), 、任意) — 入力テキストの前半と後半を示すためのセグメントトークンインデックス。インデックスは [0, 1]: 0 に対応します。 sentence A トークンに対応します。 sentence B トークンに対応します。

    トークンタイプIDとは?

  • attention_mask (torch.Tensor の形状 (batch_size, sequence_length), 、任意) — パディングトークンのインデックスに対するアテンションを回避するためのマスク。 [0, 1]:
    • マスクされていないトークンに対して1
    • マスクされたトークンに対しては 0 です。

    アテンションマスクとは?

  • pixel_mask (torch.Tensor の形状 (batch_size, height, width), 、任意) — パディングピクセル値に対するアテンションの適用を回避するためのマスク。 [0, 1]:
    • 実在するピクセル(つまり、マスクされていない)に対して1
    • padding(つまり、マスクされている)ピクセルは0です。

    アテンションマスクとは?

  • encoder_outputs (`) -- Tuple consists of (last_hidden_state, *optional*: hidden_states, *optional*: attentions) last_hidden_stateof shape(batch_size, sequence_length, hidden_size)`, optional) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
  • output_attentions (`) -- Whether or not to return the attentions tensors of all attention layers. See attentions` under returned tensors for more detail.
  • output_hidden_states (`) -- Whether or not to return the hidden states of all layers. See hidden_states` under returned tensors for more detail.
  • return_dict (“) — プレーンなタプルではなく ModelOutput を返すかどうか。

戻り値

MMGroundingDinoModelOutput または tuple(torch.FloatTensor)

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

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

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

  • last_hidden_state (torch.FloatTensor、shape (batch_size, num_queries, hidden_size)) — モデルのデコーダーの最終層の出力における、隠れ状態のシーケンス。

  • init_reference_points (torch.FloatTensor、shape (batch_size, num_queries, 4)) — Transformer デコーダーに渡される初期の参照点。

  • intermediate_hidden_states (torch.FloatTensor、shape (batch_size, config.decoder_layers, num_queries, hidden_size)) — 中間隠れ状態のスタック(デコーダーの各層の出力)。

  • intermediate_reference_points (torch.FloatTensor、shape (batch_size, config.decoder_layers, num_queries, 4)) — 積み重ねられた中間参照点(デコーダーの各層の参照点)。

  • decoder_hidden_states (tuple[torch.FloatTensor]、optional、output_hidden_states=True が渡された場合または config.output_hidden_states=True の場合に返されます)— torch.FloatTensor のタプル(埋め込み層を持つモデルの場合、埋め込みの出力が 1 つ、各層の出力がそれぞれ 1 つずつ)で、形状は (batch_size, sequence_length, hidden_size) です。

    各層の出力および初期埋め込み出力における、デコーダーの隠れ状態。

  • decoder_attentions (tuple[tuple[torch.FloatTensor]]、任意、output_attentions=True が渡された場合または config.output_attentions=True の場合に返されます) — torch.FloatTensor のタプル(各レイヤーごとに1つ)、形状は (batch_size, num_heads, sequence_length, sequence_length)。

    自己アテンションヘッドにおける加重平均を計算するために使用される、アテンションのsoftmax後のデコーダーのアテンション重み。

  • encoder_last_hidden_state_vision(torch.FloatTensor、形状 (batch_size, sequence_length, hidden_size)、任意)— モデルのエンコーダーの最終層の出力における隠れ状態のシーケンス。

  • encoder_last_hidden_state_text (torch.FloatTensor、shape (batch_size, sequence_length, hidden_size)、optional) — モデルのエンコーダーの最終層の出力における、隠れ状態のシーケンス。

  • encoder_vision_hidden_states (tuple(torch.FloatTensor)、optional、output_hidden_states=True が渡された場合または config.output_hidden_states=True の場合に返されます) — torch.FloatTensor のタプル(ビジョン埋め込みの出力用 1 つ + 各レイヤーの出力用 1 つ)で、形状は (batch_size, sequence_length, hidden_size) です。各レイヤーの出力におけるビジョンエンコーダーの隠れ状態と、初期埋め込みの出力です。

  • encoder_text_hidden_states (tuple(torch.FloatTensor)、任意、output_hidden_states=True が渡された場合または config.output_hidden_states=True の場合に返されます)— torch.FloatTensor のタプル(テキスト埋め込みの出力用 1 つ + 各層の出力用 1 つ) 形状は (batch_size, sequence_length, hidden_size) です。テキストエンコーダーの各層の出力における隠れ状態と、初期埋め込みの出力です。

  • encoder_attentions (tuple(tuple(torch.FloatTensor))、optional、output_attentions=True が渡された場合または config.output_attentions=True の場合に返されます)— torch.FloatTensor のタプルのタプル(各レイヤーの注意機構用)で、形状は (batch_size, num_heads, sequence_length, sequence_length) です。注意機構の softmax 後のアテンション重みで、テキスト-ビジョンアテンション、ビジョン-テキストアテンション、テキストエンハンサー(自己アテンション)、マルチスケール変形アテンションヘッドにおける加重平均の計算に使用されます。注意機構の softmax 後のアテンション重みで、バイアテンションヘッドにおける加重平均の計算に使用されます。

  • enc_outputs_class (torch.FloatTensor、shape (batch_size, sequence_length, config.num_labels)、optional、config.two_stage=True の場合に返される) — 1 段階目でスコアが上位の config.num_queries 個の bounding box が region proposals として選択される、予測された bounding box のスコアです。bounding box の二値分類(すなわち foreground と background)の出力です。

  • enc_outputs_coord_logits (torch.FloatTensor、shape (batch_size, sequence_length, 4)、optional、config.two_stage=True の場合に返される) — 第1段階で予測されるバウンディングボックス座標の logits。

  • encoder_logits (torch.FloatTensor、shape (batch_size, sequence_length, config.num_labels)、optional、config.two_stage=True の場合に返される) — 第1段階でスコアリングされた上位 config.num_queries 個のバウンディングボックスの logits。

  • encoder_pred_boxes(torch.FloatTensor、shape (batch_size, sequence_length, 4)、optional、config.two_stage=True の場合に返される) — 第1段階でスコアが上位の config.num_queries 個の bounding box の座標。

例:

>>> from transformers import AutoProcessor, AutoModel
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))
>>> text = "a cat."

>>> processor = AutoProcessor.from_pretrained("IDEA-Research/grounding-dino-tiny")
>>> model = AutoModel.from_pretrained("IDEA-Research/grounding-dino-tiny")

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

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

MMGroundingDinoForObjectDetection

クラス transformers.MMGroundingDinoForObjectDetection

< >

( config: MMGroundingDinoConfig )

パラメータ

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

オブジェクト検出ヘッドを備えた Grounding DINO モデル(バックボーンとエンコーダー・デコーダー型 Transformer で構成)は、COCO 検出などのタスクに使用されます。

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

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

forward

< >

( pixel_values: FloatTensorinput_ids: LongTensortoken_type_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.LongTensor] = Nonepixel_mask: typing.Optional[torch.BoolTensor] = Noneencoder_outputs: transformers.models.mm_grounding_dino.modeling_mm_grounding_dino.MMGroundingDinoEncoderOutput | tuple | None = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = Nonelabels: list[dict[str, typing.Union[torch.LongTensor, torch.FloatTensor]]] | None = None**kwargs )

パラメータ

  • pixel_values (torch.FloatTensor、shape (batch_size, num_channels, image_size, image_size)) — 入力画像に対応するテンソルです。ピクセル値はGroundingDinoImageProcessorを使用して取得できます。詳細はGroundingDinoImageProcessor.call()を参照してください(GroundingDinoProcessorは画像の処理にGroundingDinoImageProcessorを使用します)。
  • input_ids (torch.LongTensor の形状 (batch_size, text_sequence_length)) — 語彙における入力シーケンスのトークンインデックスです。パディングが提供された場合、デフォルトでは無視されます。

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

  • token_type_ids (torch.LongTensor の形状 (batch_size, text_sequence_length), 、任意) — 入力テキストの前半と後半を示すためのセグメントトークンインデックス。インデックスは [0, 1]: 0 に対応します。 sentence A トークンに対応します。 sentence B トークンに対応します。

    トークンタイプIDとは?

  • attention_mask (torch.LongTensor の形状 (batch_size, sequence_length), 、任意) — パディングトークンのインデックスに対するアテンションを回避するためのマスク。 [0, 1]:
    • マスクされていないトークンに対して1
    • マスクされたトークンに対しては 0 です。

    アテンションマスクとは?

  • pixel_mask (torch.BoolTensor 形状 (batch_size, height, width), 、任意) — パディングピクセル値へのアテンションを回避するためのマスク。 [0, 1]:
    • 実在するピクセル(つまり、マスクされていない)に対して1
    • padding(つまり、マスクされている)ピクセルは0です。

    アテンションマスクとは?

  • encoder_outputs (Union[~models.mm_grounding_dino.modeling_mm_grounding_dino.MMGroundingDinoEncoderOutput, tuple], 任意) — last_hidden_state、任意: hidden_states、任意: attentions のタプルです。 last_hidden_state は形状 (batch_size, sequence_length, hidden_size)、任意)であり、エンコーダーの最終層の出力における隠れ状態のシーケンスです。デコーダーのクロスアテンションで使用されます。
  • output_attentions (bool, 省略可) — すべてのアテンション層のアテンションテンソルを返すかどうかを指定します。詳細は、返されるテンソルの attentions を参照してください。
  • output_hidden_states (bool, 省略可) — すべての層の hidden states を返すかどうかを指定します。詳細は、返されるテンソルの hidden_states を参照してください。
  • return_dict (bool, 任意) — プレーンなタプルではなく ModelOutput を返すかどうか。
  • 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 である必要があります。

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

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

例:

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

>>> import torch
>>> from PIL import Image
>>> from transformers import AutoProcessor, AutoModelForZeroShotObjectDetection

>>> model_id = "IDEA-Research/grounding-dino-tiny"
>>> device = "cuda"

>>> processor = AutoProcessor.from_pretrained(model_id)
>>> model = AutoModelForZeroShotObjectDetection.from_pretrained(model_id).to(device)

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))
>>> # Check for cats and remote controls
>>> text_labels = [["a cat", "a remote control"]]

>>> inputs = processor(images=image, text=text_labels, return_tensors="pt").to(device)
>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> results = processor.post_process_grounded_object_detection(
...     outputs,
...     threshold=0.4,
...     text_threshold=0.3,
...     target_sizes=[(image.height, image.width)]
... )
>>> # Retrieve the first image result
>>> result = results[0]
>>> for box, score, text_label in zip(result["boxes"], result["scores"], result["text_labels"]):
...     box = [round(x, 2) for x in box.tolist()]
...     print(f"Detected {text_label} with confidence {round(score.item(), 3)} at location {box}")
Detected a cat with confidence 0.479 at location [344.7, 23.11, 637.18, 374.28]
Detected a cat with confidence 0.438 at location [12.27, 51.91, 316.86, 472.44]
Detected a remote control with confidence 0.478 at location [38.57, 70.0, 176.78, 118.18]
Update on GitHub