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.2).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

이 모델은 2024-01-04에 HF papers에 게시되었으며, 2025-08-01에 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}")

The input is a single word "Notes". 참고

MMGroundingDinoConfig

class 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], 선택) — backbone 모델의 설정입니다.
  • text_config (Union[dict, ~configuration_utils.PreTrainedConfig], 선택) — 텍스트 백본의 config 객체 또는 사전입니다.
  • num_queries (int, 선택 사항, 기본값 900) — 객체 쿼리의 수, 즉 감지 슬롯의 수입니다. 이는 MMGroundingDinoModel이 단일 이미지에서 감지할 수 있는 최대 객체 수입니다.
  • encoder_layers (int, 선택 사항, 기본값 6) — Transformer 인코더의 숨겨진 레이어 수입니다. 설정하지 않으면 num_layers와 동일한 값을 사용합니다.
  • encoder_ffn_dim (int, 선택 사항, 기본값 2048) — 인코더의 “중간” 레이어(일반적으로 feed-forward 레이어라고도 함)의 차원입니다.
  • encoder_attention_heads (int, 선택 사항, 기본값 8) — Transformer 인코더의 각 어텐션 레이어에 사용할 어텐션 헤드 수입니다.
  • decoder_layers (int, 선택 사항, 기본값 6) — Transformer decoder의 hidden layer 수입니다. 설정하지 않으면 num_layers와 동일한 값을 사용합니다.
  • decoder_ffn_dim (int, 선택 사항, 기본값 2048) — decoder의 “intermediate”(일반적으로 feed-forward라고도 함) 레이어의 차원입니다.
  • decoder_attention_heads (int, 선택 사항, 기본값 8) — Transformer decoder의 각 attention layer에 사용할 attention head 수입니다.
  • 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) — Attention 확률에 적용할 dropout 비율입니다.
  • 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) — Grounding DINO의 변형으로 영역 제안(region proposals)을 생성한 후, 이를 디코더에 입력하여 바운딩 박스를 반복적으로 정제하는 2단계 deformable DETR을 적용할지 여부입니다.
  • class_cost (float, 선택 사항, 기본값 1.0) — 헝가리안 매칭 비용에서 분류 오류의 상대적 가중치입니다.
  • bbox_cost (float, 선택 사항, 기본값 5.0) — 헝가리안 매칭 비용에서 L1 바운딩 박스 오차의 상대적 가중치입니다.
  • giou_cost (float, 선택 사항, 기본값 2.0) — 헝가리안 매칭 비용에서 일반화 IoU 손상의 상대적 가중치.
  • bbox_loss_coefficient (float, 선택 사항, 기본값 5.0) — panoptic segmentation loss에서 L1 bounding box loss의 상대적 가중치입니다.
  • giou_loss_coefficient (float, 선택 사항, 기본값 2.0) — panoptic segmentation loss에서 generalized IoU loss의 상대적 가중치입니다.
  • focal_alpha (float, 선택 사항, 기본값 0.25) — focal loss의 Alpha 매개변수입니다.
  • disable_custom_kernels (bool, 선택 사항, 기본값 False) — 커스텀 CUDA 및 CPU 커널 사용을 비활성화합니다. PyTorch ONNX export에서 커스텀 커널이 지원되지 않으므로 ONNX export를 위해 이 옵션이 필요합니다.
  • max_text_len (int, 선택 사항, 기본값 256) — 텍스트 입력의 최대 길이입니다.
  • text_enhancer_dropout (float, 선택 사항, 기본값 0.0) — 텍스트 강화기(text enhancer)에 적용할 dropout 비율입니다.
  • 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의 temperature입니다.
  • decoder_bbox_embed_share (bool, 선택 사항, 기본값 True) — 모든 decoder 레이어에서 bbox 회귀 헤드를 공유할지 여부입니다.
  • decoder_cls_embed_share (bool, 선택 사항, 기본값 True) — 모든 decoder 레이어에서 클래스 임베딩 헤드를 공유할지 여부입니다.
  • 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의 설정과 유사한 설정이 생성됩니다.

Configuration 객체는 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

class 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.Tensor)

매개변수

  • pixel_values (torch.Tensor, 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 토큰에, 1은 sentence B 토큰에 해당합니다

    토큰 타입 ID란 무엇인가요?

  • attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요? [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

    어텐션 마스크란 무엇인가요?

  • pixel_mask (torch.Tensor 의 형태인 (batch_size, height, width), 선택 사항) — 패딩 픽셀 값에 대한 attention을 수행하지 않도록 하는 마스크. [0, 1] 범위에서 선택된 마스크 값: 실제 픽셀(즉, 마스크되지 않은 픽셀)은 1, 패딩 픽셀(즉, 마스크된 픽셀)은 0. attention 마스크란 무엇인가요? [0, 1]:
    • 실제 픽셀(즉, 마스크가 적용되지 않은 픽셀)에 대해 1
    • 패딩(즉, 마스크 처리된) 픽셀은 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) 인코더의 마지막 레이어 출력에서 생성된 hidden-states의 시퀀스입니다. 디코더의 cross-attention에 사용됩니다.
  • 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 (“) — 일반 tuple 대신 ModelOutput를 반환할지 여부.

반환값

MMGroundingDinoModelOutput 또는 tuple(torch.Tensor)

MMGroundingDinoModelOutput 또는 torch.Tensor의 튜플(return_dict=False가 전달되었거나 config.return_dict=False인 경우)로, 구성(MMGroundingDinoConfig)과 입력에 따라 다양한 요소를 포함합니다.

MMGroundingDinoModel의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.

이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신 Module 인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.

  • last_hidden_state (torch.Tensor, shape (batch_size, num_queries, hidden_size)) — 모델의 decoder 마지막 레이어 출력의 hidden-state 시퀀스입니다.

  • init_reference_points (torch.Tensor, shape (batch_size, num_queries, 4)) — Transformer decoder를 통해 전달되는 초기 reference points.

  • intermediate_hidden_states (torch.Tensor, shape (batch_size, config.decoder_layers, num_queries, hidden_size)) — 스택된 중간 hidden states(decoder의 각 레이어 출력).

  • intermediate_reference_points (torch.Tensor, shape (batch_size, config.decoder_layers, num_queries, 4)) — 스택된 중간 참조 포인트(decoder의 각 레이어의 참조 포인트).

  • decoder_hidden_states (tuple[torch.Tensor], 선택 사항, output_hidden_states=True가 전달되거나 config.output_hidden_states=True인 경우 반환됨) — torch.Tensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩의 출력에 대한 것 1개 + 각 레이어의 출력에 대한 것 1개)로, 모양은 (batch_size, sequence_length, hidden_size)입니다.

    각 레이어의 출력에서 디코더의 Hidden-states와 초기 임베딩 출력을 더한 값.

  • decoder_attentions (tuple[tuple[torch.Tensor]], 선택 사항, output_attentions=True가 전달되거나 config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된 torch.Tensor의 튜플로, 모양은 (batch_size, num_heads, sequence_length, sequence_length)입니다.

    self-attention 헤드에서 가중 평균을 계산하는 데 사용되는, attention softmax 이후의 decoder의 attention 가중치입니다.

  • encoder_last_hidden_state_vision (torch.Tensor, shape (batch_size, sequence_length, hidden_size), 선택 사항) — 모델 인코더의 마지막 레이어 출력에서 생성된 hidden-state 시퀀스입니다.

  • encoder_last_hidden_state_text (torch.Tensor, shape (batch_size, sequence_length, hidden_size), 선택 사항) — 모델 인코더의 마지막 레이어 출력에서 생성된 hidden-state 시퀀스입니다.

  • encoder_vision_hidden_states (tuple(torch.Tensor), 선택 사항, output_hidden_states=True가 전달되었거나 config.output_hidden_states=True인 경우 반환됨) — torch.Tensor의 튜플(비전 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은 (batch_size, sequence_length, hidden_size)입니다. 각 레이어 출력 시점의 비전 인코더 히든 스테이트와 초기 임베딩 출력을 포함합니다.

  • encoder_text_hidden_states (tuple(torch.Tensor), 선택 사항, output_hidden_states=True가 전달되었거나 config.output_hidden_states=True인 경우 반환됨) — torch.Tensor의 튜플(텍스트 임베딩 출력용 1개 + 각 레이어 출력용 1개) 형상은 (batch_size, sequence_length, hidden_size)입니다. 각 레이어 출력에서의 텍스트 인코더 히든 스테이트와 초기 임베딩 출력을 포함합니다.

  • encoder_attentions (tuple(tuple(torch.Tensor)), 선택 사항, output_attentions=True가 전달되거나 config.output_attentions=True인 경우 반환됨) — 각 레이어의 어텐션에 대한 torch.Tensor의 튜플의 튜플로, 모양은 (batch_size, num_heads, sequence_length, sequence_length)입니다. 어텐션 softmax 이후의 어텐션 가중치로, 텍스트-비전 어텐션, 비전-텍스트 어텐션, 텍스트-엔핸서(셀프-어텐션) 및 멀티스케일 변형형 어텐션 헤드에서 가중 평균을 계산하는 데 사용됩니다.

  • enc_outputs_class (torch.Tensor, shape (batch_size, sequence_length, config.num_labels), 선택 사항, config.two_stage=True일 때 반환됨) — 첫 번째 단계에서 점수가 가장 높은 config.num_queries개의 bounding box가 region proposals로 선택되는 예측 bounding box 점수입니다. bounding box 이진 분류(즉, foreground와 background)의 출력입니다.

  • enc_outputs_coord_logits (torch.Tensor, shape (batch_size, sequence_length, 4), 선택적, config.two_stage=True일 때 반환됨) — 1단계에서 예측된 바운딩 박스 좌표의 logits입니다.

  • encoder_logits (torch.Tensor, shape (batch_size, sequence_length, config.num_labels), 선택 사항, config.two_stage=True일 때 반환됨) — 1단계에서 상위 config.num_queries 점수를 가진 바운딩 박스의 logits입니다.

  • encoder_pred_boxes (torch.Tensor, shape (batch_size, sequence_length, 4), 선택 사항, config.two_stage=True일 때 반환됨) — 1단계에서 상위 config.num_queries 점수를 가진 바운딩 박스의 좌표입니다.

예:

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

class transformers.MMGroundingDinoForObjectDetection

< >

( config: MMGroundingDinoConfig )

매개변수

  • config (MMGroundingDinoConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 연관된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.

객체 감지 헤드가 위에 있는 Grounding DINO 모델(백본과 인코더-디코더 Transformer로 구성)로, COCO 감지와 같은 작업을 수행합니다.

이 모델은 PreTrainedModel에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대한 세부 사항은 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.

forward

< >

( pixel_values: Tensorinput_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.Tensor]]] | None = None**kwargs )

매개변수

  • pixel_values (torch.Tensor, 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 토큰에, 1은 sentence B 토큰에 해당합니다

    토큰 타입 ID란 무엇인가요?

  • attention_mask (torch.LongTensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요? [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

    어텐션 마스크란 무엇인가요?

  • pixel_mask (torch.BoolTensor 형상이 (batch_size, height, width), 선택 사항) — 패딩 픽셀 값에 대한 attention을 수행하지 않도록 하는 마스크. [0, 1] 범위에서 선택된 마스크 값: 실제 픽셀(즉, 마스크되지 않은 픽셀)은 1, 패딩 픽셀(즉, 마스크된 픽셀)은 0. attention 마스크란 무엇인가요? [0, 1]:
    • 실제 픽셀(즉, 마스크가 적용되지 않은 픽셀)에 대해 1
    • 패딩(즉, 마스크 처리된) 픽셀은 0

    어텐션 마스크란 무엇인가요?

  • encoder_outputs (Union[~models.mm_grounding_dino.modeling_mm_grounding_dino.MMGroundingDinoEncoderOutput, tuple], 선택 사항) — (last_hidden_state, 선택 사항: hidden_states, 선택 사항: attentions)으로 구성된 튜플 last_hidden_state의 shape은 (batch_size, sequence_length, hidden_size)이며, 선택 사항)은 인코더의 마지막 레이어 출력에서 생성된 hidden-states 시퀀스입니다. 디코더의 cross-attention에 사용됩니다.
  • output_attentions (bool, 선택 사항) — 모든 attention 레이어의 attentions 텐서를 반환할지 여부. 자세한 내용은 반환 텐서 섹션의 attentions 항목을 참조하세요.
  • output_hidden_states (bool, 선택 사항) — 모든 레이어의 hidden states를 반환할지 여부입니다. 자세한 내용은 반환되는 텐서 중 hidden_states 항목을 참고하세요.
  • return_dict (bool, 선택) — 일반 튜플 대신 ModelOutput를 반환할지 여부.
  • labels (list[Dict], 길이 (batch_size,), 선택 사항) — 이분 매칭 손실을 계산하기 위한 라벨. 각 딕셔너리는 최소한 ‘class_labels’와 ‘boxes’라는 두 개의 키를 포함해야 합니다(각각 배치 내 이미지의 클래스 라벨과 바운딩 박스). 클래스 라벨 자체는 torch.LongTensor이며 길이는 (number of bounding boxes in the image,)이고, boxes는 torch.Tensor이며 모양은 (number of bounding boxes in the image, 4)입니다.

MMGroundingDinoForObjectDetection의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.

이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신 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