Vision Transformer에 대한 시각적 설명 (A Visual Guide to Vision Transformers)

:pytorch:PyTorchKR:kr:

Data Scientist이자 Software Engineer인 Dennis Turp의 허락 하에, 그가 작성한 Vision Transformer(ViT)에 대한 시각적 설명 글(A Visual Guide to Vision Transformers)을 번역하였습니다.

Vision Transformer(ViT)는 CV(Computer Vision) 분야에 Transformer를 적용하여 객체 탐지 및 이미지 분류 등의 분야에서 뛰어난 성능을 보이는 모델입니다. 특히 이미지로부터 특징(feature)을 추출하는 Visual Encoder로써 많이 사용되고 있습니다.

원문의 설명이 간략하여 이해가 어려울 수 있는 경우에는 이해를 돕기 위해 :pytorch::kr: 기호를 붙여 일부 주석을 추가하였습니다.:wink:


Vision Transformer(ViT)에 대한 시각적 설명

이 글은 이미지 분류 작업에서 최첨단(SotA, State-of-the-Art)의 성능을 보이는 딥러닝 모델인 Vision Transformers(ViTs)에 대한 시각적 설명 글입니다. Vision Transformer는 원래 자연어 처리(NLP)를 위해 설계된 Transformer 아키텍처를 이미지 데이터 적용한 것입니다. 이 글에서는 스크롤을 넘기며 데이터의 흐름을 이해하는데 도움이 되는 시각화와 함께 간단한 설명을 통해 Vision Transformer의 동작 방식을 이해할 수 있도록 합니다. (:pytorch::kr:: 여기에서는 스크롤로 설명은 어려워, 이미지 캡처로 대체합니다. 원문을 함께 참고하시면 좋습니다.)

This is a visual guide to Vision Transformers (ViTs), a class of deep learning models that have achieved state-of-the-art performance on image classification tasks. Vision Transformers apply the transformer architecture, originally designed for natural language processing (NLP), to image data. This guide will walk you through the key components of Vision Transformers in a scroll story format, using visualizations and simple explanations to help you understand how these models work and how the flow of the data through the model looks like.

0. 데이터 살펴보기 / Lets start with the data

Vision Transformer에 대한 시각적 설명: 0. 데이터 살펴보기

일반적인 합성곱 신경망(CNN)과 마찬가지로 Vision Transformer도 지도 학습(Supervised Learning) 방식으로 학습합니다. 즉, 이미지와 이에 맞는 레이블(label)로 구성된 데이터셋으로 모델이 학습합니다.

Like normal convolutional neural networks, vision transformers are trained in a supervised manner. This means that the model is trained on a dataset of images and their corresponding labels.

1. 데이터 하나만 집중해서 보기 / Focus on one data point

Vision Transformer에 대한 시각적 설명: 1. 데이터 하나에 집중해보기

Vision Transformer가 내부적으로 어떻게 동작하는지 알아보기 위해, 하나의 데이터(배치 크기 1)에 대해서만 먼저 집중해보겠습니다. 그리고 이 질문을 함께 생각해보시죠: Transformer에 이 데이터를 입력하기 위해서는 어떻게 준비(전처리)해야 할까요?

To get a better understanding of what happens inside a vision transformer lets focus on a single data point (batch size of 1). And lets ask the question: How is this data point prepared in order to be consumed by a transformer?

2. 레이블은 잠시 치워두기 / Forget the label for the moment

Vision Transformer에 대한 시각적 설명: 2. 레이블은 잠시 치워두기

레이블은 나중에 더 관련성있게 살펴보겠습니다. 지금은 이미지 하나만 남겨놓고 보겠습니다.

The label will become more relevant later. For now the only thing that we are left with is a single image.

3. 이미지를 패치로 쪼개기 / Create patches of the image

Vision Transformer에 대한 시각적 설명: 3. 이미지를 패치로 쪼개기

전체 이미지를 동일한 크기의 패치(p x p) 이미지로 나누어 Transformer 내부에서 사용할 수 있도록 준비합니다.

To prepare the image for the use inside the transformer we divide the image into equally sized patches of size p x p.

4. 이미지 패치들을 평탄화하기 / Flatting of the image patches

Vision Transformer에 대한 시각적 설명: 4. 이미지 패치 평탄화

패치들을 p' = p² x c 크기의 벡터로 평탄화(flaten)합니다. 이 때 p는 패치의 한 변의 크기이고, c는 채널 수입니다. (:pytorch::kr:: 예를들어, RGB 이미지의 경우 채널 수는 3입니다.)

The patches are now flattened into vectors of dimension p'= p²*c where p is the size of the patch and c is the number of channels.

5. 패치로부터 임베딩 만들기 / Creating patch embeddings

Vision Transformer에 대한 시각적 설명: 5. 패치로부터 임베딩 만들기

앞에서 이미지 패치로부터 만든 벡터들을 선형 변환을 통해 인코딩합니다. 이렇게 만들어진 패치 임베딩 벡터(Patch Embedding Vector) 는 고정된 크기 d를 갖습니다.

These image patch vectors are now encoded using a linear transformation. The resulting Patch Embedding Vector has a fixed size d.

6. 모든 패치들을 임베딩하기 / Embedding all patches

Vision Transformer에 대한 시각적 설명: 6. 모든 패치들을 임베딩하기

이미지 패치들을 모두 고정된 크기의 벡터로 임베딩하게 되면 n x d 크기의 배열을 얻게 됩니다. 여기서 n은 이미지 패치의 개수이고, d는 하나의 패치가 임베딩된 크기입니다.

Now that we have embedded our image patches into vectors of fixed size, we are left with an array of size n x d where n is the the number of image patches and d is the size of the patch embedding

7. 분류 토큰(CLS) 추가하기 / Appending a classification token

Vision Transformer에 대한 시각적 설명: 7. 분류 토큰(CLS) 추가하기

모델을 효과적으로 학습하기 위해, 패치 임베딩에 추가로 분류 토큰(CLS token)이라 부르는 벡터를 추가합니다. 이 벡터는 신경망을 통해 학습 가능한 매개변수로, 무작위로 초기화됩니다. 참고로, CLS 토큰은 하나만 있으며, 모든 데이터들에 동일한 벡터를 추가합니다. (:pytorch::kr:: 여기까지 하게 되면 n개의 패치 임베딩에 CLS 토큰을 더하여 (n+1)개에 각 임베딩 크기 d인, (n+1) x d 를 갖게 됩니다.)

In order for us to effectively train our model we extend the array of patch embeddings by an additional vector called classification token (cls token). This vector is a learnable parameter of the network and is randomly initialized. Note: We only have one cls token and we append the same vector for all data points.

8. 위치 임베딩 벡터 추가하기 / Add positional embedding Vectors

Vision Transformer에 대한 시각적 설명: 8. 위치 임베딩 벡터 추가하기

지금까지의 패치 임베딩에는 별도의 위치 정보가 없습니다. 모든 패치 임베딩에 학습 가능한, 무작위로 초기화된 위치 임베딩 벡터(Positional Embedding Vector) 를 더하여 이 문제를 해결합니다. 또한, 앞에서 추가한 분류 토큰(CLS token) 에도 이러한 위치 벡터를 추가합니다. (:pytorch::kr:: Transformer에서는 Positional Encoding의 값을 '더해'줍니다. 따라서 벡터의 크기에는 변화가 없습니다.)

Currently our patch embeddings have no positional information associated with them. We remedy that by adding a learnable randomly initialized positional embedding vector to all our patch embeddings. We also add a such a positional embedding vector to our classification token.

9. Transformer에 입력하기 / Transformer Input

Vision Transformer에 대한 시각적 설명: 9. Transformer에 입력

위치 임베딩 벡터를 추가하면 (n+1) x d 크기의 배열이 남습니다. 이 배열을 Transformer의 입력으로 제공할 것이며, 이에 대해서는 다음 단계에서 더 자세히 설명하겠습니다.

After the positional embedding vectors have been added we are left with an array of size (n+1) x d. This will be our input for the transformer which will be explained in greater detail in the next steps.

10.1. Transformer: QKV 만들기 / QKV Creation

Vision Transformer에 대한 시각적 설명: 10.1. Transformer: QKV 만들기

Transformer 입력 패치 임베딩 벡터는 여러 큰 벡터에 선형적으로 임베딩됩니다. 이러한 새로운 벡터는 동일한 크기의 세 부분으로 분리됩니다. 이는 각각 Q는 쿼리(Query) 벡터, K는 키(Key) 벡터, V는 값(Value) 벡터입니다. 모든 벡터들을 (n+1)개씩 얻게 됩니다.

Our transformer input patch embedding vectors are linearly embedded into multiple large vectors. These new vectors are than separated into three equal sized parts. The Q - Query Vector, the K - Key Vector and the V - Value Vector . We will have (n+1) of a all of those vectors.

10.2. Transformer: 어텐션 스코어 계산하기 / Attention Score Calculation

Vision Transformer에 대한 시각적 설명: 10.2. Transformer: 어텐션 스코어 계산

먼저 어텐션 스코어 A를 계산하기 위해 모든 쿼리 벡터 Q에 모든 키 벡터 K를 곱합니다.

To calculate our attention scores A we will now multiply all of our query vectors Q with all of our key vectors K.

10.3. Transformer: 어텐션 스코어 매트릭스 / Attention Score Matrix

Vision Transformer에 대한 시각적 설명: 10.3. Transformer: 어텐션 스코어 매트릭스

이렇게 얻은 어텐션 스코어 행렬 A의 모든 행의 합이 1이 되도록 모든 행에 softmax 함수를 적용합니다.

Now that we have the attention score matrix A we apply a softmax function to every row such that every row sums up to 1.

10.4. Transformer: 집계된 컨텍스트 정보 계산하기 / Aggregated Contextual Information Calculation

Vision Transformer에 대한 시각적 설명: 10.4. Transformer: 집계된 컨텍스트 정보 계산

첫 번째 패치 임베딩 벡터에 대한 집계된 문맥 정보(aggregated contextual information) 를 계산하기 위해, 어텐션 행렬의 첫 번째 행에 대해서 연산을 합니다. 여기에 값 벡터 V의 가중치를 사용하여 첫 번째 이미지 패치 임베딩에 대한 집계된 문맥 정보 벡터(aggregated vector) 를 생성합니다.

To calculate the aggregated contextual information for the first patch embedding vector. We focus on the first row of the attention matrix. And use the entires as weights for our Value Vectors V. The result is our aggregated contextual information vector for the first image patch embedding.

10.5. Transformer: 모든 패치에 대해서 집계된 컨텍스트 정보 구하기 / Aggregated Contextual Information for every patch

Vision Transformer에 대한 시각적 설명: 10.5. Transformer: 모든 패치에 대해서 집계된 컨텍스트 정보 구하기

어텐션 스코어 행렬의 다른 행들에 대해서도 위 과정을 반복하여 N+1개의 집계된 문맥 정보 벡터를 구합니다. 즉, 모든 패치마다 하나씩 (=N개) + 분류 토큰(CLS Token)에 대해서 하나 (=1) 입니다. 여기까지 해서 첫번째 어텐션 헤드(Attention Head)를 구합니다.

Now we repeat this process for every row of our attention score matrix and the result will be N+1 aggregated contextual information vectors. One for every patch + one for the classification token. This steps concludes our first Attention Head.

10.6. Transformer: 멀티-헤드 어텐션 / Multi-Head Attention

Vision Transformer에 대한 시각적 설명: 10.6. Transformer: 멀티-헤드 어텐션

(Transformer의) 멀티-헤드 어텐션을 다루고 있으므로, 다른 QKV들에 대해서 10.1부터 10.5까지의 전체 프로세스를 반복합니다. 위 그림에서는 2개의 헤드만 가정했지만, 일반적으로 ViT는 더 많은 헤드를 갖습니다. 이렇게 여러 개의 집계된 문맥 정보 벡터(Multiple Aggregated Contextual Information Vectors)가 생성됩니다.

Now because we are dealing multi head attention we repeat the entire process from step 10.1 - 10-5 again with a different QKV mapping. For our explanatory setup we assume 2 Heads but typically a VIT has many more. In the end this results in multiple Aggregated contextual information vectors.

10.7. Transformer: 마지막 어텐션 레이어 단계 / Last Attention Layer Step

Vision Transformer에 대한 시각적 설명: 10.7. Transformer: 마지막 어텐션 레이어 단계

이렇게 생성한 여러 헤드들을 쌓은 뒤, 패치 임베딩의 크기와 같은 d 크기의 벡터로 매핑시킵니다.

These heads are stacked together and are mapped to vectors of size d which was the same size as our patch embeddings had.

10.8. Transformer: 어텐션 레이어 결과 구하기 / Attention Layer Result

Vision Transformer에 대한 시각적 설명: 10.8. Transformer: 어텐션 레이어 결과

이렇게 이전 단계로부터 어텐션 레이어가 완성되었고, 입력 시에 사용했던 것과 정확히 같은 크기의 임베딩들을 얻었습니다.

The previous step concluded the attention layer and we are left with the same amount of embeddings of exactly the same size as we used as input.

10.9. Transformer: 잔차 연결하기 / Residual connections

Vision Transformer에 대한 시각적 설명: 10.9. Transformer: 잔차 연결

Transformer에서는 잔차 연결(Residual Connection) 을 많이 사용하는데, 이것은 단순히 이전 레이어의 입력을 현재 레이어의 출력에 더해주는 것입니다. 여기서도 잔차 연결을 하겠습니다.

Transformers make heavy use of residual connections which simply means adding the input of the previous layer to the output the current layer. This is also something that we will do now.

10.10. Transformer: 잔차 연결 결과 구하기 / Residual connection Result

Vision Transformer에 대한 시각적 설명: 10.10. Transformer: 잔차 연결 결과

이러한 잔차 연결을 통해 (동일한 크기 d인 벡터들끼리 더하여) 같은 크기의 벡터가 생성됩니다.

The addition results in vectors of the same size.

10.11. Transformer: 피드-포워드 네트워크에 통과시키기 / Feed Forward Network

Vision Transformer에 대한 시각적 설명: 10.11. Transformer: 피드-포워드 네트워크

지금까지의 결과(output)를 비선형 활성함수를 갖는 피드 포워드 인공 신경망에 통과시킵니다.

Now these outputs are feed through a feed forward neural network with non linear activation functions

10.12. Transformer: 최종 결과 구하기 / Final Result

Vision Transformer에 대한 시각적 설명: 10.12. Transformer: 최종 결과

Transformer에는 지금까지 연산 이후로 또다른 잔차 연결이 있지만, 여기서는 설명을 간소화하기 위해 건너뛰고 Transformer 레이어 연산을 마무리하겠습니다. 최종적으로 Transformer는 입력 크기와 같은 출력을 생성합니다.

After the transformer step there is another residual connections which we will skip here for brevity. And so the last step concluded the transformer layer. In the end the transformer produced outputs of the same size as input.

11. Transformer 연산 반복하기 / Repeat Transformers

Vision Transformer에 대한 시각적 설명: 11. Transformer 연산 반복하기

지금까지 진행한 10.1부터 10.12까지의 전체 Transformer 연산을 수차례 반복합니다. 여기에서는 6번을 예시로 들었습니다.

Repeat the entire transformer calculation Steps 10.1 - Steps 10.12 for the Transformer several times e.g. 6 times.

12. 분류 토큰 출력 확인하기 / Identify Classification token output

Vision Transformer에 대한 시각적 설명: 12. 분류 토큰 출력 확인하기

마지막 단계는 분류 토큰(CLS token) 출력을 확인하는 것입니다. 이벡터는 Vision Transformer 여정의 마지막 단계에서 사용하게 됩니다.

Last step is to identify the classification token output. This vector will be used in the final step of our Vision Transformer journey.

13. 최종 단계: 분류 확률 예측하기 / Final Step: Predicting classification probabilities

Vision Transformer에 대한 시각적 설명: 13. 최종 단계: 분류 확률 예측하기

최종적이고 마지막 단계에서는 분류 출력 토큰을 완전 연결(fully-connected)된 또 다른 인공 신경망에 통과시켜 입력 이미지에 대한 분류 확률(classification probabilties)을 예측합니다.

In the final and last step we use this classification output token and another fully connected neural network to predict the classification probabilities of our input image.

14. Vision Transformer 학습하기 / Training of the Vision Transformer

앞에서 예측한 분류 확률(class probabilties)과 정답(true class label)을 비교하는 표준 크로스-엔트로피 손실 함수(Cross-Entropy Loss Function)을 사용하여 Vision Transformer를 학습합니다. 모델은 역전파(backpropagation) 및 경사 하강법(gradient descent)을 사용하여 손실 함수를 최소화하는 쪽으로 모델의 가중치를 갱신하며 학습합니다.

We train the Vision Transformer using a standard cross-entropy loss function, which compares the predicted class probabilities with the true class labels. The model is trained using backpropagation and gradient descent, updating the model parameters to minimize the loss function.

결론 / Conclusion

지금까지 시각적 설명을 통해 데이터 준비부터 모델 학습까지 Vision Transformer의 주요 구성 요소들을 살펴봤습니다. 이 설명을 통해 Vision Transformer가 어떻게 동작하는지와 이미지 분류에 어떻게 사용되는지를 이해하는데 도움이 되었기를 바랍니다.

In this visual guide, we have walked through the key components of Vision Transformers, from the data preparation to the training of the model. We hope this guide has helped you understand how Vision Transformers work and how they can be used to classify images.

Vision Transformer를 더 잘 이해할 수 있도록 작은 Colab Notebook도 준비해두었습니다. 'Blogpost'의 덧글도 살펴봐주세요. 이 코드는 @lucidrains의 훌륭한 ViT PyTorch 구현에서 가져온 것이니 그의 작업도 꼭 확인해봐주세요.

I prepared this little Colab Notebook to help you understand the Vision Transformer even better. Please have look for the 'Blogpost' comment. The code was taken from @lucidrains great VIT Pytorch implementation be sure to checkout his work.

질문이나 피드백이 있으시다면 언제든 연락주세요. 읽어주셔서 감사합니다! (저자의 GitHub, X(Twitter), Threads, LinkedIn)

If you have any questions or feedback, please feel free to reach out to me. Thank you for reading!

감사의 글 / Acknowledgements

  • All images have been taken from Wikipedia and are licensed under the Creative Commons Attribution-Share Alike 4.0 International license.

더 읽어보기

원문

요약 글

Vision Transformer 논문

PR12의 Vision Transformer 논문 리뷰 영상

Google Research의 Vision Transformer 저장소

PapersWithCode에서 정리한 Vision Transformer 관련 논문 및 코드 등




:pytorch:파이토치 한국 사용자 모임:kr:이 정리한 이 글이 유용하셨나요? 회원으로 가입하시면 주요 글들을 이메일:love_letter:로 보내드립니다! (기본은 Weekly지만 Daily로 변경도 가능합니다.)

:gift: 아래:arrow_lower_right:쪽에 좋아요:heart:를 눌러주시면 새로운 소식들을 정리하고 공유하는데 힘이 됩니다~ :star_struck:

3개의 좋아요

유익한 글 감사합니다 :wink:

1개의 좋아요

읽어주시고 덧글 남겨주셔서 감사합니다! :bowing_man: