[Notes] BERT / BERT 架構理解

Haren Lin
14 min readJun 23, 2021

論文連結 Paper Link

https://arxiv.org/pdf/1810.04805.pdf

論文地位 Position

應該不用多說了吧!(image source: deeplearning.ai)

摘要 Abstract

Bidirectional Encoder Representation from Transformers (a.k.a BERT),即雙向 Transformer Encoder。模型的主要創新點都在 Pre-Train 方法上,即用了 Masked LM(MLM) 和 Next Sentence Prediction(NSP) 兩種方法分別捕捉 token-level & sentence-level 的表示。此外,經過預訓練後的 BERT 可以很簡單地被 Fine-Tune 應用在不同的任務上。

基本介紹 Introduction

作者提到現在對語言模型做下游任務的方法,不外乎這兩種:
(1) Feature-Based Approach (2) Fine-Tuning Approach

  • Feature Based Approach: a pre-trained neural network produces word embeddings which are then used as features in NLP models. (uses task-specific architectures that include the pre-trained representations as additional features)
  • Fine Tuning Approach: introduces minimal task-specific parameters, and is trained on the downstream tasks by simply fine-tuning all pretrained parameters.

簡單來說前者是拿預訓練好語言模型的 Embedding 來作為額外特徵,引入到後面的模型當中訓練。而後者是將我們已經訓練好的模型架構後面,再加上幾層去訓練,並微調前面層的參數。本文作者乃針對後者,Fine-Tuning Approach 提出 Bidirectional Encoder Representation from Transformers 來進行學習上的優化。

不過,進到 BERT 方法描述之前,讓我們拋棄所有過往對於 Word Embedding 的知識,重新建立對於他的認知。

Word embedding is the collective name for a set of language modeling and feature learning techniques in natural language processing (NLP) where words or phrases from the vocabulary are mapped to vectors of real numbers.

簡單來講,要讓文字有辦法以實數的角度表示,建立文字世界與機器世界的橋樑,Word Embedding 的重要性真的不容小覷。

不僅如此,我覺得可以釐清一下為什麼叫做Bidirectional?其實是因為過去做機器翻譯時,Encoder 在讀取資料的時候都是採取單一方向,不是 left-to-right 就是 right-to-left,然而 Transformer Encoder 是採取一次讀取整個 Token Sequence,一口吃進整個序列資料,因此它被認為是雙向的,不過更準確地來說是非定向的(non-directional)。這個特性允許模型根據 Token 的周圍環境,即左側和右側,來學習其的上下文。

Encoder 的長相大概與目的大概如下圖,輸入是一系列 Token 並且以 Embedding 的型態表示,在 Transformer Block 中進行處理與學習, 輸出是一個大小為 H 的 Embedding Sequence,其中每個 Embedding 對應到的就是他輸入文字經過轉換後的 Representation。

Transformer (BERT uses left part, encoder.)

接下來,將省略 Transformer 的細節解釋,直接進入到 BERT 的精華。如果忘記 Transformer 是什麼的話,可以先回顧上一篇的 [Paper Notes] Attention Is All You Need

方法 Methodology

Model Architecture

BERT的具體架構其實就是源自於 2017 Transformer 的 Encoder,在這篇論文中主要有兩組超參數組合的架構:
(1) BERT_BASE (L=12, H=768, A=12, Total Parameters=110M)
(2) BERT_LARGE (L=24, H=1024, A=16, Total Parameters=340M)
[L = # of Transformer blocks; H = hidden size; A = # of attention heads]
其中,BERT_BASE參數設置的目的是要與先前的 Open AI GPT 進行比較。

Data for Pre-Train

Pre-training 語料採用 BooksCorpus (800M words)和 English Wikipedia (2,500M words),且維基百科的部份他們只提取文字部分出來,不包含表格與標頭。作者提到語料的選取對 NSP 很重要,為了提取連續長序列特徵,即跨句語意關聯,語料的選定 Document level 會比 Sentence level 來得好,所以不使用 Billion Word Benchmark。

Input/Output Representations

BERT Input Representation

為了要讓BERT可以完成多種的下游任務,作者讓BERT的輸入可以表示單一句子,也能表示一對句子(a pair of sentence)。成對的句子在什麼任務會用到呢?顯而易見是在做 Question Answering(QA) 的部分,這樣即可輸入<Question, Answer>在同一個 Token Sequence。

作者使用 30,000 個 token 的字典作為他們的 Token Embedding 基礎,並且在一個序列的頭加上[CLS],方便日後的分類任務使用;在兩句中間加入[SEP],幫助模型分辨前句和後句的資訊。總歸來說,BERT預訓練模型中的輸入表示,是透過Token Embedding,Segment Embedding,與Positional Encoding相加而成。其中,Position Embedding 和 Transformer 中的不一樣,不是三角函數而是透過學習得到的。

Overall pre-training and fine-tuning procedures for BERT (image source: BERT paper)

Task#1: Masked LM (MLM)

作者提出了 Masked Language Model 是以克漏字為靈感,在任意段落中進行挖空,模型利用挖空的前後文來預測挖空部分應該填入的文字。為了讓模型達到一樣的能力,他們從每個 Token Sequence 中隨機挑選15%的文字進行遮罩 [MASK],並訓練模型預測 [MASK] 應填入 30,000 字中的哪個詞彙。實際運行上就是把最後一層的向量 Encoder Output 餵進去一個 Classification Layer 並且轉換成與字典一樣大小的維度,再經過 Softmax 去看哪個維度的字彙機率值最高,就取那個字為預測字。最後將預測結果與正確答案比對計算Cross Entropy Loss,將模型進行更新。

然而,這邊會有一個問題是 Pre-Train & Fine-Tune 的 Mismatch,因為在Fine-Tune時,並不會像 Pre-Train 有 [MASK] 這樣的東西出現。此時,作者加入了一些 Noise 的概念來解決這樣的問題。他們在剛剛隨機選出的15%的文字當中,做了一些手腳。其中80%就維持原先的 [MASK],有10%改成用隨機的文字取代,最後10%則是維持原先沒有被 [MASK] 的Token。

  • 80% of the time: Replace the word with the [MASK] token
    e.g., my dog is hairy → my dog is [MASK]
  • 10% of the time: Replace the word with a random word
    e.g.,my dog is hairy → my dog is apple
  • 10% of the time: Keep the word unchanged
    e.g.,my dog is hairy → my dog is hairy
MLM

Task#2: Next Sentence Prediction (NSP)

在許多下游的NLP任務中,例如 QA,NLI,他們都是基於兩個句子的關係進行語意理解,這樣的資訊語言模型其實並沒有辦法有效擷取。因此作者提出了 Next Sentence Prediction 這樣的模型訓練,兩個句子A、B作為一筆訓練資料,其中50%的訓練資料從語料中連貫的兩句子而得,標籤為 IsNext,另外50%則隨機給與兩個不連續的句子,標籤為 NotNext。

  • Input = [CLS] the man went to [MASK] store [SEP] he bought a gallon [MASK] milk [SEP] → Label = IsNext
  • Input = [CLS] the man [MASK] to the store [SEP] penguin [MASK] are flight ##less birds [SEP] → Label = NotNext

具體上的實現為,將整個輸入序列經過 Transformer 模型,使用模型最後產生的[CLS] Token,將他傳入一層 Classification Layer 進行矩陣轉換產出維度為 2×1 的向量,並且再透過 Softmax 得到IsNextSequence 的機率。

Pre-Training BERT

在預訓練時同時進行 MLM 和 NSP 兩項任務,並把兩者的 loss 加總作為最終的 loss。

其實在論文中的 footnote有提到:Google AI Language 基於 OpenAI GPT 提出 BERT 模型架構,前者可視為Transformer Decoder ,其預測只參考待測詞彙左側的資訊,後者則為Transformer encoder,可同時參考雙向的資訊,解決了 GPT 在傳統語言模型預訓練時只能採用 left-to-right 的缺陷。

最大的差別就是透過 NSP幫助跨語句的語意學習,實驗結果大獲全勝。

Fine-tuning BERT

對於所有的下游Fine-Tune任務,其實很簡單明瞭,就是把任務的輸入以及對應的輸出結果傳入模型,他就會幫你 end-to-end 地微調整個模型架構的參數。在輸出結果的部分,[CLS]會餵給一層 Output layer 去做分類任務,例如:entailment 或是 sentiment analysis。而其他 Token Representation 也會餵給一層 Output layer 去做 Token-Level 的任務,例如:Sequence Tagging 或是 Question Answering。

在論文Appendix中也有提及他們的超參數設置:Batch size: 16, 32,Learning rate (Adam): 5e-5, 3e-5, 2e-5,Number of epochs: 3, 4。相較於 Pre-Training,Fine-Tuning 的計算都快上許多,在 TPU 上面至多只需要一小時,而 GPU 上面也僅需要數小時即可完成。

Illustrations of Fine-tuning BERT on Different Tasks (image source: BERT paper)

結論 Conclusion

在計算機視覺領域,研究顯示了遷移學習(Transfer Learning)的價值 — 在已知任務上預訓練神經網絡模型,例如 ImageNet,然後進行微調 — 使用訓練好的神經網絡作為新的特定目的模型。近年來,研究人員已經表明類似的技術可以用在許多 NLP 的任務上。

BERT 提出嶄新的 MLM & NSP 預訓練架構,改變了自然語言處理詞向量表示的生態。雖然大家都把 BERT 捧上天,但觀察他的模型架構、學習策略、輸入表示,其實 Transformer 才是在這個領域中,發起革命性的改變的領航者。

最後,論文作者也提出了一些新發現。模型大小很重要,即使規模已經很大。 BERT_LARGE 擁有 3.45M 個參數,是同類模型中最大的。它在小規模任務上明顯優於「僅」有 1.1M 個參數的 BERT_BASE。此外,BERT 的雙向方法(MLM)的收斂速度比從左到右的方法慢(因為每個 Batch 只預測了15%的 Token),但經過少量預訓練步驟後,雙向訓練仍然優於從左到右訓練。

順帶一提 BTW

1. BERT的參數實在是不少,想要自己做一個 Pre-Train 的模型,可沒有想像中的簡單。先前我在中研院參與 NFinBERT 的研究時,當時使用 Loughran-McDonald 公開的10K語料,用在V100上面進行運算,訓練時間就需要好幾天。個人覺得這樣的運算成本,真的不是一般市井小民想玩就玩得起的XD

2. Google 官方表示,他們使用BERT在他們的檢索系統後,表現有顯著的進步。可以參考:Understanding searches better than ever before 這篇文章。

延伸閱讀 Extra Reading

1. 想更了解更多BERT整理的,請參考這篇論文:A Primer in BERTology: What we know about how BERT works
2. 由於我這篇Medium文章只是個人筆記,如果想看更多BERT的細節且以中文解釋的,請參考這篇文章:BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding
3. Youtube影片10分鐘完美解釋BERT的架構:BERT Neural Network — EXPLAINED!
4. Stanford lecture slides on BERT
5. Google BERT Github Repo

This article will be updated at any time! Thanks for your reading. If you like the content, please click the “clap” button. You can also press the follow button to track new articles. Feel free to connect with me via LinkedIn or email.

--

--

Haren Lin

MSWE @ UC Irvine | MSCS @ NTU GINM | B.S. @ NCCU CS x B.A. @ NCCU ECON | ex-SWE intern @ TrendMicro