본문 바로가기

명사 美 비격식 (무리 중에서) 아주 뛰어난[눈에 띄는] 사람[것]

이론

Modality 모달리티란? : 정렬 Alignment (Contrastive Learning, Cross Attention), 융합 (초기, 후기, 중간)


모달리티 Modality

정보를 표현하거나 전달하는 방식, 양식 

 

모달리티 정렬 Modality Alignment 

서로다른 데이터가 의미상 어떤 관계에 있는지 대응시키는 과정

예를 들어 이미지안의 특정 영역과 문장토큰을 연결시 정렬이 정확하지않으면 모델은 이미지에 없는 객체를 있다고 판단하거나 질문과 관계없는 영역에 집중할 수도 있다.

# CLIP 방식, 이미지와 텍스트를 각각 임베딩 한뒤 같은 의미라면 벡터가 가까워지도록 학습한다. 

import torch
import torch.nn.functional as F

# 이미지 임베딩
image_embedding = torch.tensor([
    [0.1, 0.7, 0.2]
], dtype=torch.float)

# 텍스트 임베딩
text_embedding = torch.tensor([
    [0.2, 0.6, 0.3]
], dtype=torch.float)

# 정규화
image_embedding = F.normalize(image_embedding, dim=1)
text_embedding = F.normalize(text_embedding, dim=1)

# Cosine Similarity
similarity = image_embedding @ text_embedding.T

print(similarity)
# Vision-Language Model(LLaVA, BLIP, Qwen-VL 등)은 텍스트 토큰이 이미지 특징을 참고하도록 Cross Attention을 사용한다. 

import torch
import torch.nn as nn

# 이미지 특징 (5개 패치)
image_features = torch.randn(5, 768)

# 질문 토큰 (10개)
text_features = torch.randn(10, 768)

cross_attention = nn.MultiheadAttention(
    embed_dim=768,
    num_heads=8,
    batch_first=True
)

output, attention = cross_attention(
    query=text_features.unsqueeze(0),   # 텍스트
    key=image_features.unsqueeze(0),    # 이미지
    value=image_features.unsqueeze(0)
)

print(output.shape)
print(attention.shape)
# CLIP은 정답 이미지와 텍스트는 가깝게, 다른 쌍은 멀어지도록 학습

import torch
import torch.nn.functional as F

# 이미지 임베딩 (배치 4개)
image_emb = F.normalize(torch.randn(4, 512), dim=1)

# 텍스트 임베딩 (배치 4개)
text_emb = F.normalize(torch.randn(4, 512), dim=1)

# 유사도 행렬
logits = image_emb @ text_emb.T

# 정답은 같은 인덱스끼리
labels = torch.arange(4)

loss_i = F.cross_entropy(logits, labels)
loss_t = F.cross_entropy(logits.T, labels)

loss = (loss_i + loss_t) / 2

print(loss.item())

 

 

 

 

Modality Alignment는 이미지와 텍스트처럼 서로 다른 형태의 데이터를 같은 의미 공간으로 맞추어 연겨리하는 과정. 

모델은 질문의 각 토큰이 이미지의 올바른 영역을 참ㅈ하고 이미지와 텍스트의 의미를 일관되게 이해할 수 있게된다. 

이미지
   │
Vision Encoder (ViT, CNN)
   │
Image Embedding
   │
           ┌──────────────┐
           │ Modality     │
텍스트 ───▶│ Alignment     │
Embedding  │ (Contrastive  │
           │  Learning,    │
           │ Cross Attention)
           └──────────────┘
                    │
         Shared Semantic Space
                    │
          LLM (Qwen-VL, LLaVA, GPT-4V 등)
                    │
                 최종 답변

 

 

 

 

모달리티의 융합

입력 데이터를 처리하는 초기 단계에서 특징을 결합하는 초기융합은 모달리티 사이의 세밀한 관계를 조기에 학습하나 데이터의 크기나 구조가 다르면 결함하기 어렵고 특정 모달리티의 잡음이 전체 학습에 영향을 줄 수 있다.

import torch

# 이미지 특징
image_feature = torch.randn(1, 512)

# 텍스트 특징
text_feature = torch.randn(1, 768)

# Early Fusion
fusion = torch.cat([image_feature, text_feature], dim=1)

print(fusion.shape)

 

모달리티를 독립적으로 처리한 뒤 최종 예측 결과를 결합하는 후기융합은 기존 유니모달 모델을 재사용하기 쉽고 특정 모달리티가 누락되어도 비교적 대응하기 쉽지만 모달리티 사이의 세밀한 상호작용은 충분히 학습하기 어렵다.

import torch

# 이미지 모델 결과
image_pred = torch.tensor([[0.8, 0.2]])

# 텍스트 모델 결과
text_pred = torch.tensor([[0.6, 0.4]])

# Late Fusion
final_pred = (image_pred + text_pred) / 2

print(final_pred)

 

각 모달리티 중간 특징을 추출한 뒤 모델 내부에서 반복적으로 상호작용하게 하는 중간융합은 현대 멀티 모달 모델에서 널리 사용하는 방식으로 표현력과 유연성이 높으나 구조와 학습이 복잡하다.

import torch
import torch.nn as nn

image_feature = torch.randn(1, 196, 768)
text_feature = torch.randn(1, 20, 768)

cross_attention = nn.MultiheadAttention(
    embed_dim=768,
    num_heads=8,
    batch_first=True
)

fusion, attention = cross_attention(
    query=text_feature,
    key=image_feature,
    value=image_feature
)

print(fusion.shape)
print(attention.shape)