1 of 49

Transformer 모델 (1): Self-Attention

2 of 49

수업 목표

이번 수업의 핵심:

  • Self-attention의 개념
  • Scaled dot-product attention 계산과 원리의 이해
  • Multi-head attention의 필요성과 적용 방법

핵심 개념

  • Self-attention
  • Scaled dot-product attention
  • Multi-head attention

3 of 49

Transformer 개요

Attention is all you need

  • 더 이상 RNN, CNN 모듈을 사용하지 않음

Vaswani et al. “Attention Is All You Need”. NIPS. 2017.

3

ENCODER

DECODER

ENCODER

DECODER

ENCODER

DECODER

ENCODER

DECODER

ENCODER

DECODER

ENCODER

DECODER

I go to school

입력

나는 학교에 간다

출력

4 of 49

RNN을 통한 인코딩 방식

  •  

4

 

 

 

 

 

 

 

 

 

 

입력

출력

Forward

RNN

Backward

RNN

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

5 of 49

Query, Key, Value in Hash Table

  •  

5

Key

(동물)

Value

(다리 개수)

강아지

4

2

문어

8

오징어

10

고양이

4

 

6 of 49

Self-Attention

Vaswani et al. “Attention Is All You Need”. NIPS. 2017.

6

 

 

 

Softmax

 

 

 

 

 

 

 

 

 

 

 

 

 

나는

학교에

간다

3.8

-0.2

5.9

0.7

0.1

0.2

7 of 49

Dot-Product Attention

  •  

7

8 of 49

Self-Attention의 선형 변환 예시

Vaswani et al. “Attention Is All You Need”. NIPS. 2017.

8

 

 

 

Softmax

 

 

 

 

 

 

 

 

 

 

 

 

 

나는

학교에

간다

3.8

-0.2

5.9

0.7

0.1

0.2

Embedding

입력

학교에

간다

 

 

Queries

 

 

Keys

 

 

Values

 

 

 

 

 

 

 

 

 

 

 

 

 

 

9 of 49

Dot-Product Attention for Query Batch

  •  

9

 

 

 

 

 

 

 

 

 

Row-wise

Softmax

 

 

 

 

 

10 of 49

Scaled Dot-Product Attention

  •  

Vaswani et al. “Attention Is All You Need”. NIPS. 2017.

10

11 of 49

Scaled Dot-Product Attention

11

 

입력

학교에

간다

Embedding

 

 

Queries

 

 

Keys

 

 

Values

 

 

Attention score

 

 

 

 

Softmax output

 

 

가중합

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

12 of 49

Multi-Head Attention

  •  

Vaswani et al. “Attention Is All You Need”. NIPS. 2017.

12

13 of 49

Multi-Head Attention

13

 

 

 

 

 

 

Attention Head #0

 

 

 

 

 

 

Attention Head #1

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Attention Head #7

 

 

 

 

 

 

 

14 of 49

Multi-Head Attention

14

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Concatenation

15 of 49

Multi-Head Attention

15

 

 

 

 

 

 

 

1) 문장 입력

학교에

간다

2) 각 단어를Embedding

 

 

 

  • 첫번째 Encoder 층을 제외하고는 Embedding이 필요하지 않음

🡪 이전 Encoder 층의 출력 사용

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

16 of 49

Self-Attention 시각화

Attention distribution 시각화

  • 각 단어가 어느 다른 단어에 집중하는지 확인할 수 있음

16

다른 Head를 의미

17 of 49

Self-Attention 시각화

Attention distribution 시각화

  • 각 단어가 어느 다른 단어에 집중하는지 확인할 수 있음

17

18 of 49

Self-Attention 비교

  •  

Vaswani et al. “Attention Is All You Need”. NeurIPS. 2017.

18

19 of 49

요약

  • RNN 구조의 문제점과 이를 해결하기 위한 Self-attention의 개념
  • Dot-product attention의 계산과 Scaled dot-product의 적용
  • Multi-head attention의 필요성과 구조 이해
  • Self-attention 시각화와 Convolutional/Recurrent 모듈과의 장단점

19

20 of 49

Transformer 모델 (2): 기타 구성 요소

21 of 49

수업 목표

이번 수업의 핵심:

  • Transformer block의 여러 구성 요소
  • Positional embedding의 필요성과 Sinusoidal positional embedding
  • Transformer decoder의 Masked self-attention & Cross attention

핵심 개념

  • Layer normalization
  • Positional embedding, Sinusoidal positional encoding
  • Masked attention
  • Cross attention

22 of 49

Transformer 개요

Attention is all you need

  • 더 이상 RNN, CNN 모듈을 사용하지 않음

Vaswani et al. “Attention Is All You Need”. NIPS. 2017.

22

ENCODER

DECODER

ENCODER

DECODER

ENCODER

DECODER

ENCODER

DECODER

ENCODER

DECODER

ENCODER

DECODER

I go to school

입력

나는 학교에 간다

출력

23 of 49

Transformer의 Block

  •  

저자의 성 et al. “논문 이름”. 학회/저널 별칭. 년도. 링크.

23

24 of 49

Layer Normalization

  •  

Ba et al. “Layer Normalization”. ArXiv. 2016. https://arxiv.org/abs/1607.06450.

Wu et al. “Group Normalization”. ECCV. 2018.

24

25 of 49

Layer Normalization

  1. 각 단어 벡터를 Normalization하여 평균과 분산을 0과 1로 변환
  2. 각 차원 별로 학습 가능한 Parameter Affine transformation

Ba et al. “Layer Normalization”. ArXiv. 2016. https://arxiv.org/abs/1607.06450.

25

4

2

3

-3

2

1

5

2

학교에 갑니다

학교에 갑니다

학교에 갑니다

0.65

0.7

-1.35

-0.3

-0.45

-1.5

1.25

1.1

 

 

 

 

 

 

 

 

2.95

3.1

1.35

0.3

0.55

-0.5

-0.5

-0.2

 

 

 

 

26 of 49

Positional Encoding

  • Transformer 블록은 Permutation-invariant
    • 입력 순서가 뒤바뀌어도 똑같은 출력이 나옴

  • 따라서, Transformer 모델이 같은 단어들로 이루어진 입력 Sequence에 대해서도, 서로 다른 어순을 구별하도록 하기 위해, 각 단어에 현재 위치 정보를 넣을 필요가 있음
  • 원 Transformer 논문에선 Sinusoidal function을 활용
  • 학습 가능한 Positional embedding을 사용하기도 함

Vaswani et al. “Attention Is All You Need”. NIPS. 2017.

26

27 of 49

Sinusoidal Positional Encoding

  •  

Vaswani et al. “Attention Is All You Need”. NIPS. 2017.

27

28 of 49

Decoder

Masked attention

  • Causal attention이라고도 부름
  • Self-attention이 과거 생성 결과에 대해서만 집중

Cross attention

  • Encoder-decoder 간의 attention
  • Query: Decoder의 Causal-attention 결과
  • KeyValue: Encoder의 출력

Vaswani et al. “Attention Is All You Need”. NIPS. 2017.

28

29 of 49

Masked Attention

  • 아직 생성되지 않은 단어는 추론 과정 중엔 접근할 수 없음
  • Softmax 출력을 수정하여 아직 생성되지 않은 단어에 접근을 못하게 함

Vaswani et al. “Attention Is All You Need”. NIPS. 2017.

29

Query: <SOS>

Key: <SOS>

Query: <SOS>

Key: 학교

Query: 나는

Key: 학교

Query

Key

<SOS>

나는

학교에

<SOS> 나는 학교에

<SOS>

나는

학교에

간다

나는

학교에

Transformer (Decoder)

 

 

 

<SOS>

나는

학교에

<SOS> 나는 학교에

30 of 49

Masked Attention

  • 아직 생성되지 않은 단어는 추론 과정 중엔 접근할 수 없음
  • Softmax 출력을 수정하여 아직 생성되지 않은 단어에 접근을 못하게 함

Vaswani et al. “Attention Is All You Need”. NIPS. 2017.

30

<SOS>

나는

학교에

간다

나는

학교에

Transformer (Decoder)

Query: <SOS>

Key: <SOS>

Query: <SOS>

Key: 학교

Query: 학교

Key: 나는

Query: 나는

Key: 학교

0.91

0.42

0.25

0.05

0.47

0.31

0.04

0.11

0.44

<SOS>

나는

학교에

<SOS>

나는

학교에

2.01

0.84

0.29

-0.94

0.96

0.48

-1.18

-0.49

0.84

Softmax

<SOS>

나는

학교에

<SOS>

나는

학교에

31 of 49

Masked Attention

  • 아직 생성되지 않은 단어는 추론 과정 중엔 접근할 수 없음
  • Softmax 출력을 수정하여 아직 생성되지 않은 단어에 접근을 못하게 함

Vaswani et al. “Attention Is All You Need”. NIPS. 2017.

31

<SOS>

나는

학교에

간다

나는

학교에

Transformer (Decoder)

Query: <SOS>

Key: <SOS>

Query: <SOS>

Key: 학교

Query: 학교

Key: 나는

Query: 나는

Key: 학교

1.00

0.47

0.25

0

0.53

0.31

0

0

0.44

<SOS>

나는

학교에

<SOS>

나는

학교에

2.01

0.84

0.29

-0.94

0.96

0.48

-1.18

-0.49

0.84

Softmax

<SOS>

나는

학교에

<SOS>

나는

학교에

 

 

 

32 of 49

Masked Attention

  • 아직 생성되지 않은 단어는 추론 과정 중엔 접근할 수 없음
  • Softmax 출력을 수정하여 아직 생성되지 않은 단어에 접근을 못하게 함

Vaswani et al. “Attention Is All You Need”. NIPS. 2017.

32

 

 

 

 

Query

Key

<SOS>

나는

학교에

<SOS> 나는 학교에

Value

Value

<SOS>

나는

학교에

<SOS> 나는 학교에

1.00

0.47

0.25

0

0.53

0.31

0

0

0.44

 

33 of 49

실험 결과

  • 영어-독일어/프랑스어 번역 결과 (newstest2014 데이터셋)

Vaswani et al. “Attention Is All You Need”. NIPS. 2017.

33

34 of 49

요약

  • Attention, MLP, Layer normalization 등 Transformer 모델의 구성요소
  • Layer normalization와 Batch normalization의 차이점
  • Transformer 블록의 Permutation invariance와 Positional embedding
  • Transformer decoder에서의 Masked attention의 원리와 적용

34

ENCODER

DECODER

ENCODER

DECODER

ENCODER

DECODER

ENCODER

DECODER

ENCODER

DECODER

ENCODER

DECODER

I go to school

입력

나는 학교에 간다

출력

35 of 49

Transformer 기반 Computer Vision 모델 구조�ViT

36 of 49

수업 목표

이번 수업의 핵심:

  • 컴퓨터 비전 문제에서 Transformer 모델을 적용한 Vision transformer 이해

핵심 개념

  • Vision Transformer
  • Pretraining, Fine-tunning, Transfer learning

37 of 49

컴퓨터 비전을 위한 Transformer

  • Transformer 구조는 NLP에서 가장 널리 쓰이는 모델로 사용됨
  • 반면, Computer Vision 분야에서는 CNN 구조를 주로 사용

이미지 처리를 위해서 Transformer 구조를 사용할 수 있을까?

Vaswani et al. “Attention Is All You Need”. NIPS. 2017.

Dosovitskiy et al. “An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale”. ICLR. 2021.

37

Convolutional

Neural Network

Transformer

38 of 49

Pixel-Level Transformer

이미지 처리를 위해서 Transformer 구조를 사용할 수 있을까?

  • 이미지의 픽셀을 토큰으로 간주
  • 일반적인 Transformer encoder의 입력으로 사용

38

Transformer Encoder

출력

이미지 픽셀

39 of 49

Pixel-Level Transformer의 문제점

  •  

39

 

 

Self-attention 행렬

40 of 49

Patch-Level Transformer

  •  

Dosovitskiy et al. “An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale”. ICLR. 2021.

Image credit: https://www.pexels.com/photo/cute-cat-sitting-outdoors-on-grass-and-looking-up-7149465/ CC0

40

41 of 49

Vision Transformer (ViT)

  •  

Dosovitskiy et al. “An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale”. ICLR. 2021.

41

 

 

42 of 49

Vision Transformer (ViT)

  •  

Dosovitskiy et al. “An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale”. ICLR. 2021.

42

Positional embedding

 

 

43 of 49

Vision Transformer (ViT)

  •  

Dosovitskiy et al. “An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale”. ICLR. 2021.

43

Positional embedding

Transformer Encoder

Special Token

([CLS] token)

 

 

44 of 49

Vision Transformer (ViT)

Dosovitskiy et al. “An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale”. ICLR. 2021.

44

Positional embedding

Transformer Encoder

Special Token

([CLS] token)

 

 

45 of 49

Vision Transformer (ViT)

Dosovitskiy et al. “An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale”. ICLR. 2021.

45

Positional embedding

Transformer Encoder

Special Token

([CLS] token)

  1. Linear layer로최종 예측

고양이

 

 

46 of 49

Vision Transformer (ViT)

  • JFT-300M에서 사전 학습(Pretraining)을 진행
    • JFT-300M: 18,000개 Class와 3억 개 이상의 고화질 이미지로 구성된 데이터셋
  • 이후, 각각의 데이터에서 Fine-tuning한 후 분류 정확도 측정
    • 모든 benchmark에서 당시 최신 모델인 ResNet 기반 BiT-L의 기록을 갱신

  • 모델 뒤의 숫자는 이미지 Patch의 크기를 나타냄
    • Patch 크기가 작을수록 모델의 사이즈가 증가
  • CNN 모델에 비해 연산량이 적어 효율적이고, 학습도 빠르게 수행

Dosovitskiy et al. “An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale”. ICLR. 2021.

46

47 of 49

Transfer Learning

Pretraining (사전 학습)

  • 대규모 데이터 및 이를 통한 별도의 태스크를 통해 모델을 사전에 학습

Transfer learning (전이 학습)

  • 사전 학습된 모델을 Target task에 대해 Fine-tuning하는 방법론
    • Target task는 Downstream task, Fine-tuning task라고도 불림
  • 사전학습을 위해 사용된 모델 일부는 Target task용 모듈로 대체하기도 함

47

입력 A

Task A

입력 B

Task B

Backprop

Transfer

Learning

Pretrained model

48 of 49

Vision Transformer (ViT)의 장점

  • ViT의 경우, CNN의 특징인 인접한 영역만을 반영하는 Inductive bias가 없음
  • JFT-300M 같은 ImageNet보다 대규모의 데이터로 학습을 할 경우,

ResNet 기반의 모델보다 더 좋은 성능을 보임

Dosovitskiy et al. “An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale”. ICLR. 2021.

48

49 of 49

요약

  • Computer vision 분야에서의 Transformer 모델의 적용
  • Vision transformer의 구조 및 학습 방법과 그 활용

49

Transformer Encoder