https://arxiv.org/abs/1409.0473
Neural Machine Translation by Jointly Learning to Align and Translate
Neural machine translation is a recently proposed approach to machine translation. Unlike the traditional statistical machine translation, the neural machine translation aims at building a single neural network that can be jointly tuned to maximize the tra
arxiv.org
Attention Mechanism이란
Seq2Seq 모델의 한계를 해결하기 위해 Neural Machine Translation by Jointly Learning to Align and Translate, 2014 논문에서 제안된 Attention 기법이며, NLP 영역에서 필수로 알아야하는 메커니즘이다.
Seq2Seq 모델은 Encoder에서 입력 시퀀스를 Context Vector(하나의 고정된 크기의 벡터)로 압축하고, Decoder는 이 Context Vector를 통해 출력 시퀀스를 만드는 구조로 크게 두 가지 문제가 있다.
1. 하나의 고정된 크기의 벡터인 Context Vector로 모든 정보를 압축하는 과정에서 정보 손실 발생
2. RNN의 고질적인 문제인 Vanishing Gradient(기울기 소실) 문제가 발생
이러한 한계점들로 인하여 Seq2Seq 모델은 기계 번역 분야에서 입력 문장이 길면 번역 품질이 떨어지는 현상이 나타나 이를 보정하기 위해 등장한 기법 Attention Mechanism(어텐션 메커니즘)이다.
어텐션(Attention)의 아이디어
- Decoder에서 출력 단어를 예측하는 매 시점(time step)마다, Encoder에서의 전체 입력 문장을 다시 한 번 참고한다는 점
- 참고하는 과정에서 입력 문장을 전부 동일한 비율로 참고하는 것이 아닌, 해당 시점(step)에서 예측해야할 단어와 연관이 있는 입력 단어 부분을 좀 더 집중(attention)해서 보게 되는 방식
- 입력 문장의 모든 단어를 동일한 가중치 비율로 참고하지 않고, 예측해야할 문장에서 해당 시점에 대응하는 연관이 있는 단어들에 더 많은 가중치를 부여
- 지금 당장 예측해야할 단어에 도움이 되는 입력 데이터에 집중(Attention)
어텐션 함수(Attention Function) => Attention(Q, K, V) = Attention Value
Attention Function은 입력 시퀀스의 각 단어들에 대한 가중치를 계산하는 함수이다. 이 함수는 각 단어의 중요도를 측정하여 출력 결과에 반영한다.
Attention Function은 크게 세 가지 요소(Q, K, V)로 구성된다.
Q : Query 는 현재 출력 단어를 나타내는 벡터(t 시점의 Decoder Cell에서의 hidden state)
K : Key는 입력 시퀀스의 각 단어에 대응하는 벡터(모든 시점의 Encoder Cell의 hidden state)
V : Value는 입력 시퀀스의 각 단어에 대응하는 벡터(모든 시점의 Encoder Cell의 hidden state) (유사도 반영)
중요.
Key와 Value는 같은 값이 아닌가 의문이 들 수 있다. Key와 Value는 같은 값이 맞다. 그렇지만 Key는 가중치를 계산하기 위해 사용되며, Value는 계산된 가중치가 반영되는 값이다. 역할 차이라고 볼 수 있다.
Attention Function은 Query 벡터와 Key 벡터 간의 유사도를 측정한다. 이 유사도는 내적, 외적 등 다양한 방법으로 계산될 수 있다. 이후 유사도를 정규화 하여 각 단어의 가중치를 계산한다. 이 가중치는 Value 벡터와 곱해져 최종 출력 벡터가 생성된다.
Dot-Product Attention(Luong Attention)
https://arxiv.org/abs/1508.04025
Effective Approaches to Attention-based Neural Machine Translation
An attentional mechanism has lately been used to improve neural machine translation (NMT) by selectively focusing on parts of the source sentence during translation. However, there has been little work exploring useful architectures for attention-based NMT
arxiv.org
다양한 Attention 종류 중에서 가장 이해하기 쉬운 Effective Approaches to Attention-based Neural Machine Translation, 2015 논문에서 제안된 Dot-Product Attention으로 Attention의 동작 원리를 이해해보자.
위 그림에서, Decoder(초록색)의 세 번째 LSTM셀에서 출력 단어를 예측할 때, Attention 메커니즘을 사용하는 모습이다. 참고할 입력단어들은 softmax 함수를 거친 각 단어의 결과값들의 묶음(초록 삼각형)이다.
1) Attention Score(어텐션 스코어) 계산
Attention Mechanism은 Decoder에서 출력 결과를 예측할 때, Encoder의 Hidden State들을 다시 한 번 참고해주는 방법이다. 이 때, 어느 Encoder의 Hidden State를 얼마나 참고할지를 결정해야 한다. 현재 예측에 필요한 정도라고 판단되는 점수를 어텐션 스코어 (Attention Score)라고 한다.
Dot-Product Attention에서의 스코어 값은 St를 전치(transpose)하여 나온 StT 각 은닉 상태와 내적(dot product)을 수행합니다. 즉, 모든 어텐션 스코어 값은 스칼라입니다. Attention Score들의 묶음을 $ e^{t} $라고 정의한다.
$$ e^{t}=[s_{t}^Th_{1},...,s_{t}^Th_{N}] $$
2) Attention Distribution(어텐션 분포) 생성
Attention Distribution(어텐션 분포) : $e^t$에 softmax 함수를 적용해 얻은 확률 분포
Attention Distribution은 $α^t$라고 한다.
$α^t = softmax(e^t)$
Attention Weight(어텐션 가중치) : 어텐션 분포의 각각의 값
※ softamx 함수는 입력받는 값을 모두 0 ~ 1 사이의 값으로 정규화하며 총합은 항상 1이 된다 ※
이렇게 구한 어텐션 분포(Attention Distribution)는 각 인코더 Hidden State의 중요도라고 볼 수 있다.
Ex) I : 0.1(10%), am : 0.4(40%), a : 0.1(10%), student : 0.4(40%)
3)Attention Value(=Context vector)
softmax를 통해 얻은 Attention Distribution(어텐션 분포)를 각 Encoder hidden state와 곱해준다.(Broadcasting)
각 어텐션 분포와 곱을 통해 얻어진 Hidden state들을 전부 더해준다.
즉, 가중합(Weighted Sum)을 진행
Attention Value를 $a_{t}$라고 하며, Context Vector라고도 한다.(Seq2Seq의 Context Vector와 대조된다.)
$a_{t}=\sum_{i=1}^{N} α_{i}^{t}h_{i} $
4) Attention Value(=Context Vector)를$ s_t $와 결합(Concatenation)
Attention Value(Context Vector)와 현 시점의 Decoder Cell의 hidden state($ s_t $) 결합(concatenate)하여 하나의 벡터 $ v_t $로 만든다.
5) Feedforward Network를 통해 다음 단어를 예측
- Seq2Seq 모델에서는 Decoder의 마지막 hidden state를 그대로 ouput layer의 입력으로 사용하여 다음 단어에 대한 확률을 계산
- Attention Mechanism을 적용한 Seq2Seq 에서의 output layer에 $ v_t $를 가중치행렬과 곱한 후, tanh 함수를 지나도록하여 $ \tilde{{s}}_{t} $를 얻음
- 계산 결과를 출력 층의 입력으로 사용하여 단어 예측 확률을 얻음
$ \mathbf{W_{c}} $는 학습 가능한 가중치 행렬, $ b_{c} $는 편향이다.
$ \tilde{s}_{t} = \tanh(\mathbf{W_{c}}[{a}_t;{s}_t] + b_{c}) $
$ \widehat{y}_t $는예측 벡터이다.
$ \widehat{y}_t = \text{Softmax}\left( W_y\tilde{s}_t + b_y \right) $
Attention의 종류
Attention은 스코어를 구하는 중간 수식의 차이에 따라 달라지며, 크게 개념을 벗어나지 않는다. Attention의 다양한 종류 중 간단히 설명을 하겠다. Dot-Product Attention(Luong Attention), Multi-Head Attention, Additive Attention(Bahdanau Attention), 그리고 Self-Attention 등이 있다. Dot-Product Attention(Luong Attention) 은 내적 연산을 사용하여 유사도를 계산하며, Additive/Concat Attention(Bahdanau Attention) 은 Query와 Key를 선형 변환 후 비선형 활성화 함수를 적용해 유사도를 계산하는 방식이다. Multi-Head Attention은 여러 개의 Query, Key, Value 벡터를 사용하여 각각의 가중치를 계산한 후 이를 결합하여 다양한 표현력을 학습하는 방법이다. Self-Attention은 입력 시퀀스 내의 모든 위치 간 관계를 학습하여, 각 요소가 전체 컨텍스트를 반영할 수 있도록 돕는다.
참조 :
15-01 어텐션 메커니즘 (Attention Mechanism)
앞서 배운 seq2seq 모델은 **인코더**에서 입력 시퀀스를 컨텍스트 벡터라는 하나의 고정된 크기의 벡터 표현으로 압축하고, **디코더**는 이 컨텍스트 벡터를 통해서 출력 …
wikidocs.net
Visualizing A Neural Machine Translation Model (Mechanics of Seq2seq Models With Attention)
Translations: Chinese (Simplified), French, Japanese, Korean, Persian, Russian, Turkish, Uzbek Watch: MIT’s Deep Learning State of the Art lecture referencing this post May 25th update: New graphics (RNN animation, word embedding graph), color coding, el
jalammar.github.io
https://devopedia.org/attention-mechanism-in-neural-networks#qst-ans-2
Attention Mechanism in Neural Networks
In machine translation, the encoder-decoder architecture is common. The encoder reads a sequence of words and represents it with a high-dimensional real-valued vector. This vector, often called the context vector, is given to the decoder, which then genera
devopedia.org
'DL > NLP' 카테고리의 다른 글
Seq2Seq를 활용한 논리연산(AND, OR, XOR) (0) | 2024.11.08 |
---|---|
Seq2Seq : Sequence to Sequence (0) | 2024.10.14 |
LSTM, GRU 간단 정리 (5) | 2024.10.08 |
RNN (0) | 2024.10.08 |