Transformer
Transformer Overview
Multi-head self-attention을 이용해 sequential computation을 줄여 더 많은 부분을 병렬처리가 가능하게 만들면서 동시에 더 많은 단어들 간 dependency를 모델링.
| Input je suis etudiant |
↓
| The Transformer |
↓
| Output I am a student |
Transformer box 내부


Encoding 부분은 여러 개의 encoder를 쌓아 올림 (논문에서는 6개)
→ 모두 정확히 똑같은 구조
Decoding 부분에서도 동일하게 decoder 쌓아 올림
Encoder 내부

Self-Attention layer: encoder가 하나의 특정한 word를 encode하기 위해 input 내의 모든 다른 word들과의 관계 파악
Feed Forward Neural Network: 각 위치의 word마다 독립적으로 적용돼 출력
Decoder 내부

Decoder의 두 layer + Encoder-Decoder Attention layer 추가
→ input sentence 중 각 time step에서 가장 관련 있는 부분 참고
Vector들의 Transformer Box 통과 과정
Input word → Embedding vector

각 word들은 크기 512의 vector 하나로 embed
Embedding vector들은 encoder 내 두 개의 sub-layer로 투입

각 position에 있는 각 word가 각 path를 통해 encoder에서 진행
Self-Attention layer에서 이 위치에 따른 path들 사이에 dependency 존재
Feed Forward layer에서는 이러한 dependency가 없어서 다양한 path들은 병렬처리

Self-Attention
e.g.) "그 동물은 길을 건너지 않았다. 왜냐하면 그것은 너무 피곤했기 때문이다."
→ '그것'word는 '동물'word와 연결할 수 있다.
Self-Attention은 input sequence 내 다른 position에 있는 word를 보고 힌트를 받아 현재 target position의 word를 더 잘 encoding.

Self-Attention의 연산 과정 (vector-level)
1. Embedding vector로부터 Query vector, Key voctor, Value vector 생성
→ Input vector에 대해 3개의 학습 가능한 행렬 곱


E.g.) X1 · W^Q = q1 vector 생성
2. Attention score 계산
Attention score = (현재 word의 query vector) · (score를 매기려 하는 다른 position의 word의 key vector)
이러한 score는 현재 position에서 이 word를 encode 할 때 다른 word들에 대해서 얼마나 attention할지 결정

3. Attention score을 key vector의 사이즈의 제곱근으로 나눗셈
→ 더 안정적인 gradient 가능

4. 3번의 값을 softmax에 통과시켜 모든 score를 양수로 만들고 합을 1로 변환
→ 현재 position의 word의 encoding에 있어 얼마나 각 word들의 표현이 들어갈 것인지 결정
(현재 위치의 word가 가장 높은 score)
5. Input의 각 word들의 value vector에 4번의 점수를 곱셈
→ Attention하고 싶은 word들은 남겨두고, 다른 word들은 0.001과 같은 작은 score를 곱해 제거
6. 5번의 score로 곱해진 weighted value vector들을 모두 합
→ 이를 통한 출력 = 현재 position에 대한 self-attention layer의 출력

이 결과로 나온 vector (z₁)을 feed-forward layer로 보내게 된다.
Scaled dot-product attention
Inputs: Query q와 Key-Value (k, v)
Output: Weighted sum of values
→ 각 value의 weight는 query와 그에 대응하는 key의 inner product로 계산

Self-Attention의 연산 과정 (Matrix-level)
1. Query, Key, Value Matrix들을 계산
입력 embedding vector들을 하나의 Matrix X로 쌓아 올리고, 학습할 weight Matrix (WQ, WK, WV)로 곱

Matrix X의 각 row = Input sequence의 각 word
2. 위에 vector-level Self-Attention과 동일한 연산 수행

→ Key의 dimension의 제곱근으로 QK^T Matrix를 나누어 줌으로써 scaling
"Multi-headed" attention mechanism
1. Model이 다른 position에 attention하는 능력 확장
2. Attention layer가 여러 개의 representation 공간 확보
→ Multi-head attention을 이용하여 여러 개의 query/key/value weight Matrix 확보 (논문에서는 8개)
각각 query/key/value set은 랜덤으로 initalize되어 학습
학습 된 후, 각 set은 입력 vector들에 곱해져 vector들을 각 목적에 맞게 투영
→ 여러개의 set 보유 = 각 vector들을 각각 다른 representation 공간으로 나타낸다.

→ 각 head에서 각각 다른 query/key/value weight Matrix 보유

Feed-forward layer는 한 position에 대해 한 개의 Matrix만을 input으로 받을 수 있으므로 ..
→ 모든 Matrix를 concat한 후, weight Matrix를 곱하여 투입

Mult-headed self-attention


Positional Encoding
Why use Positional Encoding?
| RNN, LSTM | Transformer |
| Seqeuntial 형태로 input | 병렬 형태로 input → Positional encoding 필요 - 학습 시간 감소, Long-term dependency 해결 - But, Sequential 정보 소멸 |
Transformer 에서 input sequence의 순서 정보 추가해주는 vector
각 입력 embedding vector에 positional encoding vector 추가
→ 각 word와 다른 word 간의 position 차이에 대한 정보
→ Positional encoding vector가 추가된 embedding vector는 query/key/va lue vector로 투영될 때 word들 간 distance를 늘릴 수 있다.

E.g.) embedding size = 4 일 시, 각 position에 따른 positional encoding

Sinusodial functions of diffenrent frequencies

Sinusodial Positional Encoding 계산 과정: Sinusoidal Positional Encoding 계산 예시 (tistory.com)
Sinusoidal Positional Encoding 계산 예시
RNN과 LSTM과 다르게 Transformer는 input X가 병렬 처리되어 투입된다. 병렬 구조의 투입은 연산 속도가 향상되고 long-term dependency 문제를 해결할 수 있지만, sentence의 sequential 한 정보가 제거된다는..
jdongy0.tistory.com
Residual connection
각 encoder 내의 sub-layer가 residual connection으로 연결 후, layer-normalization
LayerNorm(x + sublayer(x))

Layer-normalization 시각화

→ Decoder 내부의 sub-layer들에도 똑같이 적용
E.g) 2개의 encoder와 decoder로 이루어진 Transformer 형태

Layer Normalization
Input을 각 layer에서 mean=0으로, variance=1로 변환

1. Each word vector들을 mean=0, variance=1로 normalization
2. Each sequence vector들을 learnable paramter로 변환

Decoder
Encoding step
1. Encoder가 input sequence 처리
2. 가장 위의 encoder의 output은 attention vector인 K와 V로 변형
3. K와 V는 각 decoder의 'Encoder-Decoder attention' layer에서 decoder가 input sequence에 적절한 position에 attention하게 만든다.

Decoding step
1. Decoding 단계의 각 step은 출력 sequence의 한 element를 출력
2. Decoding step은 '<end of sentence>'를 출력할 때까지 반복
3. 각 step마다 출력된 word는 다음 step의 가장 밑의 decoder에 투입
(Encoder와 동일하게 embedding vector에 positional encoding 추가하여 위치 정보 보유)

Decoder에서의 Self-attention: Masked Multi-head self-attention
Output sequence 내에서 현재 position의 이전 position들에 대해서만 attend
→ Self-attention 계산 과정에서 softmax를 취하기 전, 현재 step 이후의 position은 masking
Encoder-Decoder Attention layer
Query Matrix들을 그 밑의 layer에서 가져오고
Key와 Value Matrix들은 Encoder의 output에서 가져와 계산
마지막 Linear layer와 Softmax layer
여러 decoder를 거친 후, 소수로 이루어진 vector 하나 출력
Linear layer: fully-connected 신경망으로 decoder가 마지막으로 출력한 vector를 훨씬 더 큰 size vector인 logits vector로 투영
(logits vector의 크기 = output vocabulary 크기)
Vector의 각 cell은 그에 대응하는 각 word에 대한 score가 된다.
→ Lonear layer의 결과로서 나오는 output에 대해 해석
Softmax layer: 위의 score들을 probability로 변환
→ 가장 높은 probability를 가지는 cell에 해당하는 word가 해당 step의 최종 output으로 출력

Attention weight를 게산할 때, key의 dimension의 제곱근으로 나누는 이유?


New Position Embedding Method

GeLU function

'Attention is All You Need' 논문에서는 ReLU 함수를 사용했지만, 최근 huge model에서는 GeLU function 사용

→ GeLU function은
1. 모든 점에서 미분 가능하고 (ReLU는 0에서 미분 불가능)
2. 단조 증가 함수가 아니어서(non-convex) 복잡도가 더 높다.
3. Standard Gaussian Comulative distribution function
Reference
The Illustrated Transformer – NLP in Korean – Anything about NLP in Korean
The Illustrated Transformer
저번 글에서 다뤘던 attention seq2seq 모델에 이어, attention 을 활용한 또 다른 모델인 Transformer 모델에 대해 얘기해보려 합니다. 2017 NIPS에서 Google이 소개했던 Transformer는 NLP 학계에서 정말 큰 주목을
nlpinkorean.github.io
Attention is All You Need
[1706.03762] Attention Is All You Need (arxiv.org)
Attention Is All You Need
The dominant sequence transduction models are based on complex recurrent or convolutional neural networks in an encoder-decoder configuration. The best performing models also connect the encoder and decoder through an attention mechanism. We propose a new
arxiv.org
Transformer: A Novel Neural Network Architecture for Language Understanding
Posted by Jakob Uszkoreit, Software Engineer, Natural Language Understanding Neural networks, in particular recurrent neural networks (RN...
ai.googleblog.com
'NLP' 카테고리의 다른 글
| BERT (0) | 2022.07.01 |
|---|---|
| Sinusoidal Positional Encoding 직접 계산해보기 (0) | 2022.07.01 |
| Tokenization (0) | 2022.06.28 |
| Basic Regular expression 연습 (0) | 2022.06.27 |
| NLP preprocessing (0) | 2022.06.27 |