# MLCD

## 概要

[MLCD](https://huggingface.co/papers/2407.17331)モデルは、[unicom](https://github.com/deepglint/unicom)のDeepGlint-AIチームによってリリースされました。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`、*optional*、デフォルトは`1664`) : 隠れ表現の次元数。

intermediate_size (`int`、*任意*、デフォルトは`8192`) : MLP 表現の次元数。

num_hidden_layers (`int`、*任意*、デフォルトは `48`) : Transformer デコーダーの隠れ層の数。

num_attention_heads (`int`、*任意*、デフォルトは`16`) : Transformerデコーダーの各アテンション層におけるアテンションヘッドの数。

num_key_value_groups (`int`、*optional*、デフォルトは 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`) : 各パッチのサイズ（解像度）。

hidden_act (`str`、*任意*、デフォルトは`gelu`) : デコーダーで使用する非線形活性化関数（関数または文字列）。例えば、`"gelu"`、`"relu"`、`"silu"`など。

layer_norm_eps (`float`、*任意*、デフォルトは`1e-05`) : Layer Normalization 層で使用する epsilon。

attention_dropout (`Union[float, int]`、*任意*、デフォルトは`0.0`) : 注意確率のドロップアウト率。

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/v5.23.0/ja/main_classes/configuration#transformers.PreTrainedConfig) を継承し、モデルの出力を制御するために使用できます。詳細については、[PreTrainedConfig](/docs/transformers/v5.23.0/ja/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/ja/model_doc/mlcd#transformers.MLCDVisionConfig)) : モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、[from_pretrained()](/docs/transformers/v5.23.0/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) メソッドを確認してください。

ヘッドや投影が上に乗せられていないM_L_C_Dのビジョンモデル。

このモデルは [PreTrainedModel](/docs/transformers/v5.23.0/ja/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`、形状 `(batch_size, num_channels, image_size, image_size)`、*任意*) : 入力画像に対応するテンソルです。ピクセル値は [CLIPImageProcessor](/docs/transformers/v5.23.0/ja/model_doc/clip#transformers.CLIPImageProcessor) を使用して取得できます。詳細は [CLIPImageProcessor.__call__()](/docs/transformers/v5.23.0/ja/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) を参照してください（`processor_class` は画像の処理に [CLIPImageProcessor](/docs/transformers/v5.23.0/ja/model_doc/clip#transformers.CLIPImageProcessor) を使用します）。

**戻り値:** [BaseModelOutputWithPooling](/docs/transformers/v5.23.0/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) または `tuple(torch.Tensor)`

`torch.Tensor` のタプル（`return_dict=False` が渡された場合、または `config.return_dict=False` の場合）または [BaseModelOutputWithPooling](/docs/transformers/v5.23.0/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling)。設定（[MLCDVisionConfig](/docs/transformers/v5.23.0/ja/model_doc/mlcd#transformers.MLCDVisionConfig)）と入力に応じて、さまざまな要素で構成されます。

[MLCDVisionModel](/docs/transformers/v5.23.0/ja/model_doc/mlcd#transformers.MLCDVisionModel)のforwardメソッドは、`__call__`特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく`Module`インスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを無視してしまいます。

- **last_hidden_state** (`torch.Tensor`、形状 `(batch_size, sequence_length, hidden_size)`) -- モデルの最終層の出力における隠れ状態のシーケンス。
- **pooler_output** (`torch.Tensor`、形状 `(batch_size, hidden_size)`) -- 補助的な事前学習タスクに使用される層をさらに通して処理された後、シーケンスの最初のトークン（分類トークン）の最終層の隠れ状態です。例えば、BERT系のモデルでは、線形層とtanh活性化関数を経て処理された後の分類トークンを返します。この線形層の重みは、事前学習中の次の文予測（分類）目的から学習されます。
- **hidden_states** (`tuple(torch.Tensor)`、*optional*、`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)`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）、形状は `(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}")
```

