본문 바로가기
목차
ML

Patch Embedding - Vision Transformers

by ds31x 2026. 7. 19.
728x90
반응형

Patch Embedding (Patch Partition + Linear Embedding)

  • Patch Embedding은 입력 영상을 Transformer가 처리할 수 있는 token으로 변환하는 과정.
  • Patch Partition과 Linear Embedding의 두 단계로 구성됨.
  • CNN에서 입력 영상을 최초의 feature representation으로 변환하는 stem과 동일한 역할을 수행함.


Patch Partition

  • 입력 영상을 겹치지 않는 $P\times P$ 크기의 patch로 분할한 후, 각 patch를 하나의 벡터로 flattening함.
  • 입력 영상의 크기가 $H\times W$, 입력 channel 수가 $C$일 때, patch의 개수는 다음과 같음:

$$
N=\frac{H}{P}\times\frac{W}{P}
$$

  • 각 patch는 $P^{2}C$ 차원의 벡터로 표현
  • Patch Partition의 출력은 다음과 같음:

$$
B\times C\times H\times W
\rightarrow
B\times N\times(P^{2}C)
$$


Linear Embedding (Linear Projection)

  • Patch Partition에서 생성된 각 patch vector를
  • Transformer의 embedding dimension $D$로 선형 투영(linear projection)함.

$$
B\times N\times(P^{2}C)
\rightarrow
B\times N\times D
$$

  • 모든 patch를 동일한 차원의 embedding으로 변환하여 Transformer block의 입력 형식을 구성함.
  • 입력과 출력의 차원이 동일하더라도, 학습 가능한 가중치를 이용한 linear projection이 수행됨.

Example and Implementation

ViT-B/16의 예

  • 입력 영상 : $B\times3\times224\times224$
  • Patch 크기 : $16\times16$
  • Patch 개수 : $N=14\times14=196$
  • 각 patch의 차원 : 16\times16\times3=768$

Patch Embedding 과정

$$
B\times3\times224\times224
\rightarrow
B\times196\times768
\rightarrow
B\times196\times768
$$

이후 학습 가능한 CLS token이 sequence의 앞에 추가되어

  • $B\times197\times768$ 이 되며,
  • position embedding을 더한 후 첫 번째 Transformer block에 입력됨.

구현

  • 실제 구현에서는 Patch Partition과 Linear Embedding을 별도의 연산으로 구현하기보다,
  • Conv2d(in_channels=3, out_channels=D, kernel_size=P, stride=P) 하나로 통합하여 구현하는 경우가 대부분임.
  • 이 convolution은 Patch Partition과 Linear Embedding을 수학적으로 동일하게 수행하므로,
  • 구현 관점에서는 두 과정을 합쳐 Patch Embedding 또는 Stem이라고 부름.

같이 보면 좋은 자료들

2026.07.13 - [ML] - DL Vision Model들에서 Stem이란?

 

DL Vision Model들에서 Stem이란?

1. Stem의 어원영어 stem 은고대 영어의 stefn 또는 stemn 에서 유래했다고 함.본래 식물의 줄기, 나무의 몸통, 배의 선수 부분처럼전체 구조를 지탱하는 중심축을 의미 함.여러 분야에서 다른 구성 요

ds31x.tistory.com

2026.07.11 - [ML] - Patch Merging of SWIN

 

Patch Merging of SWIN

Patch MergingPatch Merging Module (or Layer) 는CNN에서 널리 사용되는 Max (or Averaging) Pooling과 유사한 downsampling 역할을 수행하되,최댓값(or 평균값)을 선택하는 대신$2 \times 2$ 인접 patch의 feature를 결합하고 선

ds31x.tistory.com

 

728x90