Transformers documentation
OmDet-Turbo
이 모델은 2024-03-11에 HF papers에 게시되었으며, 2024-09-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 zero-shot에서 최대 100.2 FPS와 53.4 AP의 성능을 달성합니다.
해당 논문의 초록은 다음과 같습니다:
언어 모달리티를 통합한 end-to-end transformer 기반 검출기(DETR)는 closed-set 및 open-vocabulary object detection(OVD) 작업 모두에서 뛰어난 성능을 입증했습니다. 그러나 높은 계산 요구 사항은 실시간 object detection(OD) 시나리오에서의 실용적 적용을 제한해 왔습니다. 본 논문에서는 OVDEval 벤치마크의 두 주요 모델인 OmDet와 Grounding-DINO의 한계를 분석하고, OmDet-Turbo를 소개합니다. 이 새로운 transformer 기반 실시간 OVD 모델은 OmDet와 Grounding-DINO에서 관찰된 병목 현상을 완화하도록 설계된 혁신적인 Efficient Fusion Head(EFH) 모듈을 특징으로 합니다. 특히, OmDet-Turbo-Base는 TensorRT와 language cache 기법을 적용하여 초당 100.2 프레임(FPS)을 달성합니다. 주목할 점은 COCO와 LVIS 데이터셋의 zero-shot 시나리오에서 OmDet-Turbo가 현재 최첨단 supervised 모델과 거의 동등한 수준의 성능을 달성한다는 것입니다. 또한, ODinW와 OVDEval에서 각각 AP 30.1과 NMS-AP 26.86을 기록하며 새로운 최첨단 벤치마크를 수립했습니다. OmDet-Turbo의 산업적 실용성은 벤치마크 데이터셋에서의 뛰어난 성능과 우수한 추론 속도로 뒷받침되며, 이를 실시간 object detection 작업에 있어 매력적인 선택지로 자리매김하게 합니다.
OmDet-Turbo architecture overview. Taken from the original paper. 이 모델은 yonigozlan이(가) 기여했습니다. 원본 코드는 여기에서 찾을 수 있습니다.
사용 팁
Grounding DINO와 같은 다른 zero-shot 객체 감지 모델과 비교할 때, OmDet-Turbo의 고유한 특징은 텍스트 임베딩의 캐싱을 허용하는 분리된 클래스 및 프롬프트 임베딩 구조입니다. 이는 모델이 클래스와 태스크를 모두 입력으로 필요로 한다는 것을 의미하며, 여기서 클래스는 감지하려는 객체의 목록이고, 태스크는 open-vocabulary 감지를 안내하는 grounded text입니다. 이 접근 방식은 open-vocabulary 감지의 범위를 제한하고 디코딩 과정을 더 빠르게 만듭니다.
OmDetTurboProcessor는 클래스, 태스크, 이미지 3원조를 준비하는 데 사용됩니다. 태스크 입력은 선택 사항이며, 제공되지 않으면 "Detect [class1], [class2], [class3], ..."이 기본값으로 사용됩니다. 모델의 결과를 처리하려면 OmDetTurboProcessor의 post_process_grounded_object_detection를 사용할 수 있습니다. 주목할 점은, 이 함수가 입력 클래스를 인자로 받는다는 것입니다. 다른 zero-shot 객체 감지 모델과 달리 클래스와 태스크 임베딩이 분리되어 있어 후처리 단계에서 예측된 클래스 임베딩의 디코딩이 필요하지 않으며, 예측된 클래스를 입력된 클래스와 직접 매칭할 수 있습니다.
사용 예시
단일 이미지 추론
단일 이미지에서 zero-shot 객체 감지를 수행하기 위해 모델을 로드하고 입력을 준비하는 방법은 다음과 같습니다:
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
< source >( 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], 선택) — 텍스트 백본의 config 객체 또는 사전입니다. - backbone_config (
Union[dict, ~configuration_utils.PreTrainedConfig], 선택) — backbone 모델의 설정입니다. - apply_layernorm_after_vision_backbone (
bool, 선택 사항, 기본값True) — 비전 백본 출력의 feature map에 layer normalization을 적용할지 여부입니다. - 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) — batch normalization 레이어에서 사용되는 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) — task encoder의 feedforward 차원입니다. - 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") — 인코더의 feedforward 네트워크에 사용되는 활성화 함수입니다. - 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) — 인코더의 feedforward 차원입니다. - encoder_layers (
int, 선택 사항, 기본값1) — Transformer 인코더의 숨겨진 레이어 수입니다. 설정하지 않으면num_layers와 동일한 값을 사용합니다. - positional_encoding_temperature (
int, 선택 사항, 기본값 10000) — 인코더의 위치 인코딩 온도입니다. - num_feature_levels (
int, 선택 사항, 기본값 3) — 디코더의 multi-scale deformable attention 모듈에 사용할 feature level의 수입니다. - decoder_hidden_dim (
int, 선택 사항, 기본값256) — 숨겨진 표현의 차원입니다. - decoder_num_heads (
int, 선택 사항, 기본값8) — Transformer decoder의 각 attention layer에 사용할 attention head의 수입니다. - decoder_num_layers (
int, 선택 사항, 기본값6) — Transformer decoder의 숨겨진 레이어 수입니다. 설정하지 않으면num_layers와 동일한 값을 사용합니다. - decoder_activation (
str, 선택 사항, 기본값"relu") — 디코더에 사용할 활성화 함수입니다. - decoder_dim_feedforward (
int, 선택 사항, 기본값 2048) — 디코더의 feedforward 차원입니다. - decoder_num_points (
int, 선택 사항, 기본값 4) — decoder multi-scale deformable attention 모듈에서 샘플링되는 점의 수입니다. - 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와 유사한 구성이 생성됩니다.
Configuration 객체는 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.configOmDetTurboProcessor
class transformers.OmDetTurboProcessor
< source >( image_processortokenizer )
이미지 프로세서와 토크나이저를 단일 프로세서로 감싸는 OmDetTurboProcessor를 생성합니다.
OmDetTurboProcessor은 DetrImageProcessor와 CLIPTokenizer의 모든 기능을 제공합니다. 자세한 내용은 ~DetrImageProcessor와 ~CLIPTokenizer를 참고하세요.
__call__
< source >( 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 = None**kwargs: *<class 'transformers.models.omdet_turbo.processing_omdet_turbo.OmDetTurboProcessorKwargs'> ) → ~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, kwargs,list[str],TextInput또는PreTokenizedInput, optional) — 인코딩할 객체 탐지 작업 설명입니다. 제공되지 않으면text입력을 기반으로 기본 작업 설명이 생성됩니다(예: “Detect {text}.”). 단일 문자열, 문자열 목록(이미지당 하나), 또는 사전 토큰화된 입력일 수 있습니다. 작업 설명은 모델이 이미지에서 어떤 객체를 탐지할지 안내합니다. - return_tensors (
str또는 TensorType, 선택 사항) — 설정된 경우, 특정 프레임워크의 텐서를 반환합니다. 허용되는 값은 다음과 같습니다:'pt': PyTorchtorch.Tensor객체를 반환합니다.'np': NumPynp.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_type를 지정할 수 있습니다. - skip_tensor_conversion (
list[str]또는set[str], 선택 사항) —tensor_type가 지정된 경우에도 텐서로 변환하지 않아야 하는 키의 목록 또는 집합.
post_process_grounded_object_detection
< source >( 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) — 박스 non-maximum suppression에 사용할 임계값입니다. 값은 [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
class transformers.OmDetTurboForObjectDetection
< source >( config: OmDetTurboConfig )
매개변수
- config (OmDetTurboConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 연관된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.
OmDetTurbo 모델(비전 및 텍스트 백본, 인코더-디코더 아키텍처로 구성)은 COCO detection과 같은 작업에 대해 바운딩 박스와 클래스 점수를 출력합니다.
이 모델은 PreTrainedModel에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대한 세부 사항은 상위 클래스 문서를 확인하세요.
이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.
forward
< source >( 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, shape(batch_size, num_channels, image_size, image_size)) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 DetrImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 DetrImageProcessor.call()를 참조하세요 (OmDetTurboProcessor는 이미지 처리에 DetrImageProcessor를 사용합니다). - classes_input_ids (
torch.LongTensor형상(total_classes (>= batch_size), sequence_length)) — 언어 모델 어휘에서 입력 클래스 시퀀스 토큰의 인덱스. 각 작업에 여러 클래스를 제공할 수 있으므로, 토큰화된 클래스는 평탄화(flattened)되며 클래스의 구조는classes_structure인수로 제공됩니다.OmDetTurboProcessor를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 OmDetTurboProcessor.call()를 참조하세요.
- classes_attention_mask (
torch.BoolTensor, shape(total_classes (>= batch_size), num_classes, sequence_length)) — 클래스에 대한 attention mask입니다. 어떤 토큰에 attention을 주고 어떤 토큰에는 주지 않을지를 나타내는 binary mask입니다. - tasks_input_ids (
torch.LongTensor의 shape가(batch_size, sequence_length)) — 언어 모델 어휘에서 입력 태스크 시퀀스 토큰의 인덱스입니다.OmDetTurboProcessor를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 OmDetTurboProcessor.call()를 참조하세요.
- tasks_attention_mask (
torch.BoolTensor, shape(batch_size, sequence_length)) — 작업에 대한 attention mask입니다. 어떤 토큰을 attend해야 하고 어떤 토큰은 attend하지 않아야 하는지를 나타내는 이진 mask입니다. - classes_structure (
torch.LongTensor, shape(batch_size)) — 클래스 구조입니다. 이 텐서는 각 태스크에 대한 클래스 수를 나타냅니다. - 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)입니다. - output_attentions (
bool, 선택 사항) — 모든 attention 레이어의 attentions 텐서를 반환할지 여부. 자세한 내용은 반환 텐서 섹션의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__ 특수 메서드를 오버라이드합니다.
이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신
Module인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.
- loss (
torch.Tensor, 선택 사항) — 손실 값입니다. - decoder_coord_logits (
torch.Tensor, shape(batch_size, num_queries, 4)) — 객체의 예측된 좌표 logits입니다. - decoder_class_logits (
torch.Tensor, shape(batch_size, num_queries, num_classes)) — 객체의 예측 클래스입니다. - init_reference_points (
torch.Tensor, shape(batch_size, num_queries, 4)) — 초기 reference points입니다. - intermediate_reference_points (
tuple[tuple[torch.Tensor]], 선택 사항) — 중간 참조 점입니다. - encoder_coord_logits (
torch.Tensor, shape(batch_size, num_queries, 4)) — encoder에서 예측한 객체의 좌표입니다. - encoder_class_logits (
tuple[torch.Tensor], 선택) — encoder에서 예측한 객체의 클래스입니다. - encoder_extracted_states (
torch.Tensor, 선택 사항) — 인코더의 Feature Pyramid Network(FPN)와 Path Aggregation Network(PAN)에서 추출된 상태입니다. - decoder_hidden_states (
tuple[torch.Tensor], 선택) —torch.Tensor의 튜플(임베딩 출력 1개 + 각 레이어 출력 1개)로, 모양은(batch_size, sequence_length, hidden_size)입니다. 각 레이어 출력에서의 모델 hidden-states와 초기 임베딩 출력을 포함합니다. - decoder_attentions (
tuple[tuple[torch.Tensor]], 선택 사항) — 각 레이어의 어텐션에 해당하는torch.Tensor튜플의 튜플로, 모양은(batch_size, num_heads, sequence_length, sequence_length)입니다. 어텐션 softmax 이후의 어텐션 가중치로, self-attention, cross-attention 및 multi-scale deformable attention 헤드에서 가중 평균을 계산하는 데 사용됩니다. - encoder_hidden_states (
tuple[torch.Tensor], 선택) —torch.Tensor의 튜플(임베딩 출력 1개 + 각 레이어 출력 1개)로, 모양은(batch_size, sequence_length, hidden_size)입니다. 각 레이어 출력에서의 모델 hidden-states와 초기 임베딩 출력을 포함합니다. - encoder_attentions (
tuple[tuple[torch.Tensor]], 선택 사항) — 각 레이어의 어텐션에 해당하는torch.Tensor튜플의 튜플로, 모양은(batch_size, num_heads, sequence_length, sequence_length)입니다. 어텐션 softmax 이후의 어텐션 가중치로, self-attention, cross-attention 및 multi-scale deformable attention 헤드에서 가중 평균을 계산하는 데 사용됩니다. - classes_structure (
torch.LongTensor, 선택 사항) — 각 이미지에 대해 쿼리된 클래스의 수.
예:
>>> 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]