theory/NLP

Transformer

아르르르를를르 2022. 2. 4. 14:26

    배경

    seq2seq를 처리하기 위해 기존 모델들은 recurrent model로 long-term dependency에 취약했다.

    긴 문장에 어떤 정보와 다른 정보 사이의 거리가 멀때 해당 정보를 이용하지 못하는 문제가 발생했다.

    transformer는 recurrence를 사용하지 않고 attention mechanism만 사용해 input과 output의 dependency를 포착한다.

    recurrence : neural network에서 다음 step으로 넘어갈 때 출력 결과가 이전 계산 결과에 영향을 받는(=되풀이)

     

    특징

    recurrence와 convolution을 제거하고 attention을 사용하여 병렬처리를 가능케 하였다.

    key paper

    Encoder (좌측)

    N개의 동일한 layer로 구성되어 있으며, 각각의 layer는 2개의 sub-layer, multi-head self-attention, position-wise fully connected feed-forward network를 가지고 있다. 이때 sub-layer에 residual connection을 이용한다.

    residual connection : layer를 skip하고 input을 후반부로 그대로 보냄

    https://towardsdatascience.com/what-is-residual-connection-efb07cab0d55

     

    Decoder (우측)

    N개의 동일한 layer로 구성되어 있다. encoder와 달리 순차적으로 결과를 만들어내야 하기 때문에 self-attention을 masking을 사용하도록 변형한다. 시점 t 이후의 position에 attention을 주지 못하게 하여 기존 output들에만 의존하도록 한다.

     

    Embeddings and Softmax

    임베딩 값을 고정하지 않고 학습하면서 변형되는 learned embedding을 사용했다.

    decoder output을 다음 token의 확률로 바꾸기 위해 learned linear transformation과 softmax 함수를 사용했다.

     

    Attention

    Scaled Dot-Product Attention

    모든 query과 key에 대해 dot-product를 계산하고 각각을 scaling 하여 scaled dot-product attention값을 구한다. 여기에 softmax를 적용해 value들에 대한 weights를 얻어낸다. (scaling를 해주는 이유는 dot-products 값이 커질수록 softmax 함수의 기울기 변화가 거의 없기 때문이다.)

     

    Transformer의 3가지 attention

    transformer에서는 3가지 attention을 사용한다. self-attention은 q, k, v가 동일한 경우를 말하여 3번째 Encoder-Decoder attention은 self-attention이 아니다.

     

    https://wikidocs.net/31379

    encoder self-attention layer

    key, value, query들은 모두 encoder의 이전 layer의 output에서 온다. 따라서 이전 layer의 모든 position에 attention을 줄 수 있다. 첫번째 layer라면 positional encoding이 더해진 input embedding이 된다.

     

    decoder self-attention layer

    i번째 output을 다시 i+1번째 input으로 사용하는 auto-regressive 특성을 위해 masking out 된 scaled dot-product attention을 적용했다.

    query가 decoder layer의 output인 이유는 query라는 것이 조건에 해당하기 때문이다. 좀 더 풀어서 설명하면, ‘지금 decoder에서 이런 값이 나왔는데 무엇이 output이 돼야 할까?’가 query인 것이다.

    https://wikidocs.net/31379

     

    Position-wise Feed-Forward Networks

    encoder와 decoder의 layer는 모두 fully connected feed-forward network를 포함한다.

    position 마다, 즉 개별 단어마다 적용되기 때문에 position-wise이다. network는 두 번의 linear transformation과 activation function ReLU로 이루어져 있다.

     

    Positional Encoding

    transformer는 recurrence와 convolution을 사용하지 않아 단어의 seqence를 이용하기 위해서 단어의 position에 대한 정보를 추가해주어야 한다. 그래서 encoder와 decoder의 input embedding에 positional encoding(동일차원)을 더해준다. 논문에서는 다른 frequency를 가지는 sin과 cos 함수를 이용했다.

     

     

    참고:

     

     

     

    Uploaded by Notion2Tistory v1.1.0

    'theory > NLP' 카테고리의 다른 글

    [머신러닝 기초] 학습 유형  (0) 2023.05.07
    [머신러닝 기초] entropy, binary cross entropy, KL divergence  (0) 2022.09.26
    BERT  (0) 2022.02.04
    퍼셉트론(perceptron)  (0) 2022.01.17
    sparql이란?  (0) 2021.03.22