無知

갈 길이 먼 공부 일기

기술 공부/AI

트랜스포머 개요와 종류 | Formal Algorithms for Transformers

moozii 2022. 10. 18. 21:30

Formal Algorithms for Transformers
Mary Phuong and Marcus Hutter, DeepMind

 

이 글은 아래 논문을 번역하고, 관련 단어들을 리서치하며, 트랜스포머의 기본 개념에 대해 탐구하는 글입니다. 

 

https://arxiv.org/pdf/2207.09238.pdf

 


This document aims to be a self-contained, mathematically precise overview of transformer architectures and algorithms (not results). It covers what transformers are, how they are trained, what they are used for, their key architectural components, and a preview of the most prominent models. The reader is assumed to be familiar with basic ML terminology and simpler neural network architectures such as MLPs.

 

이 문서는 트랜스포머의 아키텍처 및 알고리즘에 대한 자기 충족적이고, 수학적으로 정확한 개요를 목표로 한다. 트랜스포머의 개념부터, 어떻게 학습하는지, 무슨 용도로 사용되는지, 주요 아키텍처 구성 요소 및 가장 유명한 모델들에는 무엇이 있는지 등을 다룬다. 독자는 기본적인 ML 용어 및 MLP와 같은 단순한 신경망 구조를 알고 있다고 가정한다.

 

 

 

 

1. Introduction

 

시퀀스-투-시퀀스(Sequence-to-Sequence, seq2seq)

시퀀스-투-시퀀스(Sequence-to-Sequence, seq2seq)는 입력된 시퀀스로부터 다른 도메인의 시퀀스를 출력하는 다양한 분야에서 사용되는 모델입니다. 예를 들어 챗봇(Chatbot)과 기계 번역(Machine Translation)이 그러한 대표적인 예인데, 입력 시퀀스와 출력 시퀀스를 각각 질문과 대답으로 구성하면 챗봇으로 만들 수 있고, 입력 시퀀스와 출력 시퀀스를 각각 입력 문장과 번역 문장으로 만들면 번역기로 만들 수 있습니다. 그 외에도 내용 요약(Text Summarization), STT(Speech to Text) 등에서 쓰일 수 있습니다.

seq2seq는 크게 인코더와 디코더라는 두 개의 모듈로 구성됩니다. 인코더는 입력 문장의 모든 단어들을 순차적으로 입력받은 뒤에 마지막에 이 모든 단어 정보들을 압축해서 하나의 벡터로 만드는데, 이를 컨텍스트 벡터(context vector)라고 합니다. 입력 문장의 정보가 하나의 컨텍스트 벡터로 모두 압축되면 인코더는 컨텍스트 벡터를 디코더로 전송합니다. 디코더는 컨텍스트 벡터를 받아서 번역된 단어를 한 개씩 순차적으로 출력합니다.

https://wikidocs.net/24996 
어텐션 메커니즘 (Attention Mechanism)

앞서 배운 seq2seq 모델은 인코더에서 입력 시퀀스를 컨텍스트 벡터라는 하나의 고정된 크기의 벡터 표현으로 압축하고, 디코더는 이 컨텍스트 벡터를 통해서 출력 시퀀스를 만들어냈습니다. 하지만 이러한 RNN에 기반한 seq2seq 모델에는 크게 두 가지 문제가 있습니다. 첫째, 하나의 고정된 크기의 벡터에 모든 정보를 압축하려고 하니까 정보 손실이 발생합니다. 둘째, RNN의 고질적인 문제인 기울기 소실(vanishing gradient) 문제가 존재합니다. 결국 이는 기계 번역 분야에서 입력 문장이 길면 번역 품질이 떨어지는 현상으로 나타났습니다. 이를 위한 대안으로 입력 시퀀스가 길어지면 출력 시퀀스의 정확도가 떨어지는 것을 보정해주기 위한 등장한 기법인 어텐션(attention)을 소개합니다.

어텐션의 기본 아이디어는 디코더에서 출력 단어를 예측하는 매 시점(time step)마다, 인코더에서의 전체 입력 문장을 다시 한 번 참고한다는 점입니다. 단, 전체 입력 문장을 전부 다 동일한 비율로 참고하는 것이 아니라, 해당 시점에서 예측해야할 단어와 연관이 있는 입력 단어 부분을 좀 더 집중(attention)해서 보게 됩니다.

어텐션을 함수로 표현하면 주로 다음과 같이 표현됩니다.
Attention(Q, K, V) = Attention Value
어텐션 함수는 주어진 '쿼리(Query)'에 대해서 모든 '키(Key)'와의 유사도를 각각 구합니다. 그리고 구해낸 이 유사도를 키와 맵핑되어있는 각각의 '값(Value)'에 반영해줍니다. 그리고 유사도가 반영된 '값(Value)'을 모두 더해서 리턴합니다. 여기서는 이를 어텐션 값(Attention Value)이라고 하겠습니다.

https://wikidocs.net/22893 
A feedforward neural network (FNN) is an artificial neural network wherein connections between the nodes do not form a cycle. As such, it is different from its descendant: recurrent neural networks.

https://en.wikipedia.org/wiki/Feedforward_neural_network 

 

 

Transformers are deep feed-forward artificial neural networks with a (self)attention mechanism. They have been tremendously successful in natural language processing tasks and other domains. Since their inception 5 years ago [VSP+17], many variants have been suggested [LWLQ21]. Descriptions are usually graphical, verbal, partial, or incremental. Despite their popularity, it seems no pseudocode has ever been published for any variant. Contrast this to other fields of computer science, even to “cousin” discipline reinforcement learning [MKS+13, SBB18, EMK+21].

 

트랜스포머는 어텐션 메커니즘을 활용한 순방향 인공 신경망이다. NLP 분야 등에서 성공적으로 활용되고 있다. 5년 전 트랜스포머의 첫 등장 이후로, 다양한 대안들이 제시되어 왔다. 그 서술은 대체로 시각적이거나, 음성적이거나, 부분적이거나, 점점 늘어갔다. 그 인기에 비해 여러 대안들(변종들)에 대한 유사코드를 찾기 어려웠다. 컴퓨터 과학 내 다른 분야, 심지어 친척 뻘인 강화학습과 비교해보라. 

 

 

This report intends to rectify the situation for Transformers. It aims to be a self-contained, complete, precise and compact overview of transformer architectures and formal algorithms (but not results). It covers what Transformers are (Section 6), how they are trained (Section 7), what they’re used for (Section 3), their key architectural components (Section 5), tokenization (Section 4), and a preview of practical considerations (Section 8) and the most prominent models.

 

이 보고서는 앞서 말한 트랜스포머의 상황을 바로잡기 위한 것이다. 트랜스포머 아키텍처와 알고리즘에 대한 완전하고 정밀하며 압축적인 개요를 목표로 한다. Transformer의 개념(섹션 6), 학습 방법(섹션 7), 사용 목적(섹션 3), 주요 아키텍처 구성 요소(섹션 5), 토큰화(섹션 4), 실용적인 고려 사항(섹션 8) 및 주요 모델에 대해 설명한다.

 

 

The essentially complete pseudocode is about 50 lines, compared to thousands of lines of actual real source code. We believe these formal algorithms will be useful for theoreticians who require compact, complete, and precise formulations, experimental researchers interested in implementing a Transformer from scratch, and encourage authors to augment their paper or text book with formal Transformer algorithms (Section 2).

 

이 본질적으로 완전한 유사 코드는 대략 50줄 정도로, 수천 줄에 이르는 실제 소스 코드와 비교하면 매우 간략하다. 우리는 이 알고리즘이, 압축적이고 완전하며 정밀한 공식을 필요로 하는 이론가들이나, 트랜스포머를 기초부터 구현해나가고자 하는 실험가들, 그리고 본인의 논문이나 책을 알고리즘으로 보강하고자 하는 작가들을 독려한다. 

 

 

The reader is assumed to be familiar with basic ML terminology and simpler neural network architectures such as MLPs.

 

독자들은 기본적인 머신러닝 용어들과, MLP와 같은 비교적 단순한 신경망 구조에 친숙하다고 가정한다.

 

 

In short, a (formally inclined) reader, upon understanding the contents of this document, will have a solid grasp of transformers: they will be ready to read and contribute to the literature on the topic as well as implement their own Transformer using the pseudocode as templates.

 

간략히 하자면, 독자들은, 이 문서의 맥락을 이해하는 과정에서, 트랜스포머에 대한 확실한 이해를 얻게 될 것이다. 트랜스포머 관련 문헌을 읽고 기여할 수 있게 될 것이고, 제시된 유사코드를 탬플릿 삼아 본인만의 트랜스포머를 구현할 수도 있을 것이다.

 

 

(2번 연구 동기 항목은 생략합니다)

 

 

 

 

3. Transformers and Typical Tasks

 

Transformers are neural network models that excel at natural language processing, or more generally at modelling sequential data. Two common types of tasks they are used for are sequence modelling and sequence-to-sequence prediction.

 

트랜스포머는 자연어 처리 또는 보다 일반적으로 순차 데이터를 모델링하는 데에 뛰어난 신경망 모델이다. 트랜스포머를 사용하는 두 가지 일반적인 유형의 작업은 시퀀스 모델링과 시퀀스 대 시퀀스 예측이다.

 

순차 데이터
순차 데이터란 ‘데이터 집합 내의 객체들이 어떤 순서를 가진 데이터’로, 그 순서가 변경될 경우 고유의 특성을 잃어버리는 특징이 있습니다. 쉬운 예로, ‘도’와 ‘시’라는 글자 객체들로 ‘도시’와 ‘시도’라는 단어들의 조합이 가능하지만 이들은 서로 다른 의미를 갖는 것과 같습니다.
https://www.samsungsds.com/kr/insights/sequential_data.html 
시퀀스 모델링
자연어 문장은 단어들의 순차적인 조합으로 만들어집니다. 따라서 문장은 단어의 순서 정보가 포함된 시퀀셜 데이터라고 볼 수 있습니다. 시퀀셜 데이터는 가변 길이의 데이터일 뿐만 아니라, time-step별 데이터 출현에 영향을 주고받는 존재입니다. 그러므로 기존의 완전연결 신경망(fully connected neural network, FNN) 대신, 순서 정보를 다룰 수 있는 순환 신경망(RNN)를 통해 시퀀셜 데이터를 모델링하곤 합니다. 하지만 RNN을 통한 훈련방식은 기존과 달라 많은 부분을 신경써야 합니다. 
https://kh-kim.gitbook.io/natural-language-processing-with-pytorch/00-cover-6 

시간 개념 또는 순서 정보를 사용하여 입력을 학습하는 것
https://velog.io/@jyong0719/%EC%8B%9C%ED%80%80%EC%8A%A4-%EB%AA%A8%EB%8D%B8%EB%A7%81 
sequence-to-sequence prediction
Sequence prediction is a popular machine learning task, which consists of predicting the next symbol(s) based on the previously observed sequence of symbols. These symbols could be a number, an alphabet, a word, an event, or an object like a webpage or product.
For example:
1. A sequence of words or characters in a text
2. A sequence of products bought by a customer
3. A sequence of events observed on logs
Sequence prediction is different from other types of supervised learning problems, as it imposes that the order in the data must be preserved when training models and making predictions. Sequence prediction is a common problem which finds real-life applications in various industries. 

https://jinglescode.github.io/2020/05/21/three-types-sequence-prediction-problems/ 

 

 

 

Notation | 표기

 

Let 𝑉 denote a finite set, called a vocabulary, often identified with [𝑁V] := {1, ..., 𝑁V}. This could be words or letters, but typically are sub-words, called tokens. Let 𝒙 ≡ 𝑥 [1 : ℓ] ≡ 𝑥 [1]𝑥 [2]...𝑥 [ℓ] ∈ 𝑉 ∗ be a sequence of tokens, e.g. a sentence or a paragraph or a document. Unlike in Python, we use arrays starting from 1, and 𝑥 [1 : ] includes 𝑥 [ℓ]. For a matrix 𝑀 ∈ ℝ 𝑑×𝑑' , we write 𝑀[𝑖, :] ∈ ℝ 𝑑' for the 𝑖th row and 𝑀[:, 𝑗] ∈ ℝ𝑑 for the 𝑗-th column. We use matrix × column vector convention more common in mathematics, compared to the default row vector × matrix in the transformer literature, i.e. our matrices are transposed. See Appendix B for a complete list of notation.

 

Vocabulary, V라 하는 유한한 집합은, 종종 [𝑁V] := {1, ..., 𝑁V}라고도 표현된다. 이 집합은 단어들, 글자들일 수도 있지만, 일반적으로는 토큰이라 불리는 서브워드(보조 단어)들이다. 𝒙 ≡ 𝑥 [1 : ℓ] ≡ 𝑥 [1]𝑥 [2]...𝑥 [ℓ] ∈ 𝑉 ∗를 일련의 토큰들이라 하자. 예를 들어, 하나의 문장 혹은 문단 혹은 문서이다. 파이썬과 다르게, 우리는 1부터 시작하는 배열(어레이, Array)을 사용하고, 𝑥 [1 : ]은 𝑥 [ℓ]을 포함한다. 𝑀 ∈ ℝ 𝑑×𝑑' 인 행렬 M에 대해서, 우리는 i번째 행에 대해 𝑀[𝑖, :] ∈ ℝ 𝑑'와 같이 표현하고, j번째 열에 대해 𝑀[:, 𝑗] ∈ ℝ𝑑와 같이 표현한다. 우리는 트랜스포머 관련 문서에서 기본 열 벡터 x 행렬과 비교하여, 전치행렬과 같이, 수학보다 행 X 열 벡터 관습을 더 자주 사용한다. 표기에 대한 자세한 사항은 부록B를 참고하자.

 

 

 

Chunking | 청킹, 덩이짓기

 

The predominant paradigm in machine learning is (still) learning from independent and identically distributed (i.i.d.) data. Even for sequence modelling for practical reasons this tradition is upheld. The training data may naturally be a collection of (independent) articles, but even then, some may exceed the maximal context length ℓmax transformers can handle. In this case, an article is crudely broken into shorter chunks of length ≤ ℓmax.

 

머신 러닝에서 지배적인 패러다임은 (여전히) 독립적이고 동일하게 분산된 (i.i.d.) 데이터로부터 학습하는 것이다. 실용적인 이유로 시퀀스 모델링에서도 이런 방식은 유지된다. 학습 데이터는 자연스럽게 (독립적인) 데이터의 집합일 수 있지만, 일부는 트랜스포머가 처리할 수 있는 최대 컨텍스트 길이, ℓmax를 초과할 수 있다. 이 경우, 데이터(article) 길이가 ≤ µmax인 더 짧은 덩어리로 조잡하게 쪼개진다.

 

 

 

Sequence modelling (DTransformer)

 

Given a vocabulary 𝑉, let 𝒙𝑛 ∈ 𝑉 ∗ for 𝑛 ∈ [𝑁data] be a dataset of sequences (imagined to be) sampled i.i.d. from some distribution 𝑃 over 𝑉 ∗ . The goal is to learn an estimate 𝑃ˆ of the distribution 𝑃(𝒙). In practice, the distribution estimate is often decomposed via the chain rule as 𝑃ˆ(𝒙) = 𝑃ˆ𝜽(𝑥 [1]) · 𝑃ˆ𝜽(𝑥 [2] | 𝑥 [1]) · · · 𝑃ˆ𝜽(𝑥 [ℓ] | 𝒙[1 : ℓ−1]), where 𝜽 consists of all neural network parameters to be learned. The goal is to learn a distribution over a single token 𝑥 [𝑡] given its preceding tokens 𝑥 [1 : 𝑡 − 1] as context.

 

Vocabulary, V가 주어질 때, 𝑛 ∈ [𝑁data] 에 대한 𝒙𝑛 ∈ 𝑉 ∗ 는 𝑉 ∗에 대한 특정 분포 𝑃 로부터 샘플링된 독립적이고 동일하게 분산된 (i.i.d.) 시퀀스들의 데이터셋이라고 하자. 목표는, 분포 𝑃(𝒙)에 대한 추정치 𝑃ˆ을 학습하는 것이다. 실제적으로, 분포에 대한 추정은 흔히 𝑃ˆ(𝒙) = 𝑃ˆ𝜽(𝑥 [1]) · 𝑃ˆ𝜽(𝑥 [2] | 𝑥 [1]) · · · 𝑃ˆ𝜽(𝑥 [ℓ] | 𝒙[1 : ℓ−1])와 같은 연쇄법칙(체인 룰)로 나누어볼 수 있는데, 이때  𝜽 는 학습해야 할 모든 신경망 파라미터들로 구성되어 있다. 목표는 이전 토큰 𝑥 [1 : 𝑡 − 1]을 맥락으로 할 때 단일 토큰 𝑥 [𝑡]에 대한 분포를 학습하는 것이다.

 

 

Examples include e.g. language modelling, RL policy distillation, or music generation.

 

활용 예시에는, 언어 모델링, 강화학습 정책 증류 기법, 음악 생성 등이 있다.

 

Distillation
Knowledge transfer; learn an optimal behavior from expert (e.g. a pre-trained model or a human) interactions with an environment.

Policy Distillation
Goal: extract knowledge from a teacher policy, and transfer it to a student policy using trajectories sampled from interactions between a control policy and the environment.

Distilling Policy Distillation; W. M. Czarnecki, R. Pascanu, S. Osindero, S. Jayakumar, G. Swirszcz, M. Jaderberg; PMLR, 201; Presentation by Anthony Coache STA4273 Minimizing Expectations * March 18, 2021 https://www.cs.toronto.edu/~cmaddis/courses/sta4273_w21/studentwork/Distilling_PD_slides_AC.pdf  
딥러닝 모델 지식의 증류기법, Knowledge Distillation

결국 딥러닝에서 지식 증류는 큰 모델(Teacher Network)로부터 증류한 지식을 작은 모델(Student Network)로 transfer하는 일련의 과정이라고 할 수 있습니다. (...) Knowledge Distillation은 NIPS 2014 workshop에서 발표한 논문 “Distilling the Knowledge in a Neural Network”에서 처음으로 등장한 개념입니다. 논문을 요약하자면 다음과 같습니다.
- 앙상블과 같은 복잡한 모델을 다량의 유저에게 배포하는 것은 하드웨어적으로 엄청 힘듦
- 앙상블이 가진 지식을 단일 모델로 전달해주는 기존 기법이 있으나 그보다 더 일반적인 연구를 함
- MNIST 데이터를 사용해, 큰 모델로부터 증류된 지식이 작은 모델로 잘 전달되는지 확인함
- 앙상블 학습 시간을 단축하는 새로운 방법의 앙상블을 제시함

https://baeseongsu.github.io/posts/knowledge-distillation/ 

 

 

Sequence-to-sequence (seq2seq) prediction (EDTransformer)

 

Given a vocabulary 𝑉 and an i.i.d. dataset of sequence pairs (𝒛𝑛, 𝒙𝑛) ∼ 𝑃, where 𝑃 is a distribution over 𝑉 ∗ × 𝑉 ∗ , learn an estimate of the conditional distribution 𝑃(𝒙|𝒛). In practice, the conditional distribution estimate is often decomposed as 𝑃ˆ(𝒙|𝒛) = 𝑃ˆ𝜽(𝑥 [1] | 𝒛) · 𝑃ˆ𝜽(𝑥 [2] | 𝑥 [1], 𝒛) · · · 𝑃ˆ𝜽(𝑥 [ℓ] | 𝒙[1 : ℓ− 1], 𝒛).

 

𝑉 ∗ × 𝑉 ∗에 대한 분포가 𝑃 일 때, 시퀀스 쌍(𝒛𝑛, 𝒙𝑛) ∼ 𝑃 의 i.i.d. 데이터 집합이 주어지면, 조건부 분포 𝑃(𝒙|𝒛)의 추정치를 학습한다. 실제로, 조건부 분포 추정치는 종종 𝑃ˆ(𝒙|𝒛) = 𝑃ˆ𝜽(𝑥 [1] | 𝒛) · 𝑃ˆ𝜽(𝑥 [2] | 𝑥 [1], 𝒛) · · · 𝑃ˆ𝜽(𝑥 [ℓ] | 𝒙[1 : ℓ− 1], 𝒛)로 나누어진다.

 

Examples include translation (𝒛 = a sentence in English, 𝒙 = the same sentence in German), question answering (𝒛 = question, 𝒙 = the corresponding answer), text-to-speech (𝒛 = a piece of text, 𝒙 = a voice recording of someone reading the text).

 

활용 예시에는 번역(𝒛=영어 문장, 𝒙=독일어 문장), 질문 답변(𝒛=질문, 𝒙=답변), TTS(텍스트 음성 변환)(𝒛=텍스트, 𝒙=음성) 등이 있다.

 

 

 

Classification (ETransformer)

 

Given a vocabulary 𝑉 and a set of classes [𝑁C], let (𝒙𝑛, 𝑐𝑛) ∈ 𝑉 ∗ × [𝑁C] for 𝑛 ∈ [𝑁data] be an i.i.d. dataset of sequence-class pairs sampled from 𝑃(𝒙, 𝑐). The goal in classification is to learn an estimate of the conditional distribution 𝑃(𝑐|𝒙).

 

Vocabulary 𝑉 와 클래스 집합 [𝑁C]가 주어지면, 𝑛 ∈ [𝑁data]에 대한 (𝒙𝑛, 𝑐𝑛) ∈ 𝑉 ∗ × [𝑁C]를, 𝑃(𝒙, 𝑐)로부터 샘플링된 시퀀스-클래스 쌍의 i.i.d. 데이터 집합으로 하자. 분류의 목표는 조건부 분포 (𝑐|𝒙)의 추정치를 학습하는 것이다.

 

 

Examples include e.g. sentiment classification, spam filtering, toxicity classification.

 

활용 예시에는, 감정 분류, 스팸 필터링, 독성 분류 등이 있다.

 

 

 

 

[원문 출처]

Mary Phuong, Marcus Hutter: “Formal Algorithms for Transformers”, 2022, Latest 2022 version at http://arxiv.org/abs/2207.09238 ;

 

Formal Algorithms for Transformers

This document aims to be a self-contained, mathematically precise overview of transformer architectures and algorithms (*not* results). It covers what transformers are, how they are trained, what they are used for, their key architectural components, and a

arxiv.org