# RT-DETRv2

## 개요

RT-DETRv2 모델은 Wenyu Lv, Yian Zhao, Qinyao Chang, Kui Huang, Guanzhong Wang, Yi Liu가 [RT-DETRv2: Improved Baseline with Bag-of-Freebies for Real-Time Detection Transformer](https://huggingface.co/papers/2407.17140)에서 제안했습니다.

RT-DETRv2는 선택적 다중 스케일 특징 추출, 더 넓은 배포 호환성을 위한 이산 샘플링 연산자, 동적 데이터 증강 및 스케일 적응형 하이퍼파라미터와 같은 개선된 학습 전략을 도입하여 RT-DETR을 정교화했습니다. 이러한 변경 사항은 실시간 성능을 유지하면서 유연성과 실용성을 향상시킵니다.

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

*본 보고서에서는 개선된 실시간 객체 탐지 트랜스포머(Real-Time DEtection TRansformer, RT-DETR)인 RT-DETRv2를 소개합니다. RT-DETRv2는 이전의 최첨단 실시간 탐지 모델인 RT-DETR을 기반으로 하며, 유연성과 실용성을 높이기 위한 일련의 무상 개선 사항(bag-of-freebies)을 도입하고, 성능 향상을 위해 학습 전략을 최적화했습니다. 유연성을 높이기 위해, 변형 가능한 주의(deformable attention)에서 서로 다른 스케일의 특징에 대해 서로 다른 수의 샘플링 지점을 설정하여 디코더가 선택적 다중 스케일 특징 추출을 수행하도록 제안합니다. 실용성을 높이기 위해, YOLOs와 비교할 때 RT-DETR에 특화된 grid_sample 연산자를 대체하는 선택적 이산 샘플링 연산자를 제안합니다. 이를 통해 DETR과 일반적으로 연관된 배포 제약 사항을 제거합니다. 학습 전략에 대해서는, 속도 저하 없이 성능을 향상시키기 위해 동적 데이터 증강과 스케일 적응형 하이퍼파라미터 커스터마이징을 제안합니다.*

이 모델은 [jadechoghari](https://huggingface.co/jadechoghari)님이 기여했습니다. 원본 코드는 [여기](https://github.com/lyuwenyu/RT-DETR)에서 찾을 수 있습니다.

## 사용 팁

RT-DETR의 이 두 번째 버전은 디코더가 이미지에서 객체를 찾는 방식을 개선합니다.

- **더 나은 샘플링** – 오프셋을 조정하여 모델이 올바른 영역을 참조하도록 합니다
- **유연한 어텐션** – 매끄러운(이차) 또는 고정(이산) 샘플링을 사용할 수 있습니다
- **최적화된 처리** – 어텐션 가중치가 정보를 혼합하는 방식을 개선합니다

ImageProcessor와 함께 640x640 크기로 리사이즈된 이미지에 모델을 사용하는 것이 의도된 사용법입니다. 다른 크기로 리사이즈하면 일반적으로 성능이 저하됩니다.

```python
import requests
import torch
from PIL import Image

from transformers import RTDetrImageProcessor, RTDetrV2ForObjectDetection

url = 'http://images.cocodataset.org/val2017/000000039769.jpg'
image = Image.open(requests.get(url, stream=True).raw)

image_processor = RTDetrImageProcessor.from_pretrained("PekingU/rtdetr_v2_r18vd")
model = RTDetrV2ForObjectDetection.from_pretrained("PekingU/rtdetr_v2_r18vd", 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=torch.tensor([(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.97 [341.14, 25.11, 639.98, 372.89]
cat: 0.96 [12.78, 56.35, 317.67, 471.34]
remote: 0.95 [39.96, 73.12, 175.65, 117.44]
sofa: 0.86 [-0.11, 2.97, 639.89, 473.62]
sofa: 0.82 [-0.12, 1.78, 639.87, 473.52]
remote: 0.79 [333.65, 76.38, 370.69, 187.48]
```

## 리소스

RT-DETRv2를 시작하는 데 도움이 되는 공식 Hugging Face 및 커뮤니티(🌎로 표시) 리소스 목록입니다.

- 참고: [객체 감지 작업 가이드](../tasks/object_detection).
- [추론](https://github.com/qubvel/transformers-notebooks/blob/main/notebooks/RT_DETR_v2_inference.ipynb) 및 [파인튜닝](https://github.com/qubvel/transformers-notebooks/blob/main/notebooks/RT_DETR_v2_finetune_on_a_custom_dataset.ipynb)을 위해 커스텀 데이터셋에서 RT-DETRv2를 사용하는 노트북 (🌎).

## RTDetrV2Config[[transformers.RTDetrV2Config]]

#### transformers.RTDetrV2Config[[transformers.RTDetrV2Config]]

```python
transformers.RTDetrV2Config(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 = 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, eos_coefficient: float = 0.0001, decoder_n_levels: int = 3, decoder_offset_scale: float = 0.5, decoder_method: str = 'default', tie_word_embeddings: bool = True)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rt_detr_v2/configuration_rt_detr_v2.py#L29)

**매개변수:**

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"`, `"gelu_new"`가 지원됩니다.

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 손실의 상대적 가중치.

eos_coefficient (`float`, *선택 사항*, 기본값 `0.0001`) : 객체 감지 손실에서 'no-object' 클래스의 상대 분류 가중치입니다.

decoder_n_levels (`int`, *선택 사항*, 기본값 3) : 디코더가 사용하는 특징 레벨의 수입니다.

decoder_offset_scale (`float`, *선택 사항*, 기본값 0.5) : 디코더의 어텐션 오프셋에 적용되는 스케일링 계수입니다.

decoder_method (`str`, *선택 사항*, 기본값 `"default"`) : 디코더에 사용할 방법: `"default"` 또는 `"discrete"`.

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

이것은 RTDetrV2Model의 구성을 저장하기 위한 구성 클래스입니다. 지정된 인자에 따라 Rt Detr V2 모델을 인스턴스화하여 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 구성을 인스턴스화하면 [PekingU/rtdetr_r18vd](https://huggingface.co/PekingU/rtdetr_r18vd)와 유사한 구성이 생성됩니다.

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

예:

```python
>>> from transformers import RTDetrV2Config, RTDetrV2Model

>>> # Initializing a RT-DETR configuration
>>> configuration = RTDetrV2Config()

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

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

## RTDetrV2Model[[transformers.RTDetrV2Model]]

#### transformers.RTDetrV2Model[[transformers.RTDetrV2Model]]

```python
transformers.RTDetrV2Model(config: RTDetrV2Config)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rt_detr_v2/modeling_rt_detr_v2.py#L1343)

**매개변수:**

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

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

이 모델은 [PreTrainedModel](/docs/transformers/main/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.RTDetrV2Model.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/main/src/transformers/models/rt_detr_v2/modeling_rt_detr_v2.py#L1462)

**매개변수:**

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`여야 합니다.

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

`None` 및 입력에 따라 구성이 달라지는 여러 요소로 구성된 `RTDetrV2ModelOutput` 또는 `torch.Tensor`의 튜플(`return_dict=False`가 전달되거나 `config.return_dict=False`인 경우).

[RTDetrV2Model](/docs/transformers/main/ko/model_doc/rt_detr_v2#transformers.RTDetrV2Model)의 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, RTDetrV2Model
>>> 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/RTDetrV2_r50vd")
>>> model = RTDetrV2Model.from_pretrained("PekingU/RTDetrV2_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]
```

## RTDetrV2ForObjectDetection[[transformers.RTDetrV2ForObjectDetection]]

#### transformers.RTDetrV2ForObjectDetection[[transformers.RTDetrV2ForObjectDetection]]

```python
transformers.RTDetrV2ForObjectDetection(config: RTDetrV2Config)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rt_detr_v2/modeling_rt_detr_v2.py#L1765)

**매개변수:**

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

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

이 모델은 [PreTrainedModel](/docs/transformers/main/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.RTDetrV2ForObjectDetection.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/main/src/transformers/models/rt_detr_v2/modeling_rt_detr_v2.py#L1798)

**매개변수:**

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`여야 합니다.

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

`None` 및 입력에 따라 구성이 달라지는 여러 요소로 구성된 `RTDetrV2ObjectDetectionOutput` 또는 `torch.Tensor`의 튜플(`return_dict=False`가 전달되거나 `config.return_dict=False`인 경우).

[RTDetrV2ForObjectDetection](/docs/transformers/main/ko/model_doc/rt_detr_v2#transformers.RTDetrV2ForObjectDetection)의 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`, shape `(batch_size, num_queries, 4)`) -- 모든 쿼리에 대한 정규화된 박스 좌표로, (center_x, center_y, width, height)로 표현됩니다. 이 값들은 배치 내 각 개별 이미지의 크기에 대해 [0, 1] 범위로 정규화되어 있습니다(가능한 패딩은 무시). `~RTDetrV2ImageProcessor.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
>>> from transformers import RTDetrV2ImageProcessor, RTDetrV2ForObjectDetection
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> import torch

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

>>> image_processor = RTDetrV2ImageProcessor.from_pretrained("PekingU/RTDetrV2_r50vd")
>>> model = RTDetrV2ForObjectDetection.from_pretrained("PekingU/RTDetrV2_r50vd")

>>> # 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)[
...     0
... ]

>>> for score, label, box in zip(results["scores"], results["labels"], results["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 sofa with confidence 0.97 at location [0.14, 0.38, 640.13, 476.21]
Detected cat with confidence 0.96 at location [343.38, 24.28, 640.14, 371.5]
Detected cat with confidence 0.958 at location [13.23, 54.18, 318.98, 472.22]
Detected remote with confidence 0.951 at location [40.11, 73.44, 175.96, 118.48]
Detected remote with confidence 0.924 at location [333.73, 76.58, 369.97, 186.99]
```

