2018년에 google AI Language 에서 소개된 BERT 논문을 리뷰해봤다. 이후에 BERT를 기반으로한 성능좋은 여러 모델들이 발표되었는데, 이후 더 나은 모델들을 이해하기 위해 기초가 된 논문을 읽었다.
BERT는 레이블이 없는 텍스트에서 양방향(bidirectional) 표현을 pre-trained 되도록 설계되었다.
그 결과 pre-trained model은 단지 하나의 output layer 추가로 파인 튜닝이 된다. 이것은 question answering 이나 언어추론(language inference) 와 같이 넓은 범위의 task를 만들기 위해 사용된다.
논문은 여기서 https://arxiv.org/pdf/1810.04805.pdf
Introduction
pre-trained 언어 표현을 downstream task에 적용하기 위해 존재하는 두가지 전략이 있다.
feature-based: ELMo 모델이 예시로 있으며, pre-trained 표현을 추가 기능으로 사용한다.
fine-tuning approach: 생성형 pre-trained transformer(Open AI GPT)가 예시로 있으며 최소한의 특정화된 파라미터를 도입하고, 모든 사전 학습된 파라미터를 fine- tuning 하여 다운스트림 작업에 대해 학습한다.
이 두가지의 공통점은 단방향(unidirectional) 언어 모델을 사용한다는 것이다. 단방향 언어 모델의 한계는 pre-train 중에 사용할 수 있는 아키텍처의 선택이 제한된다는 것이다. 예를 들면, OpenAI GPT는 왼쪽에서 오른쪽으로 흐르는 아키텍처를 사용하는데, self- attention에 있는 직전의 토큰만 볼 수 있다는 것이다. 이러한 단점이 문장 단위의 작업에서는 좋지 않다. question answering과 같이 양방향의 문맥을 참고해야하는 작업에는 fine-tuning 접근 방식을 적용하는 것은 좋지 않다.
BERT에서는 masked language model (MLM)을 사용하여 단방향성 제약을 완화한다. masked language model은 input으로 들어가는 토큰들을 무작위로 선택하여 마스킹하고, 단어의 문맥만을 기반으로 하여 마스킹된 어휘를 예측한다.
(순차적으로 학습하기 보다 특정 위치 부분을 mask 해서 예측한다, 선행, 후행 단어를 사용한다.)
또한 next sentence prediction(NSP)을 사용하여 한쌍의 텍스트 표현을 결합하여 pre- train 한다.
Related work
Unsupervised Feature-based Approaches
일반적으로 pre-trained 된 단어 임베딩은 최신 NLP 시스템의 필수적인 부분으로, 상당한 개선을 보여준다. 단어 임베딩 벡터를 사전학습 하기 위해 왼쪽에서 오른쪽으로 흐르는 모델링이 사용되었다. 이 모델은 오른쪽과 왼쪽 문맥에서 올바른 단어와 잘못된 단어를 구별한다. 이전 문장의 표현이 주어지면, 다음 문장 단어의 왼쪽에서 오른쪽으로 생성을 하거나 autoencoder의 노이즈 제거를 하는 방식으로 문장 표현을 train 하여 다음 후보 문장의 순위를 매겼다.
ELMo와 이전 버전 모델에서는 기존의 단어 임베딩 연구를 다른 차원에서 일반화했다. 문맥에 민감한 특징을 왼쪽에서 오른쪽, 그리고 왼쪽에서 오른쪽으로 추출한다. 문맥 단어 임베딩을 기존 작업별 아키텍처와 통합할 때, ELMo는 질문 답변(question answering), 감정 분석, NER(named entity recognition)와 같은 주요 NLP 기술들을 발전시켰다. 이들은 LSTM을 사용하여 왼쪽과 오른쪽 문맥에서 하나의 단어를 예측하는 작업을 통해 문맥 표현을 학습할 것을 제안했다.ELMo와 마찬가지로, 이 모델은 양방향성(bidirectional)이 아니다
Unsupervised Fine-tuning Approaches
최근에는 문맥 토큰 표현을 생성하는 문장 또는 문서 인코더가 레이블 작업이 되지 않은 텍스트로부터 사전 학습되었다. 또한 지도학습의 downstream task를 위해 fine-tuning 되었다. 이러한 접근은 적은 파라미터를 사용하게 한다.
Transfer Learning from Supervised Data
자연어 추론(natural language translation) 과 기계 번역(machine translation)처럼 대용량의 데이터셋을 이용한 supervised task에서 효과적인 전이가 있다는 연구도 있었다.
BERT
Pre-training과 Fine-tuning 두 단계로 나뉜다.
Pre-training 단계에서는 다양한 사전 학습 작업에 걸쳐 레이블이 없는 데이터로 모델을 학습시킨다.
Fine-tuning 단계에서는 pre-trained된 파라미터로 BERT 모델을 초기화하고, 모든 파라미터는 downstream tasks의 레이블된 데이터를 이용하여 미세 조정하였다. 각 downstream task에는 동일한 사전 학습된 파라미터로 초기화되더라도 개별적으로 미세 조정된 모델이 있다.
Model Architecture
BERT는 기존의 attention 모델이 encoder-decoder와 이루어진것과 다르게, encoder 하나만으로 이루어져있다.
여기서는 Multi-layer bidirectional Transformer encoder 로 이루어져있다.
L은 레이어 갯수(transformer block), H는 은닉층 차원(hidden size), A는 self- attention의 head 갯수이다.
BERT Base는 L=12, H=768, A=12이고, 총 파라미터는 1억천만개이다. OpenAI GPT(왼쪽 단방향)와 같은 모델 사이즈다.
BERT Large는 L=24, H=1024, A=16이고, 총 파라미터는 3억4천만개이다.
Input/Output Representations
BERT 가 다양한 downstream task를 처리할 수 있도록 input 표현이 단일 문장과 한 쌍의 문장들 모두 정확하게 표현할 수있다. 이 논문에서 sentence와 sequence의 정의를 별도로 하였다.
Sentence는 실제 언어 문장이 아닌 연속된 텍스트의 임의의 범위이다. sequence는 BERT의 input 토큰 문장(여기서 말하는 문장은 논문에서 정의하는 sentence)인데, 이것은 하나 또는 두개의 문장이 결합되어있다.
CLS: 모든 문장의 첫번째 token
SEP: 두 문장을 분리해주는 토큰
모든 토큰에 학습된 임베딩을 추가하여 해당 토큰이 sentence A(1~N, N개), sentence B(1~M, M개)에 속하는지 나타낸다.
input 임베딩은 E, CLS 토큰의 최종 은닉 벡터는 C, N번째 입력의 최종 은닉벡터는 Tn으로 나타낸다.
(BERT는 위의 mask된 token을 예측하는것 + binary classification(2개의 문장이 corpus에서 다음문장인지 아닌지) 두가지를 동시에 학습한다)
input 표현은 token embedding -> 3만개의 토큰 단어가 있는 wordpiece 임베딩( play + ## ing 쪼갠것이 word piece이다)
segment embedding -> input 두 문장에 대한 학습, 파라미터도 두배로 학습해준다
position embedding
이 세개의 embedding은 똑같은 차원으로 이루어져 있고 모두 더해진다.
Pre-training BERT
Task #1: Masked LM
깊은 양방향 표현을 학습하기 위해서는 input 토큰을 랜덤으로 마스킹하고, 마스킹된 토큰들을 예측해야한다. 이 연구에서, 랜덤으로 각 문장마다 15%의 wordpiece를 마스킹했다. 이렇게 마스킹된 단어들을 예측한다. 하나의 classification layer를 추가하여 가려진 token을 예측한다.
여기서 단점이 있다면, 사전학습과 미세조정 사이에 불일치가 발생한다. 왜냐하면 마스킹 토큰은 미세조정 과정 중 발생하지 않기 때문이다. 이를 완화하기 위해 마스킹된 단어를 실제 mask 토큰으로 사용하지 않는다. 만약 i번째 토큰이 마스킹되기 위해 선택됐다면, 다음과 같이 해결한다.
My dog is hairy 라는 문장이 있을때,
80% 마스크 토큰 -> my dog is [mask]
10% 랜덤 토큰 -> my dog is apple
10%의 토큰은 변경하지 않음 -> my dog is hairy
Task #2: Next Sentence Prediction (NSP)
Question Answering 이나 NLI(Natural Language Inference)과 같은 중요한 downstream task는 두 문장의 관계에 대한 이해에 기초되어 있다. 이 관계는 언어 모델에 의해 직접적으로 캡처되지 않는다. 문장간의 관계를 이해하기 위해 이진화된 (0 or1) next sentence prediction 을 한다. 이것은 단일 언어 말뭉치에서 간단하게 생성될 수 있다.
50%의 확률로 A 다음 B 문장이 연속적으로 나오면 (isNext,1)/ 50%의 확률로 랜덤한 문장이 나오면 (NotNext,0), C( CLS 토큰의 최종 은닉 벡터)는 NSP에 사용된다. 간단하지만 pre-train이 QA와 NLI 모두 유익하다.
예시를 들면 다음과 같다. (의식의 흐름대로 쓴 자체제작 문장)
A: Have you heard about the news that rapid downsize of birth rate in South Korea?
B: Yeah. I think there are lots of complicated issues among young people.
A: I am on the same page. It's really though for young people to retain their living because of economic recession.
B: I agree. I hope this situations get better within few years.
이렇게 노란색으로 바로 이어지는 문장은 IsNext
A: Have you heard about the news that rapid downsize of birth rate in South Korea?
B: Yeah. I think there are lots of complicated issues among young people.
A: I am on the same page. It's really though for young people to retain their living because of economic recession.
B: I agree. I hope this situations get better within few years.
이렇게 이어지지 않는 문장들은 NotNext이다.
Fine-tuning BERT
BERT는 self-attention 메커니즘을 사용하여 두 단계를 결합한다.
self-attention을 이용하여 효과적으로 결합된 텍스트 쌍을 encoding 한다. 이것은 두 문장 간의 양방향(bidirectional) attention을 포함한다. Fine-tuning BERT는 하나의 layer를 쌓는 것만으로도 충분히 구현 가능하다.
a)는 sentence pairs in paraphrasing으로 두개의 sentence를 classification을 통해 예측한다
b)는 한개의 문장을통해 pre-train 후 separation token 없이 class label를 예측한다
c) question-passage pairs in question answering은 question과 paragraph를 통해 정답을 생성한다.
d) 는 한 문장 내의 각 단어나 토큰에 태그를 할당하는 작업을 말하며, 예시로 형태소 분석, NER( Named Entity Recognition)이 있다.
output에서 토큰 표현은 시퀀스 태깅이나 질문답변( question answering )과 같은 토큰 수준 작업을 위해 출력 레이어에 전달된다. CLS 는 분류를 위한 output layer에 공급된다.
Experiments
GLUE( General Language Understanding Evaluation)
Glue task를 보면 파라미터와 레이어, 은닉층이 훨씬 많은 BERT Large 모델이 성능이 잘 나온것을 알 수 있다.
Ablation Studies
No NSP(BERT Base에서 next sentence prediction을 제외) 한 것이 accuracy와 F1 score가 약간 감소한 것을 알 수 있다. 2개 이상의 문장 task에 대해서는 NSP + pre-train이 효과 있음을 알 수 있다.
BERT의 fine- tuning 접근과 4개의 마지막 은닉층을 가중합 한것, 4개의 은닉층을 concat 한것, 12개의 모든 레이어를 가중합한것과 성능차이가 없다는 것을 알 수 있었다. Feature-based approach에는 Fine-tuning을 적용하지 않았다.
논문에서 나온 pre-train model 아키텍처인 ELMo와 GPT1도 리뷰를 해봐야 할듯 싶다. pytorch 코드리뷰를 해볼건데 pre-train된 모델과 fine-tuning을 해야해서 쉽진 않을 것 같은 느낌이다. 일단 이해할 수 있는데까지는 해보는걸로..,,
https://www.youtube.com/watch?v=IwtexRHoWG0 해당 영상을보고 논문 이해하는데 참고했다