# 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](https://huggingface.co/papers/2410.13842)에서 제안했습니다.

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

*DETer 모델에서 바운딩 박스 회귀 작업을 재정의하여 뛰어난 로컬라이제이션 정밀도를 달성하는 강력한 실시간 객체 탐지기 D-FINE을 소개합니다. D-FINE은 두 가지 핵심 구성 요소인 Fine-grained Distribution Refinement(FDR)과 Global Optimal Localization Self-Distillation(GO-LSD)으로 구성됩니다. FDR은 회귀 과정을 고정된 좌표 예측에서 확률 분포의 반복적 정제로 변환하여, 로컬라이제이션 정확도를 크게 향상시키는 세밀한 중간 표현을 제공합니다. GO-LSD는 자기 증류를 통해 정제된 분포에서 더 얕은 레이어로 로컬라이제이션 지식을 전달하는 양방향 최적화 전략으로, 동시에 더 깊은 레이어의 잔차 예측 작업을 단순화합니다. 또한 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](https://github.com/VladOS95-cyber)님이 기여했습니다. 원본 코드는 [여기](https://github.com/Peterande/D-FINE)에서 찾을 수 있습니다.

## 사용 팁

```python
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[[transformers.DFineConfig]]

#### transformers.DFineConfig[[transformers.DFineConfig]]

```python
transformers.DFineConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, is_encoder_decoder: bool = True, initializer_range: float = 0.01, initializer_bias_prior_prob: float | None = None, layer_norm_eps: float = 1e-05, batch_norm_eps: float = 1e-05, backbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, freeze_backbone_batch_norms: bool = True, encoder_hidden_dim: int = 256, encoder_in_channels: list[int] | tuple[int, ...] = (512, 1024, 2048), feat_strides: list[int] | tuple[int, ...] = (8, 16, 32), encoder_layers: int = 1, encoder_ffn_dim: int = 1024, encoder_attention_heads: int = 8, dropout: float | int = 0.0, activation_dropout: float | int = 0.0, encode_proj_layers: list[int] | tuple[int, ...] = (2,), positional_encoding_temperature: int = 10000, encoder_activation_function: str = 'gelu', activation_function: str = 'silu', eval_size: int | None = None, normalize_before: bool = False, hidden_expansion: float = 1.0, d_model: int = 256, num_queries: int = 300, decoder_in_channels: list[int] | tuple[int, ...] = (256, 256, 256), decoder_ffn_dim: int = 1024, num_feature_levels: int = 3, decoder_n_points: int | list[int] = 4, decoder_layers: int = 6, decoder_attention_heads: int = 8, decoder_activation_function: str = 'relu', attention_dropout: float | int = 0.0, num_denoising: int = 100, label_noise_ratio: float = 0.5, box_noise_scale: float = 1.0, learn_initial_query: bool = False, anchor_image_size: int | list[int] | None = None, with_box_refine: bool = True, matcher_alpha: float = 0.25, matcher_gamma: float = 2.0, matcher_class_cost: float = 2.0, matcher_bbox_cost: float = 5.0, matcher_giou_cost: float = 2.0, use_focal_loss: bool = True, auxiliary_loss: bool = True, focal_loss_alpha: float = 0.75, focal_loss_gamma: float = 2.0, weight_loss_vfl: float = 1.0, weight_loss_bbox: float = 5.0, weight_loss_giou: float = 2.0, weight_loss_fgl: float = 0.15, weight_loss_ddf: float = 1.5, eos_coefficient: float = 0.0001, eval_idx: int = -1, layer_scale: int | float = 1.0, max_num_bins: int = 32, reg_scale: float = 4.0, depth_mult: float = 1.0, top_prob_values: int = 4, lqe_hidden_dim: int = 64, lqe_layers: int = 2, decoder_offset_scale: float = 0.5, decoder_method: str = 'default', up: float = 0.5, tie_word_embeddings: bool = True)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/d_fine/configuration_d_fine.py#L31)

**매개변수:**

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`) : layer normalization 레이어에서 사용되는 epsilon 값입니다.

batch_norm_eps (`float`, *선택 사항*, 기본값 `1e-05`) : 배치 정규화 레이어에서 사용되는 epsilon 값입니다.

backbone_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`, *선택*) : 백본 모델의 구성입니다.

freeze_backbone_batch_norms (`bool`, *선택 사항*, 기본값 `True`) : 백본의 배치 정규화 레이어를 고정할지 여부.

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]`, *선택 사항*) : 스트라이드를 고려한 후 위치 임베딩의 유효 높이를 계산하는 데 사용되는 높이와 너비.

normalize_before (`bool`, *선택 사항*, 기본값 `False`) : transformer 인코더 레이어에서 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`) : 디코더의 "중간"(일반적으로 feed-forward라고도 함) 레이어의 차원.

num_feature_levels (`int`, *선택 사항*, 기본값 3) : 입력 특징 레벨의 수입니다.

decoder_n_points (`int`, *선택 사항*, 기본값 4) : 디코더의 각 어텐션 헤드에서 각 특징 레벨당 샘플링된 키의 수입니다.

decoder_layers (`int`, *선택 사항*, 기본값 `6`) : Transformer decoder의 숨겨진 레이어 수입니다. 설정하지 않으면 `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 정제(iterative 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) : 가중치 함수의 상한을 제어합니다.

tie_word_embeddings (`bool`, *선택 사항*, 기본값 `True`) : 모델의 `tied_weights_keys` 매핑에 따라 가중치 임베딩을 묶을지 여부.

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

Configuration 객체는 [PreTrainedConfig](/docs/transformers/v5.23.0/ko/main_classes/configuration#transformers.PreTrainedConfig)를 상속하며, 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 [PreTrainedConfig](/docs/transformers/v5.23.0/ko/main_classes/configuration#transformers.PreTrainedConfig)의 문서를 참고하세요.

## DFineModel[[transformers.DFineModel]]

#### transformers.DFineModel[[transformers.DFineModel]]

```python
transformers.DFineModel(config: DFineConfig)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/d_fine/modeling_d_fine.py#L1540)

**매개변수:**

config ([DFineConfig](/docs/transformers/v5.23.0/ko/model_doc/d_fine#transformers.DFineConfig)) : 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 [from_pretrained()](/docs/transformers/v5.23.0/ko/main_classes/model#transformers.PreTrainedModel.from_pretrained) 메서드를 확인하세요.

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

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

이 모델은 또한 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법과 동작에 관한 모든 사항은 PyTorch 문서를 참조하세요.

#### forward[[transformers.DFineModel.forward]]

```python
forward(pixel_values: Tensor, pixel_mask: typing.Optional[torch.LongTensor] = None, encoder_outputs: typing.Optional[torch.Tensor] = None, inputs_embeds: typing.Optional[torch.Tensor] = None, labels: list[dict] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/d_fine/modeling_d_fine.py#L1666)

**매개변수:**

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`, shape `(batch_size, height, width)`, *선택 사항*) : 패딩 픽셀 값에 대한 attention을 수행하지 않도록 하는 마스크. `[0, 1]`에서 선택된 마스크 값: - 실제 픽셀(즉, **마스크되지 않은** 픽셀)은 1, - 패딩 픽셀(즉, **마스크된** 픽셀)은 0. [attention 마스크란?](../glossary#attention-mask)

encoder_outputs (`torch.Tensor`, *선택 사항*) : (`last_hidden_state`, *선택 사항*: `hidden_states`, *선택 사항*: `attentions`) `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)`, *선택 사항*) : backbone + projection layer의 출력인 flattened feature map을 전달하는 대신, 이미지의 flattened representation을 직접 전달할 수 있습니다.

labels (`list[Dict]` of len `(batch_size,)`, *optional*) : 이분 매칭 손실을 계산하기 위한 라벨. 딕셔너리의 목록으로, 각 딕셔너리는 최소한 다음 2개의 키를 포함해야 합니다: 'class_labels'와 'boxes' (배치 내 이미지의 클래스 라벨과 바운딩 박스). 클래스 라벨 자체는 len이 `(number of bounding boxes in the image,)`인 `torch.LongTensor`여야 하고, boxes는 shape이 `(number of bounding boxes in the image, 4)`인 `torch.Tensor`여야 합니다.

**반환값:** `DFineModelOutput` 또는 `tuple(torch.Tensor)`

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

[DFineModel](/docs/transformers/v5.23.0/ko/model_doc/d_fine#transformers.DFineModel)의 forward 메서드는 `__call__` 특수 메서드를 오버라이드합니다.

`Module` 인스턴스는 전처리 및 후처리 단계를 실행하는 것을 처리하지만, 이 함수는 해당 단계를 조용히 무시하므로, 순전파(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의 각 레이어의 reference point를 스택한 중간 reference point
- **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`인 경우 반환) -- shape가 `(batch_size, sequence_length, hidden_size)`인 `torch.Tensor`의 튜플 (모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개).

  각 레이어의 출력에서 디코더의 Hidden-states와 초기 임베딩 출력을 더한 값.
- **decoder_attentions** (`tuple[torch.Tensor]`, *선택 사항*, `output_attentions=True`가 전달되거나 `config.output_attentions=True`인 경우 반환) -- 각 레이어에 하나씩, shape가 `(batch_size, num_heads, sequence_length, sequence_length)`인 `torch.Tensor` 튜플.

  self-attention 헤드에서 가중 평균을 계산하는 데 사용되는, attention softmax 이후의 decoder의 attention 가중치입니다.
- **cross_attentions** (`tuple[torch.Tensor]`, *선택*, `output_attentions=True`가 전달되거나 `config.output_attentions=True`일 때 반환) -- 각 레이어마다 하나씩 포함된 `torch.Tensor`의 튜플로, shape는 `(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개)로, shape가 `(batch_size, sequence_length, hidden_size)`입니다.

  각 레이어의 출력에서 인코더의 Hidden-states와 초기 임베딩 출력을 더한 값.
- **encoder_attentions** (`tuple[torch.Tensor]`, *선택*, `output_attentions=True`가 전달되었거나 `config.output_attentions=True`인 경우 반환) -- 각 레이어에 하나씩 포함된 `torch.Tensor` 튜플이며, shape은 `(batch_size, num_heads, sequence_length, sequence_length)`입니다.

  인코더의 어텐션 가중치입니다. 어텐션 softmax 이후에 self-attention 헤드에서 가중 평균을 계산하는 데 사용됩니다.
- **init_reference_points** (shape가 `(batch_size, num_queries, 4)`인 `torch.Tensor`) -- Transformer decoder를 통해 전달되는 초기 참조점.
- **enc_topk_logits** (`torch.Tensor`, shape `(batch_size, sequence_length, config.num_labels)`) -- 인코더 단계에서 상위 `config.two_stage_num_proposals` 점수를 가진 바운딩 박스가 리전 제안으로 선택되는 예측된 바운딩 박스 점수입니다. 바운딩 박스 이진 분류(즉, 포그라운드와 배경)의 출력입니다.
- **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`일 때 반환) -- 첫 번째 단계에서 예측된 바운딩 박스 좌표의 logits.
- **denoising_meta_values** (`dict`, *선택 사항*) -- 노이즈 제거 관련 값에 대한 추가 사전입니다.

예:

```python
>>> 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]]

#### transformers.DFineForObjectDetection[[transformers.DFineForObjectDetection]]

```python
transformers.DFineForObjectDetection(config: DFineConfig)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/d_fine/modeling_d_fine.py#L1950)

**매개변수:**

config ([DFineConfig](/docs/transformers/v5.23.0/ko/model_doc/d_fine#transformers.DFineConfig)) : 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 [from_pretrained()](/docs/transformers/v5.23.0/ko/main_classes/model#transformers.PreTrainedModel.from_pretrained) 메서드를 확인하세요.

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

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

이 모델은 또한 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법과 동작에 관한 모든 사항은 PyTorch 문서를 참조하세요.

#### forward[[transformers.DFineForObjectDetection.forward]]

```python
forward(pixel_values: Tensor, pixel_mask: typing.Optional[torch.LongTensor] = None, encoder_outputs: typing.Optional[torch.Tensor] = None, inputs_embeds: typing.Optional[torch.Tensor] = None, labels: list[dict] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/d_fine/modeling_d_fine.py#L1989)

**매개변수:**

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`, shape `(batch_size, height, width)`, *선택 사항*) : 패딩 픽셀 값에 대한 attention을 수행하지 않도록 하는 마스크. `[0, 1]`에서 선택된 마스크 값: - 실제 픽셀(즉, **마스크되지 않은** 픽셀)은 1, - 패딩 픽셀(즉, **마스크된** 픽셀)은 0. [attention 마스크란?](../glossary#attention-mask)

encoder_outputs (`torch.Tensor`, *선택 사항*) : (`last_hidden_state`, *선택 사항*: `hidden_states`, *선택 사항*: `attentions`) `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]` of len `(batch_size,)`, *optional*) : 이분 매칭 손실을 계산하기 위한 라벨. 딕셔너리의 목록으로, 각 딕셔너리는 최소한 다음 2개의 키를 포함해야 합니다: 'class_labels'와 'boxes' (배치 내 이미지의 클래스 라벨과 바운딩 박스). 클래스 라벨 자체는 len이 `(number of bounding boxes in the image,)`인 `torch.LongTensor`여야 하고, boxes는 shape이 `(number of bounding boxes in the image, 4)`인 `torch.Tensor`여야 합니다.

**반환값:** `DFineObjectDetectionOutput` 또는 `tuple(torch.Tensor)`

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

[DFineForObjectDetection](/docs/transformers/v5.23.0/ko/model_doc/d_fine#transformers.DFineForObjectDetection)의 forward 메서드는 `__call__` 특수 메서드를 오버라이드합니다.

`Module` 인스턴스는 전처리 및 후처리 단계를 실행하는 것을 처리하지만, 이 함수는 해당 단계를 조용히 무시하므로, 순전파(forward pass) 레시피를 이 함수 내에서 정의해야 하더라도 이후에는 이 함수 대신 `Module` 인스턴스를 호출해야 합니다.

- **loss** (`torch.Tensor`, 형상 `(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` of 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의 각 레이어의 reference point를 스택한 중간 reference point
- **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`인 경우 반환) -- shape가 `(batch_size, sequence_length, hidden_size)`인 `torch.Tensor`의 튜플 (모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개).

  각 레이어의 출력에서 디코더의 Hidden-states와 초기 임베딩 출력을 더한 값.
- **decoder_attentions** (`tuple[torch.Tensor]`, *선택 사항*, `output_attentions=True`가 전달되거나 `config.output_attentions=True`인 경우 반환) -- 각 레이어에 하나씩, shape가 `(batch_size, num_heads, sequence_length, sequence_length)`인 `torch.Tensor` 튜플.

  self-attention 헤드에서 가중 평균을 계산하는 데 사용되는, attention softmax 이후의 decoder의 attention 가중치입니다.
- **cross_attentions** (`tuple[torch.Tensor]`, *선택*, `output_attentions=True`가 전달되거나 `config.output_attentions=True`일 때 반환) -- 각 레이어마다 하나씩 포함된 `torch.Tensor`의 튜플로, shape는 `(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개)로, shape가 `(batch_size, sequence_length, hidden_size)`입니다.

  각 레이어의 출력에서 인코더의 Hidden-states와 초기 임베딩 출력을 더한 값.
- **encoder_attentions** (`tuple[torch.Tensor]`, *선택*, `output_attentions=True`가 전달되었거나 `config.output_attentions=True`인 경우 반환) -- 각 레이어에 하나씩 포함된 `torch.Tensor` 튜플이며, shape은 `(batch_size, num_heads, sequence_length, sequence_length)`입니다.

  인코더의 어텐션 가중치입니다. 어텐션 softmax 이후에 self-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`일 때 반환됨) -- 인코더에서 예측된 바운딩 박스 좌표의 로짓입니다.
- **enc_topk_bboxes** (`torch.Tensor`, shape `(batch_size, sequence_length, 4)`, *선택 사항*, `config.with_box_refine=True`이고 `config.two_stage=True`일 때 반환됨) -- 인코더에서 예측된 바운딩 박스 좌표의 로짓.
- **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`일 때 반환) -- 첫 번째 단계에서 예측된 바운딩 박스 좌표의 logits.
- **denoising_meta_values** (`dict`, *선택 사항*) -- 디노이징 관련 값에 대한 추가 사전

예:

```python
>>> 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]
```

