-
패스트캠퍼스 환급챌린지 59일차 미션 (3월 30일) : 딥러닝·인공지능 Signature 초격차 패키지 Online. 강의 후기패스트캠퍼스 챌린지 2024. 3. 30. 16:37
자, 오늘은
Part7. 자연어처리
CH04-20. Transformer Encoder - Positional Encoding
&
CH04-21. Transformer Encoder - Multihead Self - Attention
CH04-20. Transformer Encoder - Positional Encoding
트랜스포머는 인코더와 디코더로 나뉘어지는데 우선 인코더에 대해서 알아보자
Attention is All you need
"어제 알아본 것처럼 RNN을 쓰지 않아도 되지 않을까?" 에서 시작된 의문으로 시작되었다.
기존의 RNN 계열의 시퀀스 투 시퀀스 가 인코더와 디코더를 갖고있는 부분을 그대로 차용하였고,
RNN의 경우 각 타임 스텝별로 단어가 입력으로 들어가기 때문에 순차적으로 단어를 처리하기 때문에 병렬적으로
연산이 불가했다.
반면 Attention 연산 자체는 RNN과 많이 쓰이기도 했고 또한 병렬 연산이 가능하기 때문에 이 Attention 매커니즘을
하나의 신경망으로 만들고 RNN을 제거해버리는게 이 transformer의 핵심이다.
트랜스포머 모델들 안에는?
인코더들이 들어있고, 디코더들이 들어있다.
들 이라고 함은, 인코더 1, 인코더 2, 인코더 3 이렇게 하나의 모듈(층)으로 구성된다.
1층부터 올라가는 구조고 인코더 1층부터 6층(예시로 6층이라고 하자) 으로 올라가면 이후 디코더의 1층부터 6층까지
다시 올라가는 구조다.
특이사항으로는 인코더의 6층의 값은 디코더의 1층부터 6층까지 매 층마다 이 값을 사용한다.
트랜스포머에 대해 좀더 자세하게 들여다보자.
트랜스 포머도 다른 딥 러닝 모델과 마찬가지로 Embedding Layer를 사용하고, 이 임베딩 레이어를 통해 얻은
임베딩 레이어를 인코더와 디코더로 사용한다.
임베딩 벡터에 Positional Encoding이라는 과정을 거친 후 입력으로 이용한다.
즉, 기존의 RNN(단어가 하나하나 들어가서 순차적으로 )과 다르게 문장이 통째로 들어간다.
여기서 RNN은 순서대로 들어가니까 단어의 순서, 즉 어디가 앞이고 어디가 뒤고를 알 수있지만
트랜스포머는 한방에 입력을 받다보니 단어의 순서를 알수 없으니 이때 포지셔널 인코딩 행렬(단어의 위치
정보를 기록해놓은 행렬) 을 만들어서 문장행렬을 똑같이 만들고 두개를 더해서
문장행렬과 포지셔널 인코딩 행렬을 트랜스포머에 넣는 것이다.
그러면 이 포지셔널 인코딩 행렬은 어떻게 만드는가?
Pos 와 i 를 알아야 한다.
Pos : 문장행렬에서의 네모칸 하나 위치의 좌표 역할
i: 차원
즉, 행 렬 로 이해하면 쉽다.
그러면 왜 Pos와 i가 필요할까?
포지셔녕 인코딩을 만들려면 위와 같은 수식이 필요하다.
짝수번째 위치는 위에꺼, 홀수번째는 아래껄 사용한다.(i 기준)
결론은 우리가 문장행렬을 그대로 트랜스포머에 넣는게 아니라 트랜스포머에 넣을려면 위치 정보를 담은 포지셔널
인코딩 행렬을 더해서 넣어줘야한다.(상기 수식을 통해서)
CH04-21. Transformer Encdoer - Multihead Self - Attention
트랜스포머에는 총 3가지 어텐션이 존재한다.
인코더에서 사용하는 인코더 셀프 어텐션, 디코더에서 사용하는 디코더 셀프 어텐션, 그리고
디코더에서 사용하는 인코더 디코더 어텐션이다.
인코더에 1개, 디코더에 1개, 인코더와 디코더를 연결하는 인코더 디코더 어텐션이 1개 총 3개다.
셀프어텐션
쿼리, 키, 밸류가 모두 동일한 경우 셀프 어텐션이라고 함.
인코더 디코더 어텐션의 경우에는 쿼리는 디코더 벡터인데, 키밸류는 인코더 벡터이기 때문에 셀프
어텐션이 아니다.
인코더 내부에는 총 2개의 서브층이 존재한다.
첫번째 서브층은 셀프 어텐션, 두번째 서브층은 포지션 와이즈 피드 포워드 신경망이다.
이런게 총 6개가 있으면 트랜스포머 인코더가 되는 것.
셀프어텐션이란?!
특정 하나의 단어가 있으면 이 단어와 다른 단어들에 대해서 단어와 단어 간의 연관성을 찾아내는게 셀프어텐션이다.
위의 이미지처럼 각 it이 무엇을 의미하는지 컴퓨터가 알려면 입력된 모든 단어와 자기자신인 잇과의 연관성을 찾아낸다.
이래서 셀프 어텐션인듯..함.
셀프어텐션은 사실
Attention(Q,K,V) = softmax(QK(트랜스포즈)/루트Dk)V
멀티헤드(Q,K,V) = Concat(head1, head2, .....)Wo
요롷게 512를 맞추기 위해(논문에서는) 여러개의 헤드를 붙혀서 만든다.
(이관점에서도 보고 저관점에서도 보고....무튼 아웃풋이 512가 되어야 하니깐... 다 붙혀버림)
어려운 개념이니 복습 꼭!
59일차 끝.
본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성하였습니다.
'패스트캠퍼스 챌린지' 카테고리의 다른 글