카테고리 없음

Self Attention, Cross Attention 차이점

도도걸만단 2025. 5. 27. 17:27
반응형

Self Attention

문장 내부에서 자기자신과

 

 

 

 


Cross Attention

Cross-Attention은 Transformer 모델에서 디코더가 인코더의 출력을 참조하여 정보를 얻는 메커니즘입니다. 이는 디코더가 현재 생성 중인 출력과 관련된 입력의 부분에 집중할 수 있게 도와줍니다. 예를 들어, 기계 번역에서 영어 문장을 힌디어로 번역할 때, 디코더는 이미 생성된 단어들과 입력 문장의 관련 부분을 동시에 고려하여 다음 단어를 생성합니다.

  1. 입력 준비:
    • 두 개의 입력 시퀀스(예: 이미지 패치 시퀀스와 텍스트 시퀀스)를 준비합니다.
  2. Query, Key, Value 생성:
    • 디코더의 출력에서 Query를 생성하고, 인코더의 출력에서 Key와 Value를 생성합니다.GeeksforGeeks
  3. Attention 계산:
    • Query와 Key의 내적을 계산하고, 소프트맥스를 적용하여 Attention 가중치를 얻습니다.
    • 이 가중치를 Value에 곱하여 최종 출력을 생성합니다.

이러한 메커니즘은 이미지 캡셔닝, 텍스트 요약, 질의 응답 시스템 등 다양한 분야에서 활용됩니다.

query : decoding, 

key, value : encoding 에서 온다고 보면 됨

 

이미지를 cross attention으로 입력하는 방법은 주로 두 이미지(혹은 이미지와 텍스트 등 서로 다른 modality)를 Transformer 기반 네트워크에서 서로의 정보를 주고받게 하는 방식입니다. 최근 diffusion 모델, 이미지 편집, 멀티모달 학습 등에서 활발히 응용되고 있습니다.
아래는 대표적인 구현 방식과 참고 자료입니다.


1. 기본 원리

  • **cross attention**은 Query, Key, Value 중 일부를 서로 다른 입력(예: 두 이미지, 이미지-텍스트)에서 가져와 정보를 교환합니다.
  • 예시:
    • Query: 주 이미지(혹은 구조 이미지) feature
    • Key/Value: 다른 이미지(혹은 appearance 이미지) feature
  • 이 과정을 통해 한 이미지의 특성(구조, appearance 등)이 다른 이미지에 반영됩니다145.

2. 대표 구현 예시

a. Cross-Image Attention for Appearance Transfer

  • 구조 이미지의 feature를 Query로, 스타일(appearance) 이미지의 feature를 Key/Value로 사용
  • diffusion 모델의 denoising 과정에서 cross attention layer를 삽입
  • 두 이미지의 feature map을 각각 인코더로 추출한 뒤, cross attention 연산을 적용
 
python
# Pseudocode 예시 # x_struct: 구조 이미지 feature, x_app: appearance 이미지 feature Q = proj_query(x_struct) K = proj_key(x_app) V = proj_value(x_app) attention = softmax(Q @ K.T / sqrt(dk)) out = attention @ V

b. Deep Metric Learning에서의 Cross Attention

  • 이미지 쌍의 feature map을 뽑아, 한 이미지의 embedding을 다른 이미지에 조건(conditioning)하도록 cross attention 적용
  • 반복적으로 cross attention block을 쌓아 점진적으로 정보를 융합2

c. Diffusion/이미지 편집에서의 Cross Attention Control

  • diffusion 모델의 cross attention map을 직접 수정해 prompt-to-prompt 이미지 편집, 이미지-이미지 효과 적용3
  • 예: 한 이미지의 특정 부분에만 다른 이미지의 스타일을 반영

3. 참고 자료 및 논문


요약

  • 이미지를 cross attention으로 넣으려면, 두 이미지의 feature map을 각각 인코딩한 뒤, 한 쪽을 Query, 다른 쪽을 Key/Value로 사용해 cross attention 연산을 적용하면 됩니다.
  • diffusion 모델, 이미지 편집, 멀티모달 학습 등 다양한 분야에서 실제 적용 사례와 코드가 공개되어 있습니다1245.

가장 실용적인 구현 예시와 논문은 "Cross-Image Attention for Zero-Shot Appearance Transfer"와 그 공식 GitHub 저장소를 참고하면 좋습니다.

Citations:

  1. https://garibida.github.io/cross-image-attention/
  2. https://openaccess.thecvf.com/content/CVPR2023/papers/Kotovenko_Cross-Image-Attention_for_Conditional_Embeddings_in_Deep_Metric_Learning_CVPR_2023_paper.pdf
  3. https://velog.io/@yell0315/Prompt-to-Prompt-Image-Editing-with-Cross-Attention-Control
  4. https://arxiv.org/abs/2311.03335
  5. https://github.com/garibida/cross-image-attention
  6. https://web.stanford.edu/class/cs224n/final-reports/256711050.pdf
  7. https://openaccess.thecvf.com/content_CVPR_2020/papers/Wei_Multi-Modality_Cross_Attention_Network_for_Image_and_Sentence_Matching_CVPR_2020_paper.pdf
  8. https://arxiv.org/html/2404.02747v1
  9. https://paperswithcode.com/paper/cross-image-attention-for-conditional
  10. https://www.youtube.com/watch?v=aw3H-wPuRcw

"Cross-Image Attention for Zero-Shot Appearance Transfer" 논문과 코드의 핵심 내용을 요약하고, 실용적인 구현 방법을 안내합니다.


1. 논문 핵심 아이디어

  • 목적: 한 이미지의 **외관(appearance)**을 다른 이미지의 **구조(structure)**에 자연스럽게 전이 (예: 사과 → 오렌지 텍스처 전이)
  • 방법:
    • 두 이미지(구조 이미지 $I_s$, 외관 이미지 $I_a$)를 diffusion 모델에 입력
    • **Cross-image attention layer**를 통해 $I_a$의 외관 정보를 $I_s$의 구조에 융합
    • 사전 학습된 diffusion 모델(Stable Diffusion)을 활용해 zero-shot 학습 없이 즉시 적용 가능

2. 코드 구현 구조 (GitHub 링크)

주요 파일/기능

  • pipeline_pasd.py: 이미지 전이를 위한 커스텀 파이프라인
  • cross_image_attention.py: cross-attention 모듈 구현
  • configs/: 모델 설정(YAML 파일)

Key Code Snippet

 
python
# Cross-attention layer 예시 (일부 축약) class CrossImageAttention(nn.Module): def forward(self, q, k, v): # q: 구조 이미지 feature # k, v: 외관 이미지 feature attn = (q @ k.transpose(-2, -1)) * self.scale attn = attn.softmax(dim=-1) output = attn @ v return output

3. 사용 방법

환경 설정

 
bash
git clone https://github.com/garibida/cross-image-attention cd cross-image-attention pip install -r requirements.txt # 주요 패키지: torch, diffusers, transformers

실행 예시

 
bash
python scripts/inference.py \ --structure_image "input/structure.jpg" \ --appearance_image "input/appearance.jpg" \ --output_dir "output/" \ --config "configs/default.yaml"

4. 주요 특징

  • 강점:
    • Zero-shot 전이: 추가 학습 없이 즉시 적용 가능
    • 고화질 결과: 512x512 해상도 지원
    • 부분 전이: 마스크를 통해 특정 영역만 외관 전이 가능
  • 제한점:
    • GPU 메모리 12GB 이상 권장 (RTX 3090 기준)
    • 복잡한 구조(인물 포즈 등) 전이 시 한계 존재

5. 활용 예시

  • 스타일 전이: 풍경화 → 사진 스타일 변환
  • 텍스처 합성: 동물 무늬 → 의류 디자인
  • 의료 이미징: MRI → CT 구조 변환 (도메인 adaptation)

결론: 이 코드는 구조-외관 분리 학습 없이 즉시 이미지 전이를 수행할 수 있어 실험적 적용이 용이합니다. 논문의 cross-image attention 메커니즘을 이해하려면 cross_image_attention.py의 AttentionMap 계산 로직을 중점적으로 분석하세요.


 

Left/Right Depth에 Cross Attention을 적용한 주요 사례 및 논문

Stereo 이미지 처리(깊이 추정, 초해상도, 압축 등)에서 Left/Right Depth에 Cross Attention을 적용한 연구는 최근 활발히 진행되고 있습니다. 주요 사례를 정리합니다.


1. Stereo Image Super-Resolution (SISR)

  • 논문: Hybrid Cross-View Attention Network (HCVAN)
    • 방법: Left/Right 이미지의 intra-view feature를 추출한 후, cross-view attention으로 두 뷰의 정보를 융합하여 초해상도 복원
    • 특징: Epipolar geometry 제약을 활용해 효율적인 attention 계산

2. Stereo Depth Estimation


3. Stereo Image Compression

  • 논문: ECSIC: Epipolar Cross Attention
    • 방법: 좌우 이미지의 epipolar line 제약 하에서 cross-attention 수행
    • 효과: Stereo redundancy 감소로 압축률 극대화

4. Multi-View Depth Estimation

  • 논문: Cross-View Completion Models (ZeroCo)
    • 방법: Cross-attention map을 활용해 zero-shot geometric correspondence 및 깊이 추정
    • 장점: 사전 학습 없이도 multi-view 깊이 예측 가능

5. Cross-Spectral Depth Fusion


공통 기술 요소

  1. Epipolar Geometry 활용: 좌우 이미지의 기하학적 제약을 attention 계산에 반영
  2. Sparse vs. Dense Attention: Locality-sensitive hashing(LSH) 등으로 계산 효율성 확보
  3. Multi-Modal Fusion: RGB, 깊이, IR 등을 cross-attention으로 결합

결론: Stereo 깊이 처리 분야에서 cross-attention은 좌우 뷰 간의 상관관계 추출다중 모달리티 융합의 핵심 메커니즘으로 자리잡았습니다.

 

cross-attention을 활용한 스테레오 이미지 기반의 depth estimation은 최근 연구에서 활발히 탐구되고 있습니다. 이러한 접근 방식은 좌우 이미지 간의 정보를 효과적으로 결합하여 더 정확한 깊이 예측을 가능하게 합니다.


Cross-Attention을 활용한 스테레오 이미지 기반 Depth Estimation 사례

  1. Cross-Spectral Gated-RGB Stereo Depth Estimation
    이 연구에서는 서로 다른 스펙트럼(RGB와 Gated 이미지)의 스테레오 이미지를 활용하여 깊이를 추정합니다. cross-attention 메커니즘을 통해 두 이미지 간의 상호 정보를 효과적으로 결합하여 깊이 예측의 정확도를 높였습니다.
  2. Cross-View Completion Models
    이 모델은 서로 다른 시점의 이미지 간의 상호 보완적인 정보를 활용하여 깊이를 예측합니다. cross-attention 맵을 통해 두 이미지 간의 대응 관계를 학습하며, 이를 통해 깊이 정보를 추정합니다.
  3. Stereo Transformer (STTR)
    이 모델은 self-attention과 cross-attention을 결합하여 스테레오 이미지 간의 정밀한 대응 관계를 학습합니다. 이를 통해 깊이 예측의 정확도를 향상시킵니다.

Cross-Attention을 활용한 Depth Estimation의 장점

  • 정확한 대응 관계 학습: cross-attention은 좌우 이미지 간의 정밀한 대응 관계를 학습하여 깊이 예측의 정확도를 높입니다.
  • 다양한 시점 정보 통합: 서로 다른 시점의 이미지를 효과적으로 결합하여 더 풍부한 깊이 정보를 얻을 수 있습니다.
  • 복잡한 장면 처리 능력 향상: cross-attention을 통해 occlusion이나 textureless 영역에서도 보다 안정적인 깊이 예측이 가능합니다.(arXiv)

추가 학습 자료


 

 

Stereo depth estimation에서 cross-attention을 활용한 연구들은 다양한 방식으로 left와 right 이미지 간의 정보를 통합하여 정확한 depth 예측을 시도하고 있습니다. 이러한 접근법들은 특히 복잡한 장면이나 다양한 조명 조건에서의 성능 향상에 기여하고 있습니다.


Cross-Attention을 활용한 Stereo Depth Estimation 연구 사례

1. STereo TRansformer (STTR)

STTR은 left와 right 이미지의 epipolar line 상의 픽셀 간 대응을 찾기 위해 cross-attention을 활용합니다. 이 접근법은 고정된 disparity 범위의 제한을 완화하고, occlusion 영역을 식별하며, 매칭 과정에서의 유일성 제약을 적용합니다. 이러한 특성들은 다양한 도메인에서의 일반화 성능을 향상시키는 데 기여합니다. (CVF Open Access)

2. Cross-spectral Gated-RGB Stereo Depth Estimation

이 연구는 서로 다른 스펙트럼(예: 가시광선과 근적외선)에서 촬영된 이미지 쌍을 활용하여 depth를 예측합니다. cross-spectral fusion 모듈을 통해 두 이미지의 특징을 정렬하고, attention 기반의 feature fusion을 수행하여 다양한 조명 조건에서도 정확한 depth 맵을 생성합니다. (CVF Open Access)

3. ChiTransformer

ChiTransformer는 self-supervised 학습을 통해 stereo depth를 추정하는 모델로, gated positional cross-attention(GPCA) 레이어를 도입하여 left와 right 이미지 간의 특징을 효과적으로 통합합니다. 이 접근법은 특히 dynamic하거나 복잡한 환경에서의 depth 추정 성능을 향상시킵니다. (arXiv)


Cross-Attention 기반 Loss 설정

cross-attention을 활용한 stereo depth estimation에서는 일반적으로 다음과 같은 loss 함수들이 사용됩니다:

  • Reconstruction Loss (L1 또는 L2): 예측된 depth를 기반으로 한 이미지 재구성을 원본 이미지와 비교하여 계산합니다.
  • Perceptual Loss (예: LPIPS): 재구성된 이미지와 원본 이미지 간의 고차원 특징 차이를 측정하여 시각적 유사성을 평가합니다.
  • Smoothness Loss: depth 맵의 공간적 연속성을 유지하기 위해 인접 픽셀 간의 depth 차이를 최소화합니다.
  • Occlusion-aware Loss: occlusion 영역을 고려하여 해당 영역의 loss 기여도를 조절하거나 제외합니다.

예를 들어, STTR에서는 cross-attention을 통해 얻은 매칭 정보를 기반으로 disparity를 예측하고, 이를 통해 위의 loss 함수들을 적용하여 모델을 학습시킵니다.(CVF Open Access)


Input 및 Output 형태

  • Input: 정렬된 left와 right 이미지 쌍. 일반적으로 동일한 해상도를 가지며, epipolar geometry에 따라 정렬되어야 합니다.(arXiv)
  • Output: 각 픽셀에 대한 disparity 또는 depth 값으로 구성된 맵. 이 맵은 left 이미지의 각 픽셀에 대해 대응하는 right 이미지의 픽셀 위치를 나타내며, 이를 통해 3D 구조를 복원할 수 있습니다.

관련 자료 및 학습 리소스

 

 

 

출처 :  https://youtu.be/514eZBF8DkE?si=CMLYCdTN81yF7NV3


Citations:

  1. https://openaccess.thecvf.com/content/CVPR2024W/NTIRE/papers/Yang_Hybrid_Cross-View_Attention_Network_for_Lightweight_Stereo_Image_Super-Resolution_CVPRW_2024_paper.pdf
  2. https://openaccess.thecvf.com/content/CVPR2024/papers/Brucker_Cross-spectral_Gated-RGB_Stereo_Depth_Estimation_CVPR_2024_paper.pdf
  3. https://www.ecva.net/papers/eccv_2022/papers_ECCV/papers/136920263.pdf
  4. https://openaccess.thecvf.com/content/CVPR2023W/NTIRE/papers/Zhou_Stereo_Cross_Global_Learnable_Attention_Module_for_Stereo_Image_Super-Resolution_CVPRW_2023_paper.pdf
  5. https://arxiv.org/html/2406.10581v1
  6. https://arxiv.org/html/2309.16301v2
  7. https://openaccess.thecvf.com/content/WACV2024/papers/Wodlinger_ECSIC_Epipolar_Cross_Attention_for_Stereo_Image_Compression_WACV_2024_paper.pdf
  8. https://arxiv.org/html/2412.09072v1
  9. https://www.ki-it.com/xml/37318/37318.pdf
  10. https://github.com/bloc97/CrossAttentionControl

 

반응형