# Registers를 사용한 DINOv2

## 개요

Timothée Darcet, Maxime Oquab, Julien Mairal, Piotr Bojanowski의 [Vision Transformers Need Registers](https://huggingface.co/papers/2309.16588) 논문에서 DINOv2 with Registers 모델이 제안되었습니다.

[Vision Transformer](vit)(ViT)은 ImageNet에서 지도 기반 이미지 분류를 수행하기 위해 처음 소개된 transformer 인코더 모델(BERT와 유사)입니다.

다음으로, ViT가 레이블 없이 이미지에서 의미 있는 특징(또는 임베딩이라고도 함)을 추출하는 자감독 학습(self-supervised) 방식으로 매우 잘 작동하는 방법이 발견되었습니다. 관련 논문으로는 [DINOv2](dinov2)와 [MAE](vit_mae)가 있습니다.

DINOv2의 저자들은 ViT의 어텐션 맵에 아티팩트가 존재하는 것을 발견했습니다. 이는 모델이 일부 이미지 패치를 “레지스터”로 사용하기 때문입니다. 저자들은 이에 대한 해결책을 제안합니다. 바로 새로운 토큰(“레지스터” 토큰이라고 함)을 추가하되, 이는 사전 학습 단계에서만 사용하고 이후에는 폐기하는 것입니다. 이를 통해 다음과 같은 결과가 나옵니다:

- 아티팩트 없음
- 해석 가능한 어텐션 맵
- 그리고 향상된 성능.

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

*최근 Transformers는 시각 표현을 학습하는 강력한 도구로 부상했습니다. 본 논문에서는 지도 학습 및 자기 지도 학습 ViT 네트워크의 특징 맵에 존재하는 아티팩트를 식별하고 특성화합니다. 해당 아티팩트는 추론 과정에서 주로 이미지의 정보량이 낮은 배경 영역에 나타나는 고노름 토큰으로, 내부 계산에 재사용됩니다. 우리는 Vision Transformer의 입력 시퀀스에 추가 토큰을 제공하여 해당 역할을 수행하게 하는 단순하면서도 효과적인 해결책을 제안합니다. 이 해결책이 지도 학습 및 자기 지도 학습 모델 모두에서 해당 문제를 완전히 해결하고, 밀집 시각 예측 작업에서 자기 지도 학습 시각 모델의 새로운 최첨단 성능을 달성하며, 더 큰 모델을 활용한 객체 발견 방법을 가능하게 하고, 무엇보다도 하위 시각 처리를 위한 더 매끄러운 특징 맵과 어텐션 맵을 제공한다는 것을 보여줍니다.*

<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/dinov2_with_registers_visualization.png"
alt="drawing" width="600"/>

 registers를 사용하여 학습한 모델과 사용하지 않은 모델의 어텐션 맵 시각화. 원 논문에서 가져옴.

팁:

- Registers를 사용한 DINOv2의 사용법은 Registers를 사용하지 않는 경우와 동일하며, 더 나은 성능만 얻을 수 있습니다.

이 모델은 [nielsr](https://huggingface.co/nielsr)에 의해 기여되었습니다. 원본 코드는 [여기](https://github.com/facebookresearch/dinov2)에서 찾을 수 있습니다.

## Dinov2WithRegistersConfig[[transformers.Dinov2WithRegistersConfig]]

#### transformers.Dinov2WithRegistersConfig[[transformers.Dinov2WithRegistersConfig]]

```python
transformers.Dinov2WithRegistersConfig(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, is_encoder_decoder: bool = False, 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, hidden_size: int = 768, num_hidden_layers: int = 12, num_attention_heads: int = 12, mlp_ratio: int = 4, hidden_act: str = 'gelu', hidden_dropout_prob: float | int = 0.0, attention_probs_dropout_prob: float | int = 0.0, initializer_range: float = 0.02, layer_norm_eps: float = 1e-06, image_size: int | list[int] | tuple[int, int] = 224, patch_size: int | list[int] | tuple[int, int] = 16, num_channels: int = 3, qkv_bias: bool = True, layerscale_value: float = 1.0, drop_path_rate: float | int = 0.0, use_swiglu_ffn: bool = False, num_register_tokens: int = 4, _out_features: list[str] | None = None, _out_indices: list[int] | None = None, apply_layernorm: bool = True, reshape_hidden_states: bool = True)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/dinov2_with_registers/configuration_dinov2_with_registers.py#L32)

**매개변수:**

hidden_size (`int`, *선택 사항*, 기본값 `768`) : 숨겨진 표현의 차원.

num_hidden_layers (`int`, *선택 사항*, 기본값 `12`) : Transformer decoder의 숨겨진 레이어 수입니다.

num_attention_heads (`int`, *선택 사항*, 기본값 `12`) : Transformer decoder의 각 attention layer에 사용되는 attention head의 수입니다.

mlp_ratio (`int`, *선택 사항*, 기본값 `4`) : MLP 숨겨진 차원과 임베딩 차원의 비율입니다.

hidden_act (`str`, *선택 사항*, 기본값 `gelu`) : 디코더에서 사용되는 비선형 활성화 함수(함수 또는 문자열). 예를 들어, `"gelu"`, `"relu"`, `"silu"` 등이 있습니다.

hidden_dropout_prob (`Union[float, int]`, *선택 사항*, 기본값 `0.0`) : 임베딩, 인코더, 풀러의 모든 완전 연결 계층에 적용되는 dropout 확률입니다.

attention_probs_dropout_prob (`Union[float, int]`, *선택 사항*, 기본값 `0.0`) : attention 확률에 적용할 dropout 비율입니다.

initializer_range (`float`, *선택 사항*, 기본값 `0.02`) : 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다.

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

image_size (`Union[int, list[int], tuple[int, int]]`, *선택*, 기본값 `224`) : 각 이미지의 크기(해상도).

patch_size (`Union[int, list[int], tuple[int, int]]`, *선택*, 기본값 `16`) : 각 패치의 크기(해상도).

num_channels (`int`, *선택 사항*, 기본값 `3`) : 입력 채널의 수입니다.

qkv_bias (`bool`, *선택 사항*, 기본값 `True`) : 쿼리, 키, 값에 bias를 추가할지 여부.

layerscale_value (`float`, *선택 사항*, 기본값 1.0) : layer scale에 사용할 초기 값입니다.

drop_path_rate (`Union[float, int]`, *선택 사항*, 기본값 `0.0`) : 패치 퓨전용 드롭 패스 비율입니다.

use_swiglu_ffn (`bool`, *선택 사항*, 기본값 `False`) : SwiGLU 피드포워드 신경망을 사용할지 여부.

num_register_tokens (`int`, *선택 사항*, 기본값 4) : 사용할 레지스터 토큰의 수.

apply_layernorm (`bool`, *선택 사항*, 기본값 `True`) : 모델이 백본으로 사용될 경우, 피처 맵에 레이어 정규화를 적용할지 여부입니다.

reshape_hidden_states (`bool`, *선택 사항*, 기본값 `True`) : 모델이 백본으로 사용될 경우, feature maps를 `(batch_size, hidden_size, height, width)` 형태의 4D 텐서로 reshape할지 여부입니다. `False`인 경우, feature maps는 `(batch_size, seq_len, hidden_size)` 형태의 3D 텐서가 됩니다.

This is the configuration class to store the configuration of a Dinov2WithRegistersModel. It is used to instantiate a Dinov2 With Registers model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the [facebook/dinov2-with-registers-base](https://huggingface.co/facebook/dinov2-with-registers-base)

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 Dinov2WithRegistersConfig, Dinov2WithRegistersModel

>>> # Initializing a Dinov2WithRegisters base style configuration
>>> configuration = Dinov2WithRegistersConfig()

>>> # Initializing a model (with random weights) from the base style configuration
>>> model = Dinov2WithRegistersModel(configuration)

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

## Dinov2WithRegistersModel[[transformers.Dinov2WithRegistersModel]]

#### transformers.Dinov2WithRegistersModel[[transformers.Dinov2WithRegistersModel]]

```python
transformers.Dinov2WithRegistersModel(config: Dinov2WithRegistersConfig)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/dinov2_with_registers/modeling_dinov2_with_registers.py#L393)

**매개변수:**

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

특정 헤드가 위에 없는 상태에서 원시 hidden-states를 출력하는 순수한 Dinov2 With Registers Model입니다.

이 모델은 [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.Dinov2WithRegistersModel.forward]]

```python
forward(pixel_values: typing.Optional[torch.Tensor] = None, bool_masked_pos: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/dinov2_with_registers/modeling_dinov2_with_registers.py#L402)

**매개변수:**

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`를 사용합니다).

bool_masked_pos (`torch.BoolTensor`, shape `(batch_size, sequence_length)`) : Boolean masked positions. 어떤 patch가 mask되어 있는지(1) 아니면 그렇지 않은지(0)를 나타냅니다. 사전 학습에만 관련이 있습니다.

attention_mask (`torch.Tensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크입니다. `[0, 1]`에서 선택된 마스크 값: - **마스크되지 않은** 토큰은 1, - **마스크된** 토큰은 0. [attention 마스크란?](../glossary#attention-mask)

**반환값:** [BaseModelOutputWithPooling](/docs/transformers/main/ko/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 또는 `tuple(torch.Tensor)`

[BaseModelOutputWithPooling](/docs/transformers/main/ko/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 또는 `torch.Tensor`의 튜플(`return_dict=False`가 전달되었거나 `config.return_dict=False`인 경우)로, 구성([Dinov2WithRegistersConfig](/docs/transformers/main/ko/model_doc/dinov2_with_registers#transformers.Dinov2WithRegistersConfig))과 입력에 따라 다양한 요소를 포함합니다.

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

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

- **last_hidden_state** (`torch.Tensor`, shape `(batch_size, sequence_length, hidden_size)`) -- 모델의 마지막 레이어 출력에서 생성된 hidden-state 시퀀스입니다.
- **pooler_output** (`torch.Tensor`, shape `(batch_size, hidden_size)`) -- 시퀀스의 첫 번째 토큰(분류 토큰)의 마지막 레이어 hidden-state입니다. 보조 사전학습 작업을 위해 사용되는 레이어들을 통해 추가 처리된 값입니다. 예를 들어 BERT 계열 모델의 경우, 선형 레이어와 tanh 활성화 함수를 통해 처리된 분류 토큰을 반환합니다. 선형 레이어의 가중치는 사전학습 단계에서 다음 문장 예측(분류) 목적 함수를 통해 학습됩니다.
- **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와 선택적 초기 임베딩 출력을 포함합니다.
- **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 가중치입니다.

예:

```python
```

## Dinov2WithRegistersForImageClassification[[transformers.Dinov2WithRegistersForImageClassification]]

#### transformers.Dinov2WithRegistersForImageClassification[[transformers.Dinov2WithRegistersForImageClassification]]

```python
transformers.Dinov2WithRegistersForImageClassification(config: Dinov2WithRegistersConfig)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/dinov2_with_registers/modeling_dinov2_with_registers.py#L439)

**매개변수:**

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

Dinov2WithRegisters 모델은 [CLS] 토큰의 최종 숨겨진 상태 위에 선형 레이어를 올린 이미지 분류 헤드를 갖춘 transformer입니다. 예를 들어 ImageNet에 사용됩니다.

이 모델은 [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.Dinov2WithRegistersForImageClassification.forward]]

```python
forward(pixel_values: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/dinov2_with_registers/modeling_dinov2_with_registers.py#L452)

**매개변수:**

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`를 사용합니다).

labels (`torch.LongTensor`, shape `(batch_size,)`, *선택 사항*) : 이미지 분류/회귀 손실을 계산하는 데 사용되는 라벨. 인덱스는 `[0, ..., config.num_labels - 1]` 범위에 있어야 합니다. `config.num_labels == 1`인 경우 회귀 손실(평균 제곱 손실)이 계산되고, `config.num_labels > 1`인 경우 분류 손실(크로스 엔트로피)이 계산됩니다.

attention_mask (`torch.Tensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크입니다. `[0, 1]`에서 선택된 마스크 값: - **마스크되지 않은** 토큰은 1, - **마스크된** 토큰은 0. [attention 마스크란?](../glossary#attention-mask)

**반환값:** [ImageClassifierOutput](/docs/transformers/main/ko/main_classes/output#transformers.modeling_outputs.ImageClassifierOutput) 또는 `tuple(torch.Tensor)`

[ImageClassifierOutput](/docs/transformers/main/ko/main_classes/output#transformers.modeling_outputs.ImageClassifierOutput) 또는 `torch.Tensor` 튜플(`return_dict=False`가 전달되었거나 `config.return_dict=False`인 경우)로, 구성([Dinov2WithRegistersConfig](/docs/transformers/main/ko/model_doc/dinov2_with_registers#transformers.Dinov2WithRegistersConfig)) 및 입력에 따라 다양한 요소를 포함합니다.

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

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

- **loss** (`torch.Tensor`, shape `(1,)`, *선택*, `labels`이 제공될 때 반환됨) -- 분류(또는 config.num_labels==1인 경우 회귀) 손실.
- **logits** (`torch.Tensor`, shape `(batch_size, config.num_labels)`) -- SoftMax 적용 전 분류(또는 config.num_labels==1인 경우 회귀) 점수.
- **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(또는 feature maps)입니다.
- **attentions** (`tuple(torch.Tensor)`, *선택 사항*, `output_attentions=True`가 전달되었거나 `config.output_attentions=True`인 경우 반환) -- 각 레이어당 하나씩, shape가 `(batch_size, num_heads, patch_size, sequence_length)`인 `torch.Tensor`의 튜플.

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

예:

```python
>>> from transformers import AutoImageProcessor, Dinov2WithRegistersForImageClassification
>>> import torch
>>> from datasets import load_dataset

>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]

>>> image_processor = AutoImageProcessor.from_pretrained("facebook/dinov2-with-registers-base")
>>> model = Dinov2WithRegistersForImageClassification.from_pretrained("facebook/dinov2-with-registers-base")

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

>>> with torch.no_grad():
...     logits = model(**inputs).logits

>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_label = logits.argmax(-1).item()
>>> print(model.config.id2label[predicted_label])
...
```

