# MLCD

## 개요

[MLCD](https://huggingface.co/papers/2407.17331) 모델은 [unicom](https://github.com/deepglint/unicom)에서 공개되었습니다. unicom은 LAION400M, COYO700M과 같은 대규모 데이터셋을 활용하여 대규모 멀티모달 언어 모델의 기반 시각 모델을 구축하는 데 집중하며, 성능 최적화를 위해 샘플-클러스터 대비 학습을 적용합니다. MLCD 모델은 LLaVA와 같은 멀티모달 시각 대규모 언어 모델에 주로 사용됩니다.

🔥**MLCD-ViT-bigG**🔥 시리즈는 2D Rotary Position Embedding(RoPE2D)으로 강화된 최첨단 vision transformer 모델로, 문서 이해 및 시각 질의응답 작업에서 우수한 성능을 달성합니다. DeepGlint AI에서 개발한 이 모델은 복잡한 시각-언어 상호작용 처리에서 뛰어난 역량을 보여줍니다.

팁:

- 기초 시각 모델 평가에 공식 [LLaVA-NeXT](https://github.com/LLaVA-VL/LLaVA-NeXT)와 공식 학습 데이터셋 [LLaVA-NeXT-Data](https://huggingface.co/datasets/lmms-lab/LLaVA-NeXT-Data)를 채택했습니다.

- 언어 모델은 [Qwen2.5-7B](https://huggingface.co/Qwen/Qwen2.5-7B-Instruct)입니다.

결과:

| 비전 타워                                                                                  | RoPE2D | ChartQA   | DocVQA    | InfoVQA   | OCRBench   | MMMU      |
| :-------------------------------------------------------------------------------------------- | :----: | :-------- | :-------- | :-------- | :--------- | :-------- |
| CLIP (ViT-L-14-336px)                                                                         |   ×    | 66.52     | 75.21     | 38.88     | 525.00     | 44.20     |
| SigLIP (ViT-SO400M-384px)                                                                     |   ×    | 69.28     | 76.71     | 41.38     | 554.00     | 46.78     |
| DFN5B (ViT-H-14-378px)                                                                        |   ×    | 64.36     | 70.87     | 38.59     | 473.00     | **48.00** |
| **[MLCD (ViT-L-14-336px)](https://huggingface.co/DeepGlint-AI/mlcd-vit-large-patch14-336)**   |   ×    | 67.84     | 76.46     | 43.48     | 531.00     | 44.30     |
| **[MLCD (ViT-bigG-14-336px)](https://huggingface.co/DeepGlint-AI/mlcd-vit-bigG-patch14-336)** |   √    | 71.07     | 79.63     | 44.38     | 572.00     | 46.78     |
| **[MLCD (ViT-bigG-14-448px)](https://huggingface.co/DeepGlint-AI/mlcd-vit-bigG-patch14-448)** |   √    | **73.80** | **83.34** | **46.59** | **582.00** | 46.00     |

## 사용

```python
import requests
from PIL import Image

from transformers import AutoProcessor, MLCDVisionModel

# Load model and processor
model = MLCDVisionModel.from_pretrained("DeepGlint-AI/mlcd-vit-bigG-patch14-448", device_map="auto")
processor = AutoProcessor.from_pretrained("DeepGlint-AI/mlcd-vit-bigG-patch14-448")

# Process single image
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)
inputs = processor(images=image, return_tensors="pt").to(model.device)

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

# Get visual features
features = outputs.last_hidden_state

print(f"Extracted features shape: {features.shape}")
```

## MLCDVisionConfig[[transformers.MLCDVisionConfig]]

#### transformers.MLCDVisionConfig[[transformers.MLCDVisionConfig]]

```python
transformers.MLCDVisionConfig(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 = 1664, intermediate_size: int = 8192, num_hidden_layers: int = 48, num_attention_heads: int = 16, num_key_value_groups: int = 1, num_channels: int = 3, image_size: int | list[int] | tuple[int, int] = 336, patch_size: int | list[int] | tuple[int, int] = 14, hidden_act: str = 'gelu', layer_norm_eps: float = 1e-05, attention_dropout: float | int = 0.0, initializer_range: float = 0.02, initializer_factor: float = 1.0, rope_parameters: dict | None = None)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/mlcd/configuration_mlcd.py#L28)

**매개변수:**

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

intermediate_size (`int`, *선택 사항*, 기본값 `8192`) : MLP 표현의 차원.

num_hidden_layers (`int`, *선택 사항*, 기본값 `48`) : Transformer 디코더의 숨겨진 레이어 수.

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

num_key_value_groups (`int`, *선택 사항*, 기본값 1) : Attention에서 사용되는 key-value 그룹의 수.

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

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

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

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

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

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

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

initializer_factor (`float`, *선택 사항*, 기본값 `1.0`) : 모든 가중치 행렬을 초기화하는 계수입니다(1로 유지해야 하며, 초기화 테스트를 위해 내부적으로 사용됨).

rope_parameters (`dict`, *선택*) : RoPE 임베딩의 구성 매개변수를 포함하는 사전입니다. 사전에는 `rope_theta` 값이 포함되어야 하며, 더 긴 `max_position_embeddings`로 RoPE를 사용하려는 경우 스케일링에 사용되는 매개변수를 선택적으로 포함할 수 있습니다.

이것은 MLCDVisionModel의 구성을 저장하기 위한 구성 클래스입니다. 지정된 인자에 따라 Mlcd 모델을 인스턴스화하여 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 구성을 인스턴스화하면 [DeepGlint-AI/mlcd-vit-bigG-patch14-336](https://huggingface.co/DeepGlint-AI/mlcd-vit-bigG-patch14-336)의 구성과 유사한 구성이 생성됩니다.

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)의 문서를 참고하세요.

예:

```python
>>> from transformers import MLCDVisionConfig, MLCDVisionModel

>>> # Initializing a MLCDVisionConfig with DeepGlint-AI/mlcd-vit-bigG-patch14-336 style configuration
>>> configuration = MLCDVisionConfig()

>>> # Initializing a MLCDVisionModel (with random weights) from the DeepGlint-AI/mlcd-vit-bigG-patch14-336 style configuration
>>> model = MLCDVisionModel(configuration)

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

## MLCDVisionModel[[transformers.MLCDVisionModel]]

#### transformers.MLCDVisionModel[[transformers.MLCDVisionModel]]

```python
transformers.MLCDVisionModel(config: MLCDVisionConfig)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/mlcd/modeling_mlcd.py#L466)

**매개변수:**

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

상단부에 헤드나 투영이 없는 M_L_C_D의 비전 모델입니다.

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

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

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/mlcd/modeling_mlcd.py#L484)

**매개변수:**

pixel_values (`torch.Tensor`, shape `(batch_size, num_channels, image_size, image_size)`, *선택 사항*) : 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 [CLIPImageProcessor](/docs/transformers/v5.23.0/ko/model_doc/clip#transformers.CLIPImageProcessor)를 사용하여 얻을 수 있습니다. 자세한 내용은 [CLIPImageProcessor.__call__()](/docs/transformers/v5.23.0/ko/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)를 참조하세요 (`processor_class`는 이미지 처리에 [CLIPImageProcessor](/docs/transformers/v5.23.0/ko/model_doc/clip#transformers.CLIPImageProcessor)를 사용합니다).

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

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

[MLCDVisionModel](/docs/transformers/v5.23.0/ko/model_doc/mlcd#transformers.MLCDVisionModel)의 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
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from PIL import Image
>>> from transformers import AutoProcessor, MLCDVisionModel
>>> model = MLCDVisionModel.from_pretrained("DeepGlint-AI/mlcd-vit-bigG-patch14-448")
>>> processor = AutoProcessor.from_pretrained("DeepGlint-AI/mlcd-vit-bigG-patch14-448")

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

>>> with torch.no_grad():
...     outputs = model(**inputs, output_attentions=True)

>>> features = outputs.last_hidden_state
>>> print(f"Extracted features shape: {features.shape}")
>>> print(f"Number of attention layers: {len(outputs.attentions)}")
>>> print(f"Attention shape: {outputs.attentions[0].shape}")
```

