Transformers documentation

MLCD

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

이 모델은 2024-07-24에 HF papers에 게시되었으며, 2025-04-15에 Hugging Face Transformers에 기여되었습니다.

MLCD

SDPA

개요

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

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

팁:

결과:

비전 타워RoPE2DChartQADocVQAInfoVQAOCRBenchMMMU
CLIP (ViT-L-14-336px)×66.5275.2138.88525.0044.20
SigLIP (ViT-SO400M-384px)×69.2876.7141.38554.0046.78
DFN5B (ViT-H-14-378px)×64.3670.8738.59473.0048.00
MLCD (ViT-L-14-336px)×67.8476.4643.48531.0044.30
MLCD (ViT-bigG-14-336px)√71.0779.6344.38572.0046.78
MLCD (ViT-bigG-14-448px)√73.8083.3446.59582.0046.00

사용

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_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 1664intermediate_size: int = 8192num_hidden_layers: int = 48num_attention_heads: int = 16num_key_value_groups: int = 1num_channels: int = 3image_size: int | list[int] | tuple[int, int] = 336patch_size: int | list[int] | tuple[int, int] = 14hidden_act: str = 'gelu'layer_norm_eps: float = 1e-05attention_dropout: float | int = 0.0initializer_range: float = 0.02initializer_factor: float = 1.0rope_parameters: dict | None = None )

매개변수

  • hidden_size (int, 선택 사항, 기본값 1664) — 숨겨진 표현의 차원입니다.
  • intermediate_size (int, 선택 사항, 기본값 8192) — MLP 표현의 차원입니다.
  • num_hidden_layers (int, 선택 사항, 기본값 48) — Transformer decoder의 숨겨진 레이어 수입니다.
  • 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) — 레이어 정규화 레이어에서 사용되는 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의 설정과 유사한 설정이 생성됩니다.

Configuration 객체는 PreTrainedConfig를 상속하며 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 PreTrainedConfig의 문서를 참고하세요.

예:

>>> 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

< >

( config: MLCDVisionConfig )

매개변수

  • config (MLCDVisionConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 연관된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.

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

이 모델은 PreTrainedModel에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대한 세부 사항은 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.

forward

< >

( pixel_values: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

매개변수

  • pixel_values (torch.Tensor, shape (batch_size, num_channels, image_size, image_size), 선택 사항) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 CLIPImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 CLIPImageProcessor.call()를 참조하세요 (processor_class는 이미지 처리에 CLIPImageProcessor를 사용합니다).

반환값

BaseModelOutputWithPooling 또는 tuple(torch.Tensor)

torch.Tensor의 튜플 또는 BaseModelOutputWithPooling (return_dict=False가 전달되었거나 config.return_dict=False인 경우)로, 구성(MLCDVisionConfig)과 입력에 따라 다양한 요소를 포함합니다.

MLCDVisionModel의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.

이 함수 내에서 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 가중치.

예:

>>> 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}")
Update on GitHub