Transformers documentation

D-FINE

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-10-17에 HF papers에 게시되었으며, 2025-04-29에 Hugging Face Transformers에 기여되었습니다.

D-FINE

개요

D-FINE 모델은 Yansong Peng, Hebei Li, Peixi Wu, Yueyi Zhang, Xiaoyan Sun, Feng Wu가 D-FINE: Redefine Regression Task in DETRs as Fine-grained Distribution Refinement에서 제안했습니다.

해당 논문의 초록은 다음과 같습니다:

DETR 모델에서 바운딩 박스 회귀 작업을 재정의하여 뛰어난 로컬라이제이션 정밀도를 달성하는 강력한 실시간 객체 탐지 모델 D-FINE을 소개합니다. D-FINE은 Fine-grained Distribution Refinement(FDR)과 Global Optimal Localization Self-Distillation(GO-LSD)이라는 두 가지 핵심 구성 요소로 이루어져 있습니다. FDR은 회귀 과정을 고정된 좌표 예측에서 확률 분포를 반복적으로 정제하는 방식으로 변환하여, 로컬라이제이션 정확도를 크게 향상시키는 세밀한 중간 표현을 제공합니다. GO-LSD는 정제된 분포에서 더 얕은 레이어로 로컬라이제이션 지식을 자기 증류(self-distillation)를 통해 전달하는 동시에, 더 깊은 레이어의 잔차 예측 작업을 단순화하는 양방향 최적화 전략입니다. 또한 D-FINE은 계산 집약적인 모듈과 연산에 경량화 최적화를 적용하여 속도와 정확도 사이의 균형을 더 잘 맞춥니다. 구체적으로, D-FINE-L / X는 NVIDIA T4 GPU에서 COCO 데이터셋 기준으로 124 / 78 FPS에서 54.0% / 55.8% AP를 달성합니다. Objects365에서 사전 학습을 수행하면 D-FINE-L / X는 57.1% / 59.3% AP를 달성하여 기존 모든 실시간 탐지기를 능가합니다. 또한, 우리의 방법은 추가 파라미터와 학습 비용이 거의 없으면서도 다양한 DETR 모델의 성능을 최대 5.3% AP까지 크게 향상시킵니다. 코드와 사전 학습 모델: this https URL.

이 모델은 VladOS95-cyber님이 기여했습니다. 원본 코드는 여기에서 찾을 수 있습니다.

사용 팁

import torch

from transformers import AutoImageProcessor, DFineForObjectDetection
from transformers.image_utils import load_image


url = 'http://images.cocodataset.org/val2017/000000039769.jpg'
image = load_image(url)

image_processor = AutoImageProcessor.from_pretrained("ustc-community/dfine_x_coco")
model = DFineForObjectDetection.from_pretrained("ustc-community/dfine_x_coco", device_map="auto")

inputs = image_processor(images=image, return_tensors="pt").to(model.device)

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

results = image_processor.post_process_object_detection(outputs, target_sizes=[(image.height, image.width)], threshold=0.5)

for result in results:
    for score, label_id, box in zip(result["scores"], result["labels"], result["boxes"]):
        score, label = score.item(), label_id.item()
        box = [round(i, 2) for i in box.tolist()]
        print(f"{model.config.id2label[label]}: {score:.2f} {box}")
cat: 0.96 [344.49, 23.4, 639.84, 374.27]
cat: 0.96 [11.71, 53.52, 316.64, 472.33]
remote: 0.95 [40.46, 73.7, 175.62, 117.57]
sofa: 0.92 [0.59, 1.88, 640.25, 474.74]
remote: 0.89 [333.48, 77.04, 370.77, 187.3]

DFineConfig

class transformers.DFineConfig

< >

( 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 = Trueinitializer_range: float = 0.01initializer_bias_prior_prob: float | None = Nonelayer_norm_eps: float = 1e-05batch_norm_eps: float = 1e-05backbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonefreeze_backbone_batch_norms: bool = Trueencoder_hidden_dim: int = 256encoder_in_channels: list[int] | tuple[int, ...] = (512, 1024, 2048)feat_strides: list[int] | tuple[int, ...] = (8, 16, 32)encoder_layers: int = 1encoder_ffn_dim: int = 1024encoder_attention_heads: int = 8dropout: float | int = 0.0activation_dropout: float | int = 0.0encode_proj_layers: list[int] | tuple[int, ...] = (2,)positional_encoding_temperature: int = 10000encoder_activation_function: str = 'gelu'activation_function: str = 'silu'eval_size: int | None = Nonenormalize_before: bool = Falsehidden_expansion: float = 1.0d_model: int = 256num_queries: int = 300decoder_in_channels: list[int] | tuple[int, ...] = (256, 256, 256)decoder_ffn_dim: int = 1024num_feature_levels: int = 3decoder_n_points: int | list[int] = 4decoder_layers: int = 6decoder_attention_heads: int = 8decoder_activation_function: str = 'relu'attention_dropout: float | int = 0.0num_denoising: int = 100label_noise_ratio: float = 0.5box_noise_scale: float = 1.0learn_initial_query: bool = Falseanchor_image_size: int | list[int] | None = Nonewith_box_refine: bool = Truematcher_alpha: float = 0.25matcher_gamma: float = 2.0matcher_class_cost: float = 2.0matcher_bbox_cost: float = 5.0matcher_giou_cost: float = 2.0use_focal_loss: bool = Trueauxiliary_loss: bool = Truefocal_loss_alpha: float = 0.75focal_loss_gamma: float = 2.0weight_loss_vfl: float = 1.0weight_loss_bbox: float = 5.0weight_loss_giou: float = 2.0weight_loss_fgl: float = 0.15weight_loss_ddf: float = 1.5eos_coefficient: float = 0.0001eval_idx: int = -1layer_scale: int | float = 1.0max_num_bins: int = 32reg_scale: float = 4.0depth_mult: float = 1.0top_prob_values: int = 4lqe_hidden_dim: int = 64lqe_layers: int = 2decoder_offset_scale: float = 0.5decoder_method: str = 'default'up: float = 0.5tie_word_embeddings: bool = True )

매개변수

  • is_encoder_decoder (bool, 선택 사항, 기본값 True) — 모델이 인코더/디코더로 사용되는지 여부를 나타냅니다.
  • initializer_range (float, 선택 사항, 기본값 0.01) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다.
  • initializer_bias_prior_prob (float, 선택 사항) — enc_score_head와 class_embed의 bias를 초기화하는 데 사용되는 bias initializer의 사전 확률입니다. None인 경우, 모델 가중치를 초기화할 때 prior_prob을 prior_prob = 1 / (num_labels + 1)로 계산합니다.
  • layer_norm_eps (float, 선택 사항, 기본값 1e-05) — 레이어 정규화 레이어에서 사용되는 epsilon 값입니다.
  • batch_norm_eps (float, 선택 사항, 기본값 1e-05) — batch normalization 레이어에서 사용되는 epsilon 값입니다.
  • backbone_config (Union[dict, ~configuration_utils.PreTrainedConfig], 선택) — backbone 모델의 설정입니다.
  • freeze_backbone_batch_norms (bool, 선택 사항, 기본값 True) — backbone의 batch normalization 레이어를 고정할지 여부입니다.
  • encoder_hidden_dim (int, 선택 사항, 기본값 256) — 숨겨진 표현의 차원입니다.
  • encoder_in_channels (list, 선택 사항, 기본값 [512, 1024, 2048]) — 인코더에 입력되는 다중 레벨 특징.
  • feat_strides (list[int], 선택 사항, 기본값 [8, 16, 32]) — 각 feature map에서 사용되는 strides입니다.
  • encoder_layers (int, 선택 사항, 기본값 1) — Transformer 인코더의 숨겨진 레이어 수입니다. 설정하지 않으면 num_layers와 동일한 값을 사용합니다.
  • encoder_ffn_dim (int, 선택 사항, 기본값 1024) — 인코더의 “중간” 레이어(일반적으로 feed-forward 레이어라고 함)의 차원입니다.
  • encoder_attention_heads (int, 선택 사항, 기본값 8) — Transformer 인코더의 각 어텐션 레이어에 사용할 어텐션 헤드 수입니다.
  • dropout (Union[float, int], 선택 사항, 기본값 0.0) — 모든 dropout 레이어에 적용할 비율입니다.
  • activation_dropout (Union[float, int], 선택 사항, 기본값 0.0) — 완전 연결 레이어 내부 활성화에 적용할 dropout 비율입니다.
  • encode_proj_layers (list[int], 선택 사항, 기본값 [2]) — 인코더에서 사용할 투영된 레이어의 인덱스입니다.
  • positional_encoding_temperature (int, 선택 사항, 기본값 10000) — 위치 인코딩을 생성할 때 사용되는 temperature 파라미터입니다.
  • encoder_activation_function (str, 선택 사항, 기본값 "gelu") — 인코더와 풀러에서 사용되는 비선형 활성화 함수(함수 또는 문자열)입니다. 문자열인 경우 "gelu", "relu", "silu", "gelu_new"를 지원합니다.
  • activation_function (str, 선택 사항, 기본값 silu) — 디코더에서 사용되는 비선형 활성화 함수(함수 또는 문자열)입니다. 예를 들어, "gelu", "relu", "silu" 등이 있습니다.
  • eval_size (tuple[int, int], 선택 사항) — stride를 고려한 후 position embeddings의 유효한 높이와 너비를 계산하는 데 사용되는 높이와 너비입니다.
  • normalize_before (bool, 선택 사항, 기본값 False) — transformer encoder layer에서 self-attention 및 feed-forward 모듈을 적용하기 전에 layer normalization을 적용할지 여부를 결정합니다.
  • hidden_expansion (float, 선택 사항, 기본값 1.0) — RepVGGBlock과 CSPRepLayer의 차원 크기를 확장하는 비율입니다.
  • d_model (int, 선택 사항, 기본값 256) — 인코더 레이어와 풀러 레이어의 크기입니다.
  • num_queries (int, 선택 사항, 기본값 300) — 객체 쿼리의 수입니다.
  • decoder_in_channels (list, 선택 사항, 기본값 [256, 256, 256]) — 디코더의 다중 레벨 특징 차원
  • decoder_ffn_dim (int, 선택 사항, 기본값 1024) — decoder의 “intermediate”(일반적으로 feed-forward라고도 함) 레이어의 차원입니다.
  • num_feature_levels (int, 선택 사항, 기본값 3) — 입력 특징 레벨의 수입니다.
  • decoder_n_points (int, 선택 사항, 기본값 4) — 디코더의 각 어텐션 헤드에서 각 피처 레벨당 샘플링되는 키의 수입니다.
  • decoder_layers (int, 선택 사항, 기본값 6) — Transformer decoder의 hidden layer 수입니다. 설정하지 않으면 num_layers와 동일한 값을 사용합니다.
  • decoder_attention_heads (int, 선택 사항, 기본값 8) — Transformer decoder의 각 attention layer에 사용할 attention head 수입니다.
  • decoder_activation_function (str, 선택 사항, 기본값 "relu") — 디코더에서 사용되는 비선형 활성화 함수(함수 또는 문자열)입니다. 문자열인 경우 "gelu", "relu", "silu", "gelu_new"를 지원합니다.
  • attention_dropout (Union[float, int], 선택 사항, 기본값 0.0) — Attention 확률에 적용할 dropout 비율입니다.
  • num_denoising (int, 선택 사항, 기본값 100) — 대조적 노이즈 제거에 사용할 전체 노이즈 제거 작업 또는 쿼리의 수입니다.
  • label_noise_ratio (float, 선택 사항, 기본값 0.5) — 랜덤 노이즈를 추가할 디노이징 레이블의 비율입니다.
  • box_noise_scale (float, 선택 사항, 기본값 1.0) — 바운딩 박스에 추가할 노이즈의 스케일 또는 크기입니다.
  • learn_initial_query (bool, 선택 사항, 기본값 False) — 학습 중에 디코더의 초기 쿼리 임베딩을 학습할지 여부를 나타냅니다
  • anchor_image_size (tuple[int, int], 선택) — 평가 시 바운딩 박스 앵커를 생성하는 데 사용되는 입력 이미지의 높이와 너비입니다. None인 경우, 앵커가 자동으로 생성됩니다.
  • with_box_refine (bool, 선택 사항, 기본값 True) — 각 decoder 레이어가 이전 레이어의 예측을 기반으로 bounding box를 개선하는 반복적 bounding box refinement을 적용할지 여부입니다.
  • matcher_alpha (float, 선택 사항, 기본값 0.25) — Hungarian Matcher에서 사용하는 alpha 매개변수입니다.
  • matcher_gamma (float, 선택 사항, 기본값 2.0) — Hungarian Matcher에서 사용하는 gamma 매개변수입니다.
  • matcher_class_cost (float, 선택 사항, 기본값 2.0) — Hungarian Matcher가 사용하는 클래스 손실의 상대적 가중치입니다.
  • matcher_bbox_cost (float, 선택 사항, 기본값 5.0) — Hungarian Matcher가 사용하는 바운딩 박스 손실의 상대 가중치입니다.
  • matcher_giou_cost (float, 선택 사항, 기본값 2.0) — Hungarian Matcher에서 사용되는 giou loss의 상대적 가중치입니다.
  • use_focal_loss (bool, 선택 사항, 기본값 True) — focal loss를 사용할지 여부를 지정하는 매개변수입니다.
  • auxiliary_loss (bool, 선택 사항, 기본값 True) — 보조 디코딩 손실(각 디코더 레이어의 손실)을 사용할지 여부입니다.
  • focal_loss_alpha (float, 선택 사항, 기본값 0.75) — focal loss를 계산하는 데 사용되는 alpha 매개변수입니다.
  • focal_loss_gamma (float, 선택 사항, 기본값 2.0) — focal loss를 계산하는 데 사용되는 gamma 매개변수입니다.
  • weight_loss_vfl (float, 선택 사항, 기본값 1.0) — 객체 탐지 손실에서 varifocal loss의 상대적 가중치입니다.
  • weight_loss_bbox (float, 선택 사항, 기본값 5.0) — 객체 탐지 손실에서 L1 바운딩 박스 손실의 상대적 가중치.
  • weight_loss_giou (float, 선택, 기본값 2.0) — 객체 감지 손실에서 일반화 IoU 손실의 상대적 가중치입니다.
  • weight_loss_fgl (float, 선택 사항, 기본값 0.15) — 객체 탐지 손실에서 세분화된 위치 지정 손실의 상대적 가중치.
  • weight_loss_ddf (float, 선택 사항, 기본값 1.5) — 객체 탐지 손실에서 분리된 증류 초점 손실의 상대 가중치.
  • eos_coefficient (float, 선택 사항, 기본값 0.0001) — 객체 감지 손실에서 ‘no-object’ 클래스의 상대 분류 가중치입니다.
  • eval_idx (int, 선택 사항, 기본값 -1) — 평가에 사용할 decoder 레이어의 인덱스입니다. 음수인 경우 끝에서부터 세어지며(예: -1은 마지막 레이어를 사용한다는 의미입니다). 이를 통해 decoder 스택의 후반부 레이어를 학습하는 동안에도 초기 예측이 가능합니다.
  • layer_scale (float, 선택 사항, 기본값 1.0) — 후반부 decoder 레이어의 hidden dimension에 적용되는 스케일링 계수입니다. 평가 레이어 이후 모델 용량을 조정하는 데 사용됩니다.
  • max_num_bins (int, 선택 사항, 기본값 32) — 분포 기반 바운딩 박스 정제에 사용할 최대 빈(bin) 수입니다. 값이 높을수록 더 세밀한 위치 파악이 가능하지만 계산 비용이 증가합니다.
  • reg_scale (float, 선택 사항, 기본값 4.0) — 회귀 분포의 스케일 팩터입니다. 바운딩 박스 정제 과정의 범위와 세밀도를 제어합니다.
  • depth_mult (float, 선택 사항, 기본값 1.0) — RepNCSPELAN4 레이어의 블록 수에 곱해지는 배수입니다. 아키텍처를 유지하면서 모델의 깊이를 조정하는 데 사용됩니다.
  • top_prob_values (int, 선택 사항, 기본값 4) — 각 코너의 분포에서 고려할 상위 확률 값의 개수.
  • lqe_hidden_dim (int, 선택 사항, 기본값 64) — Location Quality Estimator(LQE) 네트워크의 숨겨진 차원 크기.
  • lqe_layers (int, 선택 사항, 기본값 2) — Location Quality Estimator MLP의 레이어 수입니다.
  • decoder_offset_scale (float, 선택 사항, 기본값 0.5) — deformable attention에서 사용되는 offset scale입니다.
  • decoder_method (str, 선택 사항, 기본값 "default") — 디코더에 사용할 방법: "default" 또는 "discrete".
  • up (float, 선택 사항, 기본값 0.5) — Weighting Function의 상한을 제어합니다.
  • tie_word_embeddings (bool, 선택, 기본값 True) — 모델의 tied_weights_keys 매핑에 따라 가중치 임베딩을 묶을지 여부.

이것은 DFineModel의 설정을 저장하기 위한 설정 클래스입니다. 지정된 인자에 따라 D Fine 모델을 인스턴스화하여 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 설정을 인스턴스화하면 ustc-community/dfine-xlarge-coco와 유사한 설정이 생성됩니다.

Configuration 객체는 PreTrainedConfig를 상속하며 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 PreTrainedConfig의 문서를 참고하세요.

DFineModel

class transformers.DFineModel

< >

( config: DFineConfig )

매개변수

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

head가 없는 backbone과 encoder-decoder로 구성된 RT-DETR Model이 raw hidden states를 출력합니다.

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

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

forward

< >

( pixel_values: Tensorpixel_mask: typing.Optional[torch.LongTensor] = Noneencoder_outputs: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: list[dict] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → DFineModelOutput or tuple(torch.Tensor)

매개변수

  • pixel_values (torch.Tensor, shape (batch_size, num_channels, image_size, image_size)) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 image_processor_class를 사용하여 얻을 수 있습니다. 자세한 내용은 image_processor_class.__call__를 참조하세요. (processor_class는 이미지 처리에 image_processor_class를 사용합니다.)
  • pixel_mask (torch.LongTensor 다음 형식의 (batch_size, height, width), 선택 사항) — 패딩 픽셀 값에 대한 attention을 수행하지 않도록 하는 마스크. [0, 1]에서 선택된 마스크 값: 실제 픽셀(즉, 마스크되지 않은 픽셀)은 1, 패딩 픽셀(즉, 마스크된 픽셀)은 0. attention 마스크란 무엇일까요? [0, 1]:
    • 실제 픽셀(즉, 마스크가 적용되지 않은 픽셀)에 대해 1
    • 패딩(즉, 마스크 처리된) 픽셀은 0

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

  • encoder_outputs (torch.Tensor, 선택 사항) — (last_hidden_state, 선택 사항: hidden_states, 선택 사항: attentions)로 구성된 Tuple last_hidden_state의 shape은 (batch_size, sequence_length, hidden_size), 선택 사항)이며, 인코더의 마지막 레이어 출력에서 생성된 hidden-states 시퀀스입니다. 디코더의 cross-attention에 사용됩니다.
  • inputs_embeds (torch.Tensor, shape (batch_size, sequence_length, hidden_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)입니다.

반환값

DFineModelOutput 또는 tuple(torch.Tensor)

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

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

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

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

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

  • intermediate_logits (torch.Tensor, shape (batch_size, config.decoder_layers, sequence_length, config.num_labels)) — 스택된 중간 logits(decoder의 각 레이어의 logits).

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

  • intermediate_predicted_corners (torch.Tensor, shape (batch_size, config.decoder_layers, num_queries, 4)) — 스택된 중간 예측 코너(디코더의 각 레이어에서 예측된 코너).

  • initial_reference_points (torch.Tensor, shape (batch_size, num_queries, 4)) — 첫 번째 decoder layer에 사용되는 초기 reference points입니다.

  • 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[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 가중치입니다.

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

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

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

  • encoder_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와 초기 임베딩 출력을 더한 값.

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

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

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

  • enc_topk_logits (torch.Tensor, shape (batch_size, sequence_length, config.num_labels)) — 인코더 단계에서 상위 config.two_stage_num_proposals 점수 영역을 region proposals로 선택하는 예측 바운딩 박스 점수입니다. 바운딩 박스 이진 분류(즉, foreground와 background)의 출력입니다.

  • enc_topk_bboxes (torch.Tensor, shape (batch_size, sequence_length, 4)) — 인코더 단계에서 예측된 바운딩 박스 좌표의 로짓.

  • enc_outputs_class (torch.Tensor, shape (batch_size, sequence_length, config.num_labels), 선택 사항, config.with_box_refine=True이고 config.two_stage=True일 때 반환됨) — 첫 번째 단계에서 점수가 가장 높은 config.two_stage_num_proposals개의 바운딩 박스가 영역 제안으로 선택되는 예측 바운딩 박스 점수입니다. 바운딩 박스 이진 분류(즉, 포그라운드와 배경)의 출력입니다.

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

  • denoising_meta_values (dict, 선택 사항) — denoising 관련 값에 대한 추가 사전입니다.

예:

>>> from transformers import AutoImageProcessor, DFineModel
>>> 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()))

>>> image_processor = AutoImageProcessor.from_pretrained("PekingU/DFine_r50vd")
>>> model = DFineModel.from_pretrained("PekingU/DFine_r50vd")

>>> inputs = image_processor(images=image, return_tensors="pt")

>>> outputs = model(**inputs)

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

DFineForObjectDetection

클래스 transformers.DFineForObjectDetection

< >

( config: DFineConfig )

매개변수

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

RT-DETR 모델(백본과 인코더-디코더로 구성)은 바운딩 박스와 로짓을 출력하며, 이는 점수와 클래스로 추가 디코딩됩니다.

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

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

forward

< >

( pixel_values: Tensorpixel_mask: typing.Optional[torch.LongTensor] = Noneencoder_outputs: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: list[dict] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → DFineObjectDetectionOutput or tuple(torch.Tensor)

매개변수

  • pixel_values (torch.Tensor, shape (batch_size, num_channels, image_size, image_size)) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 image_processor_class를 사용하여 얻을 수 있습니다. 자세한 내용은 image_processor_class.__call__를 참조하세요. (processor_class는 이미지 처리에 image_processor_class를 사용합니다.)
  • pixel_mask (torch.LongTensor 다음 형식의 (batch_size, height, width), 선택 사항) — 패딩 픽셀 값에 대한 attention을 수행하지 않도록 하는 마스크. [0, 1]에서 선택된 마스크 값: 실제 픽셀(즉, 마스크되지 않은 픽셀)은 1, 패딩 픽셀(즉, 마스크된 픽셀)은 0. attention 마스크란 무엇일까요? [0, 1]:
    • 실제 픽셀(즉, 마스크가 적용되지 않은 픽셀)에 대해 1
    • 패딩(즉, 마스크 처리된) 픽셀은 0

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

  • encoder_outputs (torch.Tensor, 선택 사항) — (last_hidden_state, 선택 사항: hidden_states, 선택 사항: attentions)로 구성된 Tuple last_hidden_state의 shape은 (batch_size, sequence_length, hidden_size), 선택 사항)이며, 인코더의 마지막 레이어 출력에서 생성된 hidden-states 시퀀스입니다. 디코더의 cross-attention에 사용됩니다.
  • inputs_embeds (torch.Tensor, shape (batch_size, sequence_length, hidden_size), 선택) — input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델 내부의 임베딩 조회 행렬보다 input_ids 인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요한 경우에 유용합니다.
  • 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)입니다.

반환값

DFineObjectDetectionOutput 또는 tuple(torch.Tensor)

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

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

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

  • loss (torch.Tensor, shape (1,), 선택 사항, labels가 제공될 때 반환됨) — 클래스 예측에 대한 음의 로그 가능도(교차 엔트로피)와 바운딩 박스 손실의 선형 결합으로 계산된 총 손실입니다. 후자는 L1 손실과 일반화된 스케일 불변 IoU 손실의 선형 결합으로 정의됩니다.

  • loss_dict (Dict, 선택) — 개별 손실 값을 포함하는 사전입니다. 로깅에 유용합니다.

  • logits (torch.Tensor, shape (batch_size, num_queries, num_classes + 1)) — 모든 query에 대한 분류 logits(no-object 포함).

  • pred_boxes (torch.Tensor, shape (batch_size, num_queries, 4)) — 모든 쿼리에 대한 정규화된 박스 좌표로, (center_x, center_y, width, height)로 표현됩니다. 이 값들은 배치 내 각 개별 이미지의 크기에 대해 [0, 1] 범위로 정규화되어 있습니다(가능한 패딩은 무시). ~DFineImageProcessor.post_process_object_detection를 사용하여 정규화되지 않은(절대) 바운딩 박스를 가져올 수 있습니다.

  • auxiliary_outputs (list[Dict], 선택) — 선택 사항이며, 보조 손실이 활성화된 경우(즉, config.auxiliary_loss가 True로 설정된 경우)와 라벨이 제공된 경우에만 반환됩니다. 각 디코더 레이어에 대해 위의 두 키(logits와 pred_boxes)를 포함하는 사전의 목록입니다.

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

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

  • intermediate_logits (torch.Tensor, shape (batch_size, config.decoder_layers, num_queries, config.num_labels)) — 스택된 중간 logits(decoder의 각 레이어의 logits).

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

  • intermediate_predicted_corners (torch.Tensor, shape (batch_size, config.decoder_layers, num_queries, 4)) — 스택된 중간 예측 코너(디코더의 각 레이어에서 예측된 코너).

  • initial_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[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 가중치입니다.

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

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

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

  • encoder_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와 초기 임베딩 출력을 더한 값.

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

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

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

  • enc_topk_logits (torch.Tensor, shape (batch_size, sequence_length, config.num_labels), 선택, config.with_box_refine=True이고 config.two_stage=True일 때 반환됨) — 인코더에서 예측된 바운딩 박스 좌표의 logits입니다.

  • enc_topk_bboxes (torch.Tensor, shape (batch_size, sequence_length, 4), 선택 사항, config.with_box_refine=True이고 config.two_stage=True일 때 반환됨) — 인코더에서 예측된 바운딩 박스 좌표의 logits입니다.

  • enc_outputs_class (torch.Tensor, shape (batch_size, sequence_length, config.num_labels), 선택 사항, config.with_box_refine=True이고 config.two_stage=True일 때 반환됨) — 첫 번째 단계에서 점수가 가장 높은 config.two_stage_num_proposals개의 바운딩 박스가 영역 제안으로 선택되는 예측 바운딩 박스 점수입니다. 바운딩 박스 이진 분류(즉, 포그라운드와 배경)의 출력입니다.

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

  • denoising_meta_values (dict, 선택) — 디노이징 관련 값에 대한 추가 사전

예:

>>> import torch
>>> from transformers.image_utils import load_image
>>> from transformers import AutoImageProcessor, DFineForObjectDetection

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = load_image(url)

>>> image_processor = AutoImageProcessor.from_pretrained("ustc-community/dfine-xlarge-coco")
>>> model = DFineForObjectDetection.from_pretrained("ustc-community/dfine-xlarge-coco")

>>> # prepare image for the model
>>> inputs = image_processor(images=image, return_tensors="pt")

>>> # forward pass
>>> outputs = model(**inputs)

>>> logits = outputs.logits
>>> list(logits.shape)
[1, 300, 80]

>>> boxes = outputs.pred_boxes
>>> list(boxes.shape)
[1, 300, 4]

>>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
>>> target_sizes = torch.tensor([image.size[::-1]])
>>> results = image_processor.post_process_object_detection(outputs, threshold=0.9, target_sizes=target_sizes)
>>> result = results[0]  # first image in batch

>>> for score, label, box in zip(result["scores"], result["labels"], result["boxes"]):
...     box = [round(i, 2) for i in box.tolist()]
...     print(
...         f"Detected {model.config.id2label[label.item()]} with confidence "
...         f"{round(score.item(), 3)} at location {box}"
...     )
Detected cat with confidence 0.958 at location [344.49, 23.4, 639.84, 374.27]
Detected cat with confidence 0.956 at location [11.71, 53.52, 316.64, 472.33]
Detected remote with confidence 0.947 at location [40.46, 73.7, 175.62, 117.57]
Detected sofa with confidence 0.918 at location [0.59, 1.88, 640.25, 474.74]
Update on GitHub