# MLCD

## 概述

[MLCD](https://huggingface.co/papers/2407.17331) 模型由 [unicom](https://github.com/deepglint/unicom) 中的 DeepGlint-AI 团队发布。该团队专注于利用 LAION400M 和 COYO700M 等大规模数据集，为大型多模态语言模型构建基础视觉模型，并采用样本到簇的对比学习来优化性能。MLCD 模型主要用于多模态视觉大语言模型，例如 LLaVA。

🔥**MLCD-ViT-bigG**🔥 系列是引入了 2D 旋转位置编码（RoPE2D）的先进视觉 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/main/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 解码器中每个注意力层的注意力头数量。

num_key_value_groups (`int`，*可选*，默认为 1)：Attention 中使用的键值组数量。

num_channels (`int`，*可选*，默认为 `3`)：输入通道数。

image_size (`Union[int, list[int], tuple[int, int]]`，*可选*，默认为 `336`)：每张图片的尺寸（分辨率）。

patch_size (`Union[int, list[int], tuple[int, int]]`，*可选*，默认为 `14`)：每个 patch 的大小（分辨率）。

hidden_act (`str`，*可选*，默认为 `gelu`)：解码器中的非线性激活函数（函数或字符串）。例如，`"gelu"`、`"relu"`、`"silu"` 等。

layer_norm_eps (`float`，*可选*，默认为 `1e-05`)：层归一化层所使用的 epsilon。

attention_dropout (`Union[float, int]`，*可选*，默认值为 `0.0`)：注意力概率的 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) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/main/zh/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/main/src/transformers/models/mlcd/modeling_mlcd.py#L466)

**参数：**

config ([MLCDVisionConfig](/docs/transformers/main/zh/model_doc/mlcd#transformers.MLCDVisionConfig)) : 模型配置类，包含模型的所有参数。使用配置文件进行初始化不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

M_L_C_D 的视觉模型，顶部未添加任何分类头或投影层。

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/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/main/src/transformers/models/mlcd/modeling_mlcd.py#L484)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*) : 与输入图像对应的张量。可以使用 [CLIPImageProcessor](/docs/transformers/main/zh/model_doc/clip#transformers.CLIPImageProcessor) 获取像素值。有关详细信息，请参阅 [CLIPImageProcessor.__call__()](/docs/transformers/main/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（`processor_class` 使用 [CLIPImageProcessor](/docs/transformers/main/zh/model_doc/clip#transformers.CLIPImageProcessor) 处理图像）。

**返回：** [BaseModelOutputWithPooling](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `tuple(torch.Tensor)`

一个 [BaseModelOutputWithPooling](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[MLCDVisionConfig](/docs/transformers/main/zh/model_doc/mlcd#transformers.MLCDVisionConfig)）和输入。

[MLCDVisionModel](/docs/transformers/main/zh/model_doc/mlcd#transformers.MLCDVisionModel) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。
- **pooler_output**（形状为 `(batch_size, hidden_size)` 的 `torch.Tensor`）-- 序列中第一个 token（分类 token）的最后一层隐藏状态，经过用于辅助预训练任务的层进一步处理后的结果。例如，对于 BERT 系列模型，这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重是在预训练期间通过下一句预测（分类）目标训练得到的。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。

示例：

```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}")
```

