日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

一本读懂BERT(实践篇)

發布時間:2023/12/15 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 一本读懂BERT(实践篇) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

目錄

一、什么是BERT?

二、BERT安裝

三、預訓練模型

四、運行Fine-Tuning

五、數據讀取源碼閱讀

(一) DataProcessor

(二) MrpcProcessor

六、分詞源碼閱讀

(一)FullTokenizer

(二) WordpieceTokenizer

七、run_classifier.py的main函數

八、BertModel類

九、自己進行Pretraining

十、性能測試

(一)關于max_seq_len對速度的影響

(二)client_batch_size對速度的影響

(三)num_client?對并發性和速度的影響


一、什么是BERT?

首先我們先看官方的介紹:

BERT is a method of pre-training language representations, meaning that we train a general-purpose "language understanding" model on a large text corpus (like Wikipedia), and then use that model for downstream NLP tasks that we care about (like question answering). BERT outperforms previous methods because it is the first?unsupervised,?deeply bidirectional?system for pre-training NLP.

劃重點:the first?unsupervised,?deeply bidirectional?system for pre-training NLP.

無監督意味著BERT可以僅使用純文本語料庫進行訓練,這是非常重要的特性,因為大量純文本數據在網絡上以多種語言公開。

(上面左圖,紅色的是ELMo,右二是BERT)

預訓練方法可以粗略分為不聯系上下文的詞袋模型等和聯系上下文的方法。其中聯系上下文的方法可以進一步分為單向和雙向聯系上下文兩種。諸如NNLM、Skip-Gram、 Glove等詞袋模型,是一種單層Shallow模型,無法聯系上下文;而LSTM、Transformer為典型的可以聯系上下文的深層次網絡模型。

BERT是在現有預訓練工作的基礎上對現有的技術的良好整合與一定的創新?,F有的這些模型都是單向或淺雙向的。每個單詞僅使用左側(或右側)的單詞進行語境化。例如,在句子中

I ?have?fallen?in?love with a girl.

單向表示love僅基于I ?have?fallen?in?但不 基于with a girl。之前有一些模型也有可以聯系上下文的,但僅以單層"shallow"的方式。BERT能聯系上下文來表示“love” ----- I ?have?fallen?in ...?with a girl。是一種深層次、雙向的深度神經網絡模型。

使用BERT有兩個階段:預訓練和微調。

Pre-training?硬件成本相當昂貴(4--16個云TPU需4天),但是每種語言都只需要訓練一次(目前的模型主要為英語)。為節省計算資源,谷歌正在發布一些預先培訓的模型。?

Fine-tuning 硬件成本相對較低。文中的實踐可以在單個云TPU上(最多1小時)或者在GPU(幾小時)復現出來。BERT的另一個重要方面是它可以適應許多類型的NLP任務:

  • 句子級別(例如,SST-2)
  • 句子對級別(例如,MultiNLI)
  • 單詞級別(例如,NER)
  • 文本閱讀(例如,SQuAD)

二、BERT安裝

Google提供的BERT代碼在這里,可以直接git clone下來。注意運行它需要Tensorflow 1.11及其以上的版本,低版本的Tensorflow不能運行。

三、預訓練模型

由于從頭開始(from scratch)訓練需要巨大的計算資源,因此Google提供了預訓練的模型(的checkpoint),目前包括英語、漢語和多語言3類模型:

  • BERT-Base, Uncased:12層,768隱藏,12頭,110M參數
  • BERT-Large, Uncased:24層,1024個隱藏,16個頭,340M參數
  • BERT-Base, Cased:12層,768隱藏,12頭,110M參數
  • BERT-Large, Cased:24層,1024個隱藏,16個頭,340M參數
  • BERT-Base, Multilingual Cased (New, recommended):104種語言,12層,768隱藏,12頭,110M參數
  • BERT-Base, Multilingual Uncased (Orig, not recommended)?(不推薦使用,Multilingual Cased代替使用):102種語言,12層,768隱藏,12頭,110M參數
  • BERT-Base, Chinese:中文簡體和繁體,12層,768隱藏,12頭,110M參數

Uncased的意思是在預處理的時候都變成了小寫,而cased是保留大小寫。

這么多版本應該如何選擇呢?

如果我們處理的問題只包含英文,那么我們應該選擇英語的版本(模型大效果好但是參數多訓練慢而且需要更多內存/顯存)。如果我們只處理中文,那么應該使用中文的版本。如果是其他語言就使用多語言的版本。

四、運行Fine-Tuning

對于大部分情況,不需要重新Pretraining。我們要做的只是根據具體的任務進行Fine-Tuning,因此我們首先介紹Fine-Tuning。這里我們已GLUE的MRPC為例子,我們首先需要下載預訓練的模型然后解壓,比如作者解壓后的位置是:

/home/chai/data/chinese_L-12_H-768_A-12 # 為了方便我們需要定義環境變量 export BERT_BASE_DIR=/home/chai/data/chinese_L-12_H-768_A-12

環境變量BERT_BASE_DIR是BERT Pretraining的目錄,它包含如下內容:

~/data/chinese_L-12_H-768_A-12$ ls -1 bert_config.json bert_model.ckpt.data-00000-of-00001 bert_model.ckpt.index bert_model.ckpt.meta vocab.txt

vocab.txt是模型的詞典,這個文件會經常要用到,后面會講到。

bert_config.json是BERT的配置(超參數),比如網絡的層數,通常我們不需要修改,但是也會經常用到。

bert_model.ckpt*,這是預訓練好的模型的checkpoint

Fine-Tuning模型的初始值就是來自于這些文件,然后根據不同的任務進行Fine-Tuning。

接下來我們需要下載GLUE數據,這可以使用這個腳本下載,可能需要代理才能下載。

但是大概率下載不下來,能下載的步驟也很麻煩,建議下載網盤的備份版本:
鏈接:https://pan.baidu.com/s/1-b4I3ocYhiuhu3bpSmCJ_Q
提取碼:z6mk

假設下載后的位置是:

/home/chai/data/glue_data # 同樣為了方便,我們定義如下的環境變量 export GLUE_DIR=/home/chai/data/glue_data

GLUE有很多任務,我們來看其中的MRPC任務。

chai:~/data/glue_data/MRPC$ head test.tsv index #1 ID #2 ID #1 String #2 String 0 1089874 1089925 PCCW 's chief operating officer , Mike Butcher , and Alex Arena , the chief financial officer , will report directly to Mr So . Current Chief Operating Officer Mike Butcher and Group Chief Financial Officer Alex Arena will report to So . 1 3019446 3019327 The world 's two largest automakers said their U.S. sales declined more than predicted last month as a late summer sales frenzy caused more of an industry backlash than expected . Domestic sales at both GM and No. 2 Ford Motor Co. declined more than predicted as a late summer sales frenzy prompted a larger-than-expected industry backlash .

數據是tsv(tab分割)文件,每行有4個用Tab分割的字段,分別表示index,第一個句子的id,第二個句子的id,第一個句子,第二個句子。也就是輸入兩個句子,模型判斷它們是否同一個意思(Paraphrase)。如果是測試數據,那么第一列就是index(無意義),如果是訓練數據,那么第一列就是0或者1,其中0代表不同的意思而1代表相同意思。接下來就可以運行如下命令來進行Fine-Tuning了:

python run_classifier.py \--task_name=MRPC \--do_train=true \--do_eval=true \--data_dir=$GLUE_DIR/MRPC \--vocab_file=$BERT_BASE_DIR/vocab.txt \--bert_config_file=$BERT_BASE_DIR/bert_config.json \--init_checkpoint=$BERT_BASE_DIR/bert_model.ckpt \--max_seq_length=128 \--train_batch_size=8 \--learning_rate=2e-5 \--num_train_epochs=3.0 \--output_dir=/tmp/mrpc_output/

這里簡單的解釋一下參數的含義,在后面的代碼閱讀里讀者可以更加詳細的了解其意義。

  • task_name 任務的名字,這里我們Fine-Tuning MRPC任務
  • do_train 是否訓練,這里為True
  • do_eval 是否在訓練結束后驗證,這里為True
  • data_dir 訓練數據目錄,配置了環境變量后不需要修改,否則填入絕對路徑
  • vocab_file BERT模型的詞典
  • bert_config_file BERT模型的配置文件
  • init_checkpoint Fine-Tuning的初始化參數
  • max_seq_length Token序列的最大長度,這里是128
  • train_batch_size batch大小,對于普通8GB的GPU,最大batch大小只能是8,再大就會OOM
  • learning_rate
  • num_train_epochs 訓練的epoch次數,根據任務進行調整
  • output_dir 訓練得到的模型的存放目錄

這里最常見的問題就是內存不夠,通常我們的GPU只有8G作用的顯存,因此對于小的模型(bert-base),我們最多使用batchsize=8,而如果要使用bert-large,那么batchsize只能設置成1。運行結束后可能得到類似如下的結果:

***** Eval results ***** eval_accuracy = 0.845588 eval_loss = 0.505248 global_step = 343 loss = 0.505248

這說明在驗證集上的準確率是0.84左右。

五、數據讀取源碼閱讀

(一) DataProcessor

我們首先來看數據是怎么讀入的。這是一個抽象基類,定義了get_train_examples、get_dev_examples、get_test_examples和get_labels等4個需要子類實現的方法,另外提供了一個_read_tsv函數用于讀取tsv文件。下面我們通過一個實現類MrpcProcessor來了解怎么實現這個抽象基類,如果讀者想使用自己的數據,那么就需要自己實現一個新的子類。

(二) MrpcProcessor

對于MRPC任務,這里定義了MrpcProcessor來基礎DataProcessor。我們來看其中的get_labels和get_train_examples,其余兩個抽象方法是類似的。首先是get_labels,它非常簡單,這任務只有兩個label。

def get_labels(self): return ["0", "1"]

接下來是get_train_examples:

def get_train_examples(self, data_dir):return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")

這個函數首先使用_read_tsv讀入訓練文件train.tsv,然后使用_create_examples函數把每一行變成一個InputExample對象。

def _create_examples(self, lines, set_type):examples = []for (i, line) in enumerate(lines):if i == 0:continueguid = "%s-%s" % (set_type, i)text_a = tokenization.convert_to_unicode(line[3])text_b = tokenization.convert_to_unicode(line[4])if set_type == "test":label = "0"else:label = tokenization.convert_to_unicode(line[0])examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))return examples

代碼非常簡單,line是一個list,line[3]和line[4]分別代表兩個句子,如果是訓練集合和驗證集合,那么第一列line[0]就是真正的label,而如果是測試集合,label就沒有意義,隨便賦值成”0”。然后對于所有的字符串都使用tokenization.convert_to_unicode把字符串變成unicode的字符串。這是為了兼容Python2和Python3,因為Python3的str就是unicode,而Python2的str其實是bytearray,Python2卻有一個專門的unicode類型。感興趣的讀者可以參考其實現,不感興趣的可以忽略。

最終構造出一個InputExample對象來,它有4個屬性:guid、text_a、text_b和label,guid只是個唯一的id而已。text_a代表第一個句子,text_b代表第二個句子,第二個句子可以為None,label代表分類標簽。

六、分詞源碼閱讀

分詞是我們需要重點關注的代碼,因為如果想要把BERT產品化,我們需要使用Tensorflow Serving,Tensorflow Serving的輸入是Tensor,把原始輸入變成Tensor一般需要在Client端完成。BERT的分詞是Python的代碼,如果我們使用其它語言的gRPC Client,那么需要用其它語言實現同樣的分詞算法,否則預測時會出現問題。

這部分代碼需要讀者有Unicode的基礎知識,了解什么是CodePoint,什么是Unicode Block。Python2和Python3的str有什么區別,Python2的unicode類等價于Python3的str等等。不熟悉的讀者可以參考一些資料。

(一)FullTokenizer

BERT里分詞主要是由FullTokenizer類來實現的。

class FullTokenizer(object): def __init__(self, vocab_file, do_lower_case=True):self.vocab = load_vocab(vocab_file)self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case)self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab)def tokenize(self, text):split_tokens = []for token in self.basic_tokenizer.tokenize(text):for sub_token in self.wordpiece_tokenizer.tokenize(token):split_tokens.append(sub_token)return split_tokensdef convert_tokens_to_ids(self, tokens):return convert_tokens_to_ids(self.vocab, tokens)

FullTokenizer的構造函數需要傳入參數詞典vocab_file和do_lower_case。如果我們自己從頭開始訓練模型(后面會介紹),那么do_lower_case決定了我們的某些是否區分大小寫。如果我們只是Fine-Tuning,那么這個參數需要與模型一致,比如模型是chinese_L-12_H-768_A-12,那么do_lower_case就必須為True。

函數首先調用load_vocab加載詞典,建立詞到id的映射關系。下面是文件chinese_L-12_H-768_A-12/vocab.txt的部分內容

馬 高 龍 ? ? ? ! ( ) , - . / : ? ~ the of and in to

接下來是構造BasicTokenizer和WordpieceTokenizer。前者是根據空格等進行普通的分詞,而后者會把前者的結果再細粒度的切分為WordPiece。

tokenize函數實現分詞,它先調用BasicTokenizer進行分詞,接著調用WordpieceTokenizer把前者的結果再做細粒度切分。下面我們來詳細閱讀這兩個類的代碼。我們首先來看BasicTokenizer的tokenize方法。

def tokenize(self, text): text = convert_to_unicode(text)text = self._clean_text(text)# 這是2018年11月1日為了支持多語言和中文增加的代碼。這個代碼也可以用于英語模型,因為在# 英語的訓練數據中基本不會出現中文字符(但是某些wiki里偶爾也可能出現中文)。text = self._tokenize_chinese_chars(text)orig_tokens = whitespace_tokenize(text)split_tokens = []for token in orig_tokens:if self.do_lower_case:token = token.lower()token = self._run_strip_accents(token)split_tokens.extend(self._run_split_on_punc(token))output_tokens = whitespace_tokenize(" ".join(split_tokens))return output_tokens

首先是用convert_to_unicode把輸入變成unicode,這個函數前面也介紹過了。接下來是_clean_text函數,它的作用是去除一些無意義的字符。

def _clean_text(self, text):"""去除一些無意義的字符以及whitespace"""output = []for char in text:cp = ord(char)if cp == 0 or cp == 0xfffd or _is_control(char):continueif _is_whitespace(char):output.append(" ")else:output.append(char)return "".join(output)

codepoint為0的是無意義的字符,0xfffd(U+FFFD)顯示為�,通常用于替換未知的字符。_is_control用于判斷一個字符是否是控制字符(control character),所謂的控制字符就是用于控制屏幕的顯示,比如\n告訴(控制)屏幕把光標移到下一行的開始。讀者可以參考這里。

def _is_control(char):"""檢查字符char是否是控制字符"""# 回車換行和tab理論上是控制字符,但是這里我們把它認為是whitespace而不是控制字符if char == "\t" or char == "\n" or char == "\r":return Falsecat = unicodedata.category(char)if cat.startswith("C"):return Truereturn False

這里使用了unicodedata.category這個函數,它返回這個Unicode字符的Category,這里C開頭的都被認為是控制字符,讀者可以參考這里。

接下來是調用_is_whitespace函數,把whitespace變成空格。

def _is_whitespace(char):"""Checks whether `chars` is a whitespace character."""# \t, \n, and \r are technically contorl characters but we treat them# as whitespace since they are generally considered as such.if char == " " or char == "\t" or char == "\n" or char == "\r":return Truecat = unicodedata.category(char)if cat == "Zs":return Truereturn False

這里把category為Zs的字符以及空格、tab、換行和回車當成whitespace。然后是_tokenize_chinese_chars,用于切分中文,這里的中文分詞很簡單,就是切分成一個一個的漢字。也就是在中文字符的前后加上空格,這樣后續的分詞流程會把沒一個字符當成一個詞。

def _tokenize_chinese_chars(self, text): output = []for char in text:cp = ord(char)if self._is_chinese_char(cp):output.append(" ")output.append(char)output.append(" ")else:output.append(char)return "".join(output)

這里的關鍵是調用_is_chinese_char函數,這個函數用于判斷一個unicode字符是否中文字符。

def _is_chinese_char(self, cp):if ((cp >= 0x4E00 and cp <= 0x9FFF) or #(cp >= 0x3400 and cp <= 0x4DBF) or #(cp >= 0x20000 and cp <= 0x2A6DF) or #(cp >= 0x2A700 and cp <= 0x2B73F) or #(cp >= 0x2B740 and cp <= 0x2B81F) or #(cp >= 0x2B820 and cp <= 0x2CEAF) or(cp >= 0xF900 and cp <= 0xFAFF) or #(cp >= 0x2F800 and cp <= 0x2FA1F)): #return Truereturn False

很多網上的判斷漢字的正則表達式都只包括4E00-9FA5,但這是不全的,比如???就不再這個范圍內。讀者可以參考這里。

接下來是使用whitespace進行分詞,這是通過函數whitespace_tokenize來實現的。它直接調用split函數來實現分詞。Python里whitespace包括’\t\n\x0b\x0c\r ‘。然后遍歷每一個詞,如果需要變成小寫,那么先用lower()函數變成小寫,接著調用_run_strip_accents函數去除accent。它的代碼為:

def _run_strip_accents(self, text):text = unicodedata.normalize("NFD", text)output = []for char in text:cat = unicodedata.category(char)if cat == "Mn":continueoutput.append(char)return "".join(output)

它首先調用unicodedata.normalize(“NFD”, text)對text進行歸一化。這個函數有什么作用呢?我們先看一下下面的代碼:

>>> s1 = 'café' >>> s2 = 'cafe\u0301' >>> s1, s2 ('café', 'café') >>> len(s1), len(s2) (4, 5) >>> s1 == s2 False

我們”看到”的é其實可以有兩種表示方法,一是用一個codepoint直接表示”é”,另外一種是用”e”再加上特殊的codepoint U+0301兩個字符來表示。U+0301是COMBINING ACUTE ACCENT,它跟在e之后就變成了”é”。類似的”a\u0301”顯示出來就是”á”。注意:這只是打印出來一模一樣而已,但是在計算機內部的表示它們完全不同的,前者é是一個codepoint,值為0xe9,而后者是兩個codepoint,分別是0x65和0x301。unicodedata.normalize(“NFD”, text)就會把0xe9變成0x65和0x301,比如下面的測試代碼。

接下來遍歷每一個codepoint,把category為Mn的去掉,比如前面的U+0301,COMBINING ACUTE ACCENT就會被去掉。category為Mn的所有Unicode字符完整列表在這里。

s = unicodedata.normalize("NFD", "é") for c in s:print("%#x" %(ord(c)))# 輸出為: 0x65 0x301

處理完大小寫和accent之后得到的Token通過函數_run_split_on_punc再次用標點切分。這個函數會對輸入字符串用標點進行切分,返回一個list,list的每一個元素都是一個char。比如輸入he’s,則輸出是[[h,e], [’],[s]]。代碼很簡單,這里就不贅述。里面它會調用函數_is_punctuation來判斷一個字符是否標點。

def _is_punctuation(char): cp = ord(char)# 我們把ASCII里非字母數字都當成標點。# 在Unicode的category定義里, "^", "$", and "`" 等都不是標點,但是我們這里都認為是標點。if ((cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or(cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126)):return Truecat = unicodedata.category(char)# category是P開頭的都是標點,參考https://en.wikipedia.org/wiki/Unicode_character_propertyif cat.startswith("P"):return Truereturn False

(二) WordpieceTokenizer

WordpieceTokenizer的作用是把詞再切分成更細粒度的WordPiece。WordPiece(Byte Pair Encoding)是一種解決OOV問題的方法,如果不管細節,我們把它看成比詞更小的基本單位就行。對于中文來說,WordpieceTokenizer什么也不干,因為之前的分詞已經是基于字符的了。有興趣的讀者可以參考這個開源項目。一般情況我們不需要自己重新生成WordPiece,使用BERT模型里自帶的就行。

WordpieceTokenizer的代碼為:

def tokenize(self, text):# 把一段文字切分成word piece。這其實是貪心的最大正向匹配算法。# 比如:# input = "unaffable"# output = ["un", "##aff", "##able"]text = convert_to_unicode(text)output_tokens = []for token in whitespace_tokenize(text):chars = list(token)if len(chars) > self.max_input_chars_per_word:output_tokens.append(self.unk_token)continueis_bad = Falsestart = 0sub_tokens = []while start < len(chars):end = len(chars)cur_substr = Nonewhile start < end:substr = "".join(chars[start:end])if start > 0:substr = "##" + substrif substr in self.vocab:cur_substr = substrbreakend -= 1if cur_substr is None:is_bad = Truebreaksub_tokens.append(cur_substr)start = endif is_bad:output_tokens.append(self.unk_token)else:output_tokens.extend(sub_tokens)return output_tokens

代碼有點長,但是很簡單,就是貪心的最大正向匹配。其實為了加速,是可以把詞典加載到一個Double Array Trie里的。我們用一個例子來看代碼的執行過程。比如假設輸入是”unaffable”。我們跳到while循環部分,這是start=0,end=len(chars)=9,也就是先看看unaffable在不在詞典里,如果在,那么直接作為一個WordPiece,如果不再,那么end-=1,也就是看unaffabl在不在詞典里,最終發現”un”在詞典里,把un加到結果里。

接著start=2,看affable在不在,不在再看affabl,…,最后發現?##aff?在詞典里。注意:##表示這個詞是接著前面的,這樣使得WordPiece切分是可逆的——我們可以恢復出“真正”的詞。

七、run_classifier.py的main函數

main函數的主要代碼為:

main()bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)task_name = FLAGS.task_name.lower()processor = processors[task_name]()label_list = processor.get_labels()tokenizer = tokenization.FullTokenizer(vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)run_config = tf.contrib.tpu.RunConfig(cluster=tpu_cluster_resolver,master=FLAGS.master,model_dir=FLAGS.output_dir,save_checkpoints_steps=FLAGS.save_checkpoints_steps,tpu_config=tf.contrib.tpu.TPUConfig(iterations_per_loop=FLAGS.iterations_per_loop,num_shards=FLAGS.num_tpu_cores,per_host_input_for_training=is_per_host))train_examples = Nonenum_train_steps = Nonenum_warmup_steps = Noneif FLAGS.do_train:train_examples = processor.get_train_examples(FLAGS.data_dir)num_train_steps = int(len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs)num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)model_fn = model_fn_builder(bert_config=bert_config,num_labels=len(label_list),init_checkpoint=FLAGS.init_checkpoint,learning_rate=FLAGS.learning_rate,num_train_steps=num_train_steps,num_warmup_steps=num_warmup_steps,use_tpu=FLAGS.use_tpu,use_one_hot_embeddings=FLAGS.use_tpu)# 如果沒有TPU,那么會使用GPU或者CPUestimator = tf.contrib.tpu.TPUEstimator(use_tpu=FLAGS.use_tpu,model_fn=model_fn,config=run_config,train_batch_size=FLAGS.train_batch_size,eval_batch_size=FLAGS.eval_batch_size,predict_batch_size=FLAGS.predict_batch_size)if FLAGS.do_train:train_file = os.path.join(FLAGS.output_dir, "train.tf_record")file_based_convert_examples_to_features(train_examples, label_list, FLAGS.max_seq_length, tokenizer, train_file)train_input_fn = file_based_input_fn_builder(input_file=train_file,seq_length=FLAGS.max_seq_length,is_training=True,drop_remainder=True)estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)if FLAGS.do_eval:eval_examples = processor.get_dev_examples(FLAGS.data_dir)eval_file = os.path.join(FLAGS.output_dir, "eval.tf_record")file_based_convert_examples_to_features(eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file)# This tells the estimator to run through the entire set.eval_steps = Noneeval_drop_remainder = True if FLAGS.use_tpu else Falseeval_input_fn = file_based_input_fn_builder(input_file=eval_file,seq_length=FLAGS.max_seq_length,is_training=False,drop_remainder=eval_drop_remainder)result = estimator.evaluate(input_fn=eval_input_fn, steps=eval_steps)if FLAGS.do_predict:predict_examples = processor.get_test_examples(FLAGS.data_dir)predict_file = os.path.join(FLAGS.output_dir, "predict.tf_record")file_based_convert_examples_to_features(predict_examples, label_list,FLAGS.max_seq_length, tokenizer, predict_file)predict_drop_remainder = True if FLAGS.use_tpu else Falsepredict_input_fn = file_based_input_fn_builder(input_file=predict_file,seq_length=FLAGS.max_seq_length,is_training=False,drop_remainder=predict_drop_remainder)result = estimator.predict(input_fn=predict_input_fn)

這里使用的是Tensorflow的Estimator API,這里只介紹訓練部分的代碼。

首先是通過file_based_convert_examples_to_features函數把輸入的tsv文件變成TFRecord文件,便于Tensorflow處理。

train_file = os.path.join(FLAGS.output_dir, "train.tf_record")file_based_convert_examples_to_features(train_examples, label_list, FLAGS.max_seq_length, tokenizer, train_file)def file_based_convert_examples_to_features(examples, label_list, max_seq_length, tokenizer, output_file):writer = tf.python_io.TFRecordWriter(output_file)for (ex_index, example) in enumerate(examples):feature = convert_single_example(ex_index, example, label_list,max_seq_length, tokenizer)def create_int_feature(values):f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))return ffeatures = collections.OrderedDict()features["input_ids"] = create_int_feature(feature.input_ids)features["input_mask"] = create_int_feature(feature.input_mask)features["segment_ids"] = create_int_feature(feature.segment_ids)features["label_ids"] = create_int_feature([feature.label_id])tf_example = tf.train.Example(features=tf.train.Features(feature=features))writer.write(tf_example.SerializeToString())

file_based_convert_examples_to_features函數遍歷每一個example(InputExample類的對象)。然后使用convert_single_example函數把每個InputExample對象變成InputFeature。InputFeature就是一個存放特征的對象,它包括input_ids、input_mask、segment_ids和label_id,這4個屬性除了label_id是一個int之外,其它都是int的列表,因此使用create_int_feature函數把它變成tf.train.Feature,而label_id需要構造一個只有一個元素的列表,最后構造tf.train.Example對象,然后寫到TFRecord文件里。后面Estimator的input_fn會用到它。

這里的最關鍵是convert_single_example函數,讀懂了它就真正明白BERT把輸入表示成向量的過程,所以請讀者仔細閱讀代碼和其中的注釋。

def convert_single_example(ex_index, example, label_list, max_seq_length,tokenizer):"""把一個`InputExample`對象變成`InputFeatures`."""# label_map把label變成id,這個函數每個example都需要執行一次,其實是可以優化的。# 只需要在可以再外面執行一次傳入即可。label_map = {}for (i, label) in enumerate(label_list):label_map[label] = itokens_a = tokenizer.tokenize(example.text_a)tokens_b = Noneif example.text_b:tokens_b = tokenizer.tokenize(example.text_b)if tokens_b:# 如果有b,那么需要保留3個特殊Token[CLS], [SEP]和[SEP]# 如果兩個序列加起來太長,就需要去掉一些。_truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)else:# 沒有b則只需要保留[CLS]和[SEP]兩個特殊字符# 如果Token太多,就直接截取掉后面的部分。if len(tokens_a) > max_seq_length - 2:tokens_a = tokens_a[0:(max_seq_length - 2)]# BERT的約定是:# (a) 對于兩個序列:# tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]# type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1# (b) 對于一個序列:# tokens: [CLS] the dog is hairy . [SEP]# type_ids: 0 0 0 0 0 0 0## 這里"type_ids"用于區分一個Token是來自第一個還是第二個序列# 對于type=0和type=1,模型會學習出兩個Embedding向量。# 雖然理論上這是不必要的,因為[SEP]隱式的確定了它們的邊界。# 但是實際加上type后,模型能夠更加容易的知道這個詞屬于那個序列。## 對于分類任務,[CLS]對應的向量可以被看成 "sentence vector"# 注意:一定需要Fine-Tuning之后才有意義tokens = []segment_ids = []tokens.append("[CLS]")segment_ids.append(0)for token in tokens_a:tokens.append(token)segment_ids.append(0)tokens.append("[SEP]")segment_ids.append(0)if tokens_b:for token in tokens_b:tokens.append(token)segment_ids.append(1)tokens.append("[SEP]")segment_ids.append(1)input_ids = tokenizer.convert_tokens_to_ids(tokens)# mask是1表示是"真正"的Token,0則是Padding出來的。在后面的Attention時會通過tricky的技巧讓# 模型不能attend to這些padding出來的Token上。input_mask = [1] * len(input_ids)# padding使得序列長度正好等于max_seq_lengthwhile len(input_ids) < max_seq_length:input_ids.append(0)input_mask.append(0)segment_ids.append(0)label_id = label_map[example.label]feature = InputFeatures(input_ids=input_ids,input_mask=input_mask,segment_ids=segment_ids,label_id=label_id)return feature

如果兩個Token序列的長度太長,那么需要去掉一些,這會用到_truncate_seq_pair函數:

def _truncate_seq_pair(tokens_a, tokens_b, max_length):while True:total_length = len(tokens_a) + len(tokens_b)if total_length <= max_length:breakif len(tokens_a) > len(tokens_b):tokens_a.pop()else:tokens_b.pop()

這個函數很簡單,如果兩個序列的長度小于max_length,那么不用truncate,否則在tokens_a和tokens_b中選擇長的那個序列來pop掉最后面的那個Token,這樣的結果是使得兩個Token序列一樣長(或者最多a比b多一個Token)。對于Estimator API來說,最重要的是實現model_fn和input_fn。我們先看input_fn,它是由file_based_input_fn_builder構造出來的。代碼如下:

def file_based_input_fn_builder(input_file, seq_length, is_training,drop_remainder):name_to_features = {"input_ids": tf.FixedLenFeature([seq_length], tf.int64),"input_mask": tf.FixedLenFeature([seq_length], tf.int64),"segment_ids": tf.FixedLenFeature([seq_length], tf.int64),"label_ids": tf.FixedLenFeature([], tf.int64),}def _decode_record(record, name_to_features):# 把record decode成TensorFlow example.example = tf.parse_single_example(record, name_to_features)# tf.Example只支持tf.int64,但是TPU只支持tf.int32.# 因此我們把所有的int64變成int32.for name in list(example.keys()):t = example[name]if t.dtype == tf.int64:t = tf.to_int32(t)example[name] = treturn exampledef input_fn(params): batch_size = params["batch_size"]# 對于訓練來說,我們會重復的讀取和shuffling # 對于驗證和測試,我們不需要shuffling和并行讀取。d = tf.data.TFRecordDataset(input_file)if is_training:d = d.repeat()d = d.shuffle(buffer_size=100)d = d.apply(tf.contrib.data.map_and_batch(lambda record: _decode_record(record, name_to_features),batch_size=batch_size,drop_remainder=drop_remainder))return dreturn input_fn

這個函數返回一個函數input_fn。這個input_fn函數首先從文件得到TFRecordDataset,然后根據是否訓練來shuffle和重復讀取。然后用applay函數對每一個TFRecord進行map_and_batch,調用_decode_record函數對record進行parsing。從而把TFRecord的一條Record變成tf.Example對象,這個對象包括了input_ids等4個用于訓練的Tensor。

接下來是model_fn_builder,它用于構造Estimator使用的model_fn。下面是它的主要代碼(一些無關的log和TPU相關代碼去掉了):

def model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate,num_train_steps, num_warmup_steps, use_tpu,use_one_hot_embeddings): # 注意:在model_fn的設計里,features表示輸入(特征),而labels表示輸出# 但是這里的實現有點不好,把label也放到了features里。def model_fn(features, labels, mode, params): input_ids = features["input_ids"]input_mask = features["input_mask"]segment_ids = features["segment_ids"]label_ids = features["label_ids"]is_training = (mode == tf.estimator.ModeKeys.TRAIN)# 創建Transformer模型,這是最主要的代碼。(total_loss, per_example_loss, logits, probabilities) = create_model(bert_config, is_training, input_ids, input_mask, segment_ids, label_ids,num_labels, use_one_hot_embeddings)tvars = tf.trainable_variables()# 從checkpoint恢復參數if init_checkpoint: (assignment_map, initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)tf.train.init_from_checkpoint(init_checkpoint, assignment_map)output_spec = None# 構造訓練的specif mode == tf.estimator.ModeKeys.TRAIN:train_op = optimization.create_optimizer(total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)output_spec = tf.contrib.tpu.TPUEstimatorSpec(mode=mode,loss=total_loss,train_op=train_op,scaffold_fn=scaffold_fn)# 構造eval的specelif mode == tf.estimator.ModeKeys.EVAL: def metric_fn(per_example_loss, label_ids, logits):predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)accuracy = tf.metrics.accuracy(label_ids, predictions)loss = tf.metrics.mean(per_example_loss)return {"eval_accuracy": accuracy,"eval_loss": loss,}eval_metrics = (metric_fn, [per_example_loss, label_ids, logits])output_spec = tf.contrib.tpu.TPUEstimatorSpec(mode=mode,loss=total_loss,eval_metrics=eval_metrics,scaffold_fn=scaffold_fn)# 預測的specelse:output_spec = tf.contrib.tpu.TPUEstimatorSpec(mode=mode,predictions=probabilities,scaffold_fn=scaffold_fn)return output_specreturn model_fn

這里的代碼都是一些boilerplate代碼,沒什么可說的,最重要的是調用create_model”真正”的創建Transformer模型。下面我們來看這個函數的代碼:

def create_model(bert_config, is_training, input_ids, input_mask, segment_ids,labels, num_labels, use_one_hot_embeddings): model = modeling.BertModel(config=bert_config,is_training=is_training,input_ids=input_ids,input_mask=input_mask,token_type_ids=segment_ids,use_one_hot_embeddings=use_one_hot_embeddings)# 在這里,我們是用來做分類,因此我們只需要得到[CLS]最后一層的輸出。# 如果需要做序列標注,那么可以使用model.get_sequence_output()# 默認參數下它返回的output_layer是[8, 768]output_layer = model.get_pooled_output()# 默認是768hidden_size = output_layer.shape[-1].valueoutput_weights = tf.get_variable("output_weights", [num_labels, hidden_size],initializer=tf.truncated_normal_initializer(stddev=0.02))output_bias = tf.get_variable("output_bias", [num_labels], initializer=tf.zeros_initializer())with tf.variable_scope("loss"):if is_training:# 0.1的概率會dropoutoutput_layer = tf.nn.dropout(output_layer, keep_prob=0.9)# 對[CLS]輸出的768的向量再做一個線性變換,輸出為label的個數。得到logitslogits = tf.matmul(output_layer, output_weights, transpose_b=True)logits = tf.nn.bias_add(logits, output_bias)probabilities = tf.nn.softmax(logits, axis=-1)log_probs = tf.nn.log_softmax(logits, axis=-1)one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)loss = tf.reduce_mean(per_example_loss)return (loss, per_example_loss, logits, probabilities)

上面代碼調用modeling.BertModel得到BERT模型,然后使用它的get_pooled_output方法得到[CLS]最后一層的輸出,這是一個768(默認參數下)的向量,然后就是常規的接一個全連接層得到logits,然后softmax得到概率,之后就可以根據真實的分類標簽計算loss。我們這時候發現關鍵的代碼是modeling.BertModel。

八、BertModel類

這個類是最終定義模型的地方,代碼比較多,我們會按照執行和調用的順序逐個閱讀。因為文字只能線性描述,但是函數的調用關系很復雜,所以建議讀者對照源代碼來閱讀。

我們首先來看這個類的用法,把它當成黑盒。前面的create_model也用到了BertModel,這里我們在詳細的介紹一下。下面的代碼演示了BertModel的使用方法:

# 假設輸入已經分詞并且變成WordPiece的id了?# 輸入是[2, 3],表示batch=2,max_seq_length=3input_ids = tf.constant([[31, 51, 99], [15, 5, 0]])# 第一個例子實際長度為3,第二個例子長度為2input_mask = tf.constant([[1, 1, 1], [1, 1, 0]])# 第一個例子的3個Token中前兩個屬于句子1,第三個屬于句子2# 而第二個例子的第一個Token屬于句子1,第二個屬于句子2(第三個是padding)token_type_ids = tf.constant([[0, 0, 1], [0, 1, 0]])# 創建一個BertConfig,詞典大小是32000,Transformer的隱單元個數是512# 8個Transformer block,每個block有6個Attention Head,全連接層的隱單元是1024config = modeling.BertConfig(vocab_size=32000, hidden_size=512,num_hidden_layers=8, num_attention_heads=6, intermediate_size=1024)# 創建BertModelmodel = modeling.BertModel(config=config, is_training=True,input_ids=input_ids, input_mask=input_mask, token_type_ids=token_type_ids)# label_embeddings用于把512的隱單元變換成logitslabel_embeddings = tf.get_variable(...)# 得到[CLS]最后一層輸出,把它看成句子的Embedding(Encoding)pooled_output = model.get_pooled_output()# 計算logitslogits = tf.matmul(pooled_output, label_embeddings)

接下來我們看一下BertModel的構造函數:

def __init__(self,config,is_training,input_ids,input_mask=None,token_type_ids=None,use_one_hot_embeddings=True,scope=None): # Args:# config: `BertConfig` 對象# is_training: bool 表示訓練還是eval,是會影響dropout# input_ids: int32 Tensor shape是[batch_size, seq_length]# input_mask: (可選) int32 Tensor shape是[batch_size, seq_length]# token_type_ids: (可選) int32 Tensor shape是[batch_size, seq_length]# use_one_hot_embeddings: (可選) bool# 如果True,使用矩陣乘法實現提取詞的Embedding;否則用tf.embedding_lookup()# 對于TPU,使用前者更快,對于GPU和CPU,后者更快。# scope: (可選) 變量的scope。默認是"bert"# Raises:# ValueError: 如果config或者輸入tensor的shape有問題就會拋出這個異常config = copy.deepcopy(config)if not is_training:config.hidden_dropout_prob = 0.0config.attention_probs_dropout_prob = 0.0input_shape = get_shape_list(input_ids, expected_rank=2)batch_size = input_shape[0]seq_length = input_shape[1]if input_mask is None:input_mask = tf.ones(shape=[batch_size, seq_length], dtype=tf.int32)if token_type_ids is None:token_type_ids = tf.zeros(shape=[batch_size, seq_length], dtype=tf.int32)with tf.variable_scope(scope, default_name="bert"):with tf.variable_scope("embeddings"):# 詞的Embedding lookup (self.embedding_output, self.embedding_table) = embedding_lookup(input_ids=input_ids,vocab_size=config.vocab_size,embedding_size=config.hidden_size,initializer_range=config.initializer_range,word_embedding_name="word_embeddings",use_one_hot_embeddings=use_one_hot_embeddings)# 增加位置embeddings和token type的embeddings,然后是# layer normalize和dropout。self.embedding_output = embedding_postprocessor(input_tensor=self.embedding_output,use_token_type=True,token_type_ids=token_type_ids,token_type_vocab_size=config.type_vocab_size,token_type_embedding_name="token_type_embeddings",use_position_embeddings=True,position_embedding_name="position_embeddings",initializer_range=config.initializer_range,max_position_embeddings=config.max_position_embeddings,dropout_prob=config.hidden_dropout_prob)with tf.variable_scope("encoder"):# 把shape為[batch_size, seq_length]的2D mask變成# shape為[batch_size, seq_length, seq_length]的3D mask# 以便后向的attention計算,讀者可以對比之前的Transformer的代碼。attention_mask = create_attention_mask_from_input_mask(input_ids, input_mask)# 多個Transformer模型stack起來。# all_encoder_layers是一個list,長度為num_hidden_layers(默認12),每一層對應一個值。# 每一個值都是一個shape為[batch_size, seq_length, hidden_size]的tensor。self.all_encoder_layers = transformer_model(input_tensor=self.embedding_output,attention_mask=attention_mask,hidden_size=config.hidden_size,num_hidden_layers=config.num_hidden_layers,num_attention_heads=config.num_attention_heads,intermediate_size=config.intermediate_size,intermediate_act_fn=get_activation(config.hidden_act),hidden_dropout_prob=config.hidden_dropout_prob,attention_probs_dropout_prob=config.attention_probs_dropout_prob,initializer_range=config.initializer_range,do_return_all_layers=True)# `sequence_output` 是最后一層的輸出,shape是[batch_size, seq_length, hidden_size]self.sequence_output = self.all_encoder_layers[-1]with tf.variable_scope("pooler"):# 取最后一層的第一個時刻[CLS]對應的tensor# 從[batch_size, seq_length, hidden_size]變成[batch_size, hidden_size]# sequence_output[:, 0:1, :]得到的是[batch_size, 1, hidden_size]# 我們需要用squeeze把第二維去掉。first_token_tensor = tf.squeeze(self.sequence_output[:, 0:1, :], axis=1)# 然后再加一個全連接層,輸出仍然是[batch_size, hidden_size]self.pooled_output = tf.layers.dense(first_token_tensor,config.hidden_size,activation=tf.tanh,kernel_initializer=create_initializer(config.initializer_range))

代碼很長,但是其實很簡單。首先是對config(BertConfig對象)深度拷貝一份,如果不是訓練,那么把dropout都置為零。如果輸入的input_mask為None,那么構造一個shape合適值全為1的input_mask,這表示輸入都是”真實”的輸入,沒有padding的內容。如果token_type_ids為None,那么構造一個shape合適并且值全為0的tensor,表示所有Token都屬于第一個句子。

然后使用embedding_lookup函數構造詞的Embedding,用embedding_postprocessor函數增加位置embeddings和token type的embeddings,然后是layer normalize和dropout。

接著用transformer_model函數構造多個Transformer SubLayer然后stack在一起。得到的all_encoder_layers是一個list,長度為num_hidden_layers(默認12),每一層對應一個值。 每一個值都是一個shape為[batch_size, seq_length, hidden_size]的tensor。

self.sequence_output是最后一層的輸出,shape是[batch_size, seq_length, hidden_size]。first_token_tensor是第一個Token([CLS])最后一層的輸出,shape是[batch_size, hidden_size]。最后對self.sequence_output再加一個線性變換,得到的tensor仍然是[batch_size, hidden_size]。

embedding_lookup函數用于實現Embedding,它有兩種方式:使用tf.nn.embedding_lookup和矩陣乘法(one_hot_embedding=True)。前者適合于CPU與GPU,后者適合于TPU。所謂的one-hot方法是把輸入id表示成one-hot的向量,當然輸入id序列就變成了one-hot的矩陣,然后乘以Embedding矩陣。而tf.nn.embedding_lookup是直接用id當下標提取Embedding矩陣對應的向量。一般認為tf.nn.embedding_lookup更快一點,但是TPU上似乎不是這樣,作者也不太了解原因是什么,猜測可能是TPU的沒有快捷的辦法提取矩陣的某一行/列?

def embedding_lookup(input_ids,vocab_size,embedding_size=128,initializer_range=0.02,word_embedding_name="word_embeddings",use_one_hot_embeddings=False):"""word embeddingArgs:input_ids: int32 Tensor shape為[batch_size, seq_length],表示WordPiece的idvocab_size: int 詞典大小,需要于vocab.txt一致 embedding_size: int embedding后向量的大小 initializer_range: float 隨機初始化的范圍 word_embedding_name: string 名字,默認是"word_embeddings"use_one_hot_embeddings: bool 如果True,使用one-hot方法實現embedding;否則使用 `tf.nn.embedding_lookup()`. TPU適合用One hot方法。Returns:float Tensor shape為[batch_size, seq_length, embedding_size]"""# 這個函數假設輸入的shape是[batch_size, seq_length, num_inputs]# 普通的Embeding一般假設輸入是[batch_size, seq_length],# 增加num_inputs這一維度的目的是為了一次計算更多的Embedding# 但目前的代碼并沒有用到,傳入的input_ids都是2D的,這增加了代碼的閱讀難度。# 如果輸入是[batch_size, seq_length],# 那么我們把它 reshape成[batch_size, seq_length, 1]if input_ids.shape.ndims == 2:input_ids = tf.expand_dims(input_ids, axis=[-1])# 構造Embedding矩陣,shape是[vocab_size, embedding_size]embedding_table = tf.get_variable(name=word_embedding_name,shape=[vocab_size, embedding_size],initializer=create_initializer(initializer_range))if use_one_hot_embeddings:flat_input_ids = tf.reshape(input_ids, [-1])one_hot_input_ids = tf.one_hot(flat_input_ids, depth=vocab_size)output = tf.matmul(one_hot_input_ids, embedding_table)else:output = tf.nn.embedding_lookup(embedding_table, input_ids)input_shape = get_shape_list(input_ids)# 把輸出從[batch_size, seq_length, num_inputs(這里總是1), embedding_size]# 變成[batch_size, seq_length, num_inputs*embedding_size]output = tf.reshape(output,input_shape[0:-1] + [input_shape[-1] * embedding_size])return (output, embedding_table)

Embedding本來很簡單,使用tf.nn.embedding_lookup就行了。但是為了優化TPU,它還支持使用矩陣乘法來提取詞向量。另外為了提高效率,輸入的shape除了[batch_size, seq_length]外,它還增加了一個維度變成[batch_size, seq_length, num_inputs]。如果不關心細節,我們把這個函數當成黑盒,那么我們只需要知道它的輸入input_ids(可能)是[8, 128],輸出是[8, 128, 768]就可以了。

函數embedding_postprocessor的代碼如下,需要注意的部分都有注釋。

def embedding_postprocessor(input_tensor,use_token_type=False,token_type_ids=None,token_type_vocab_size=16,token_type_embedding_name="token_type_embeddings",use_position_embeddings=True,position_embedding_name="position_embeddings",initializer_range=0.02,max_position_embeddings=512,dropout_prob=0.1):"""對word embedding之后的tensor進行后處理Args:input_tensor: float Tensor shape為[batch_size, seq_length, embedding_size]use_token_type: bool 是否增加`token_type_ids`的Embeddingtoken_type_ids: (可選) int32 Tensor shape為[batch_size, seq_length]如果`use_token_type`為True則必須有值token_type_vocab_size: int Token Type的個數,通常是2token_type_embedding_name: string Token type Embedding的名字use_position_embeddings: bool 是否使用位置Embeddingposition_embedding_name: string,位置embedding的名字 initializer_range: float,初始化范圍 max_position_embeddings: int,位置編碼的最大長度,可以比最大序列長度大,但是不能比它小。dropout_prob: float. Dropout 概率Returns:float tensor shape和`input_tensor`相同。"""input_shape = get_shape_list(input_tensor, expected_rank=3)batch_size = input_shape[0]seq_length = input_shape[1]width = input_shape[2]if seq_length > max_position_embeddings:raise ValueError("The seq length (%d) cannot be greater than ""`max_position_embeddings` (%d)" %(seq_length, max_position_embeddings))output = input_tensorif use_token_type:if token_type_ids is None:raise ValueError("`token_type_ids` must be specified if""`use_token_type` is True.")token_type_table = tf.get_variable(name=token_type_embedding_name,shape=[token_type_vocab_size, width],initializer=create_initializer(initializer_range))# 因為Token Type通常很小(2),所以直接用矩陣乘法(one-hot)更快flat_token_type_ids = tf.reshape(token_type_ids, [-1])one_hot_ids = tf.one_hot(flat_token_type_ids, depth=token_type_vocab_size)token_type_embeddings = tf.matmul(one_hot_ids, token_type_table)token_type_embeddings = tf.reshape(token_type_embeddings,[batch_size, seq_length, width])output += token_type_embeddingsif use_position_embeddings:full_position_embeddings = tf.get_variable(name=position_embedding_name,shape=[max_position_embeddings, width],initializer=create_initializer(initializer_range))# 位置Embedding是可以學習的參數,因此我們創建一個[max_position_embeddings, width]的矩陣# 但實際輸入的序列可能并不會到max_position_embeddings(512),為了提高訓練速度,# 我們通過tf.slice取出[0, 1, 2, ..., seq_length-1]的部分,。if seq_length < max_position_embeddings:position_embeddings = tf.slice(full_position_embeddings, [0, 0],[seq_length, -1])else:position_embeddings = full_position_embeddingsnum_dims = len(output.shape.as_list())# word embedding之后的tensor是[batch_size, seq_length, width]# 因為位置編碼是與輸入內容無關,它的shape總是[seq_length, width]# 我們無法把位置Embedding加到word embedding上# 因此我們需要擴展位置編碼為[1, seq_length, width]# 然后就能通過broadcasting加上去了。position_broadcast_shape = []for _ in range(num_dims - 2):position_broadcast_shape.append(1)position_broadcast_shape.extend([seq_length, width])# 默認情況下position_broadcast_shape為[1, 128, 768]position_embeddings = tf.reshape(position_embeddings,position_broadcast_shape)# output是[8, 128, 768], position_embeddings是[1, 128, 768]# 因此可以通過broadcasting相加。output += position_embeddingsoutput = layer_norm_and_dropout(output, dropout_prob)return output

create_attention_mask_from_input_mask函數用于構造Mask矩陣。我們先了解一下它的作用然后再閱讀其代碼。比如調用它時的兩個參數是是:

input_ids=[[1,2,3,0,0],[1,3,5,6,1] ] input_mask=[[1,1,1,0,0],[1,1,1,1,1] ]

表示這個batch有兩個樣本,第一個樣本長度為3(padding了2個0),第二個樣本長度為5。在計算Self-Attention的時候每一個樣本都需要一個Attention Mask矩陣,表示每一個時刻可以attend to的范圍,1表示可以attend,0表示是padding的(或者在機器翻譯的Decoder中不能attend to未來的詞)。對于上面的輸入,這個函數返回一個shape是[2, 5, 5]的tensor,分別代表兩個Attention Mask矩陣。

[[1, 1, 1, 0, 0], #它表示第1個詞可以attend to 3個詞[1, 1, 1, 0, 0], #它表示第2個詞可以attend to 3個詞[1, 1, 1, 0, 0], #它表示第3個詞可以attend to 3個詞[1, 1, 1, 0, 0], #無意義,因為輸入第4個詞是padding的0[1, 1, 1, 0, 0] #無意義,因為輸入第5個詞是padding的0 ][[1, 1, 1, 1, 1], # 它表示第1個詞可以attend to 5個詞[1, 1, 1, 1, 1], # 它表示第2個詞可以attend to 5個詞[1, 1, 1, 1, 1], # 它表示第3個詞可以attend to 5個詞[1, 1, 1, 1, 1], # 它表示第4個詞可以attend to 5個詞[1, 1, 1, 1, 1] # 它表示第5個詞可以attend to 5個詞 ]

了解了它的用途之后下面的代碼就很好理解了。

def create_attention_mask_from_input_mask(from_tensor, to_mask):"""Create 3D attention mask from a 2D tensor mask.Args:from_tensor: 2D or 3D Tensor,shape為[batch_size, from_seq_length, ...].to_mask: int32 Tensor, shape為[batch_size, to_seq_length].Returns:float Tensor,shape為[batch_size, from_seq_length, to_seq_length]."""from_shape = get_shape_list(from_tensor, expected_rank=[2, 3])batch_size = from_shape[0]from_seq_length = from_shape[1]to_shape = get_shape_list(to_mask, expected_rank=2)to_seq_length = to_shape[1]to_mask = tf.cast(tf.reshape(to_mask, [batch_size, 1, to_seq_length]), tf.float32)# `broadcast_ones` = [batch_size, from_seq_length, 1]broadcast_ones = tf.ones(shape=[batch_size, from_seq_length, 1], dtype=tf.float32)# Here we broadcast along two dimensions to create the mask.mask = broadcast_ones * to_maskreturn mask

比如前面舉的例子,broadcast_ones的shape是[2, 5, 1],值全是1,而to_mask是

to_mask=[ [1,1,1,0,0], [1,1,1,1,1] ]

shape是[2, 5],reshape為[2, 1, 5]。然后broadcast_ones * to_mask就得到[2, 5, 5],正是我們需要的兩個Mask矩陣,讀者可以驗證。注意[batch, A, B]*[batch, B, C]=[batch, A, C],我們可以認為是batch個[A, B]的矩陣乘以batch個[B, C]的矩陣。接下來就是transformer_model函數了,它就是構造Transformer的核心代碼。

def transformer_model(input_tensor,attention_mask=None,hidden_size=768,num_hidden_layers=12,num_attention_heads=12,intermediate_size=3072,intermediate_act_fn=gelu,hidden_dropout_prob=0.1,attention_probs_dropout_prob=0.1,initializer_range=0.02,do_return_all_layers=False):"""Multi-headed, multi-layer的Transformer,參考"Attention is All You Need".這基本上是和原始Transformer encoder相同的代碼。原始論文為:https://arxiv.org/abs/1706.03762Also see:https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/models/transformer.pyArgs:input_tensor: float Tensor,shape為[batch_size, seq_length, hidden_size]attention_mask: (可選) int32 Tensor,shape [batch_size, seq_length,seq_length], 1表示可以attend to,0表示不能。 hidden_size: int. Transformer隱單元個數num_hidden_layers: int. 有多少個SubLayer num_attention_heads: int. Transformer Attention Head個數。intermediate_size: int. 全連接層的隱單元個數intermediate_act_fn: 函數. 全連接層的激活函數。hidden_dropout_prob: float. Self-Attention層殘差之前的Dropout概率attention_probs_dropout_prob: float. attention的Dropout概率initializer_range: float. 初始化范圍(truncated normal的標準差)do_return_all_layers: 返回所有層的輸出還是最后一層的輸出。Returns:如果do_return_all_layers True,返回最后一層的輸出,是一個Tensor,shape為[batch_size, seq_length, hidden_size];否則返回所有層的輸出,是一個長度為num_hidden_layers的list,list的每一個元素都是[batch_size, seq_length, hidden_size]。"""if hidden_size % num_attention_heads != 0:raise ValueError("The hidden size (%d) is not a multiple of the number of attention ""heads (%d)" % (hidden_size, num_attention_heads))# 因為最終要輸出hidden_size,總共有num_attention_heads個Head,因此每個Head輸出# 為hidden_size / num_attention_headsattention_head_size = int(hidden_size / num_attention_heads)input_shape = get_shape_list(input_tensor, expected_rank=3)batch_size = input_shape[0]seq_length = input_shape[1]input_width = input_shape[2]# 因為需要殘差連接,我們需要把輸入加到Self-Attention的輸出,因此要求它們的shape是相同的。if input_width != hidden_size:raise ValueError("The width of the input tensor (%d) != hidden size (%d)" %(input_width, hidden_size))# 為了避免在2D和3D之間來回reshape,我們統一把所有的3D Tensor用2D來表示。# 雖然reshape在GPU/CPU上很快,但是在TPU上卻不是這樣,這樣做的目的是為了優化TPU# input_tensor是[8, 128, 768], prev_output是[8*128, 768]=[1024, 768] prev_output = reshape_to_matrix(input_tensor)all_layer_outputs = []for layer_idx in range(num_hidden_layers):# 每一層都有自己的variable scopewith tf.variable_scope("layer_%d" % layer_idx):layer_input = prev_output# attention層with tf.variable_scope("attention"):attention_heads = []# self attentionwith tf.variable_scope("self"):attention_head = attention_layer(from_tensor=layer_input,to_tensor=layer_input,attention_mask=attention_mask,num_attention_heads=num_attention_heads,size_per_head=attention_head_size,attention_probs_dropout_prob=attention_probs_dropout_prob,initializer_range=initializer_range,do_return_2d_tensor=True,batch_size=batch_size,from_seq_length=seq_length,to_seq_length=seq_length)attention_heads.append(attention_head)attention_output = Noneif len(attention_heads) == 1:attention_output = attention_heads[0]else:# 如果有多個head,那么需要把多個head的輸出concat起來attention_output = tf.concat(attention_heads, axis=-1)# 使用線性變換把前面的輸出變成`hidden_size`,然后再加上`layer_input`(殘差連接)with tf.variable_scope("output"):attention_output = tf.layers.dense(attention_output,hidden_size,kernel_initializer=create_initializer(initializer_range))# dropoutattention_output = dropout(attention_output, hidden_dropout_prob)# 殘差連接再加上layer norm。attention_output = layer_norm(attention_output + layer_input)# 全連接層with tf.variable_scope("intermediate"):intermediate_output = tf.layers.dense(attention_output,intermediate_size,activation=intermediate_act_fn,kernel_initializer=create_initializer(initializer_range))# 然后是用一個線性變換把大小變回`hidden_size`,這樣才能加殘差連接with tf.variable_scope("output"):layer_output = tf.layers.dense(intermediate_output,hidden_size,kernel_initializer=create_initializer(initializer_range))layer_output = dropout(layer_output, hidden_dropout_prob)layer_output = layer_norm(layer_output + attention_output)prev_output = layer_outputall_layer_outputs.append(layer_output)if do_return_all_layers:final_outputs = []for layer_output in all_layer_outputs:final_output = reshape_from_matrix(layer_output, input_shape)final_outputs.append(final_output)return final_outputselse:final_output = reshape_from_matrix(prev_output, input_shape)return final_output

如果對照Transformer的論文,非常容易閱讀,里面實現Self-Attention的函數就是attention_layer。

def attention_layer(from_tensor,to_tensor,attention_mask=None,num_attention_heads=1,size_per_head=512,query_act=None,key_act=None,value_act=None,attention_probs_dropout_prob=0.0,initializer_range=0.02,do_return_2d_tensor=False,batch_size=None,from_seq_length=None,to_seq_length=None):"""用`from_tensor`(作為Query)去attend to `to_tensor`(提供Key和Value)這個函數實現論文"Attentionis all you Need"里的multi-head attention。如果`from_tensor`和`to_tensor`是同一個tensor,那么就實現Self-Attention。`from_tensor`的每個時刻都會attends to `to_tensor`,也就是用from的Query去乘以所有to的Key,得到weight,然后把所有to的Value加權求和起來。這個函數首先把`from_tensor`變換成一個"query" tensor,然后把`to_tensor`變成"key"和"value" tensors??偣灿?#96;num_attention_heads`組Query、Key和Value,每一個Query,Key和Value的shape都是[batch_size(8), seq_length(128), size_per_head(512/8=64)].然后計算query和key的內積并且除以size_per_head的平方根(8)。然后softmax變成概率,最后用概率加權value得到輸出。因為有多個Head,每個Head都輸出[batch_size, seq_length, size_per_head],最后把8個Head的結果concat起來,就最終得到[batch_size(8), seq_length(128), size_per_head*8=512] 實際上我們是把這8個Head的Query,Key和Value都放在一個Tensor里面的,因此實際通過transpose和reshape就達到了上面的效果。Args:from_tensor: float Tensor,shape [batch_size, from_seq_length, from_width]to_tensor: float Tensor,shape [batch_size, to_seq_length, to_width].attention_mask: (可選) int32 Tensor, shape[batch_size,from_seq_length,to_seq_length]。值可以是0或者1,在計算attention score的時候,我們會把0變成負無窮(實際是一個絕對值很大的負數),而1不變,這樣softmax的時候進行exp的計算,前者就趨近于零,從而間接實現Mask的功能。num_attention_heads: int. Attention heads的數量。size_per_head: int. 每個head的sizequery_act: (可選) query變換的激活函數key_act: (可選) key變換的激活函數value_act: (可選) value變換的激活函數attention_probs_dropout_prob: (可選) float. attention的Dropout概率。initializer_range: float. 初始化范圍 do_return_2d_tensor: bool. 如果True,返回2D的Tensor其shape是[batch_size * from_seq_length, num_attention_heads * size_per_head];否則返回3D的Tensor其shape為[batch_size, from_seq_length, num_attention_heads * size_per_head].batch_size: (可選) int. 如果輸入是3D的,那么batch就是第一維,但是可能3D的壓縮成了2D的,所以需要告訴函數batch_size from_seq_length: (可選) 同上,需要告訴函數from_seq_lengthto_seq_length: (可選) 同上,to_seq_lengthReturns:float Tensor,shape [batch_size,from_seq_length,num_attention_heads * size_per_head]。如果`do_return_2d_tensor`為True,則返回的shape是[batch_size * from_seq_length, num_attention_heads * size_per_head]."""def transpose_for_scores(input_tensor, batch_size, num_attention_heads,seq_length, width):output_tensor = tf.reshape(input_tensor, [batch_size, seq_length, num_attention_heads, width])output_tensor = tf.transpose(output_tensor, [0, 2, 1, 3])return output_tensorfrom_shape = get_shape_list(from_tensor, expected_rank=[2, 3])to_shape = get_shape_list(to_tensor, expected_rank=[2, 3])if len(from_shape) != len(to_shape):raise ValueError("The rank of `from_tensor` must match the rank of `to_tensor`.")# 如果輸入是3D的(沒有壓縮),那么我們可以推測出batch_size、from_seq_length和to_seq_length# 即使參數傳入也會被覆蓋。if len(from_shape) == 3:batch_size = from_shape[0]from_seq_length = from_shape[1]to_seq_length = to_shape[1]# 如果是壓縮成2D的,那么一定要傳入這3個參數,否則拋異常。 elif len(from_shape) == 2:if (batch_size is None or from_seq_length is None or to_seq_length is None):raise ValueError("When passing in rank 2 tensors to attention_layer, the values ""for `batch_size`, `from_seq_length`, and `to_seq_length` ""must all be specified.")# B = batch size (number of sequences) 默認配置是8# F = `from_tensor` sequence length 默認配置是128# T = `to_tensor` sequence length 默認配置是128# N = `num_attention_heads` 默認配置是12# H = `size_per_head` 默認配置是64# 把from和to壓縮成2D的。# [8*128, 768]from_tensor_2d = reshape_to_matrix(from_tensor)# [8*128, 768]to_tensor_2d = reshape_to_matrix(to_tensor)# 計算Query `query_layer` = [B*F, N*H] =[8*128, 12*64]# batch_size=8,共128個時刻,12和head,每個head的query向量是64# 因此最終得到[8*128, 12*64]query_layer = tf.layers.dense(from_tensor_2d,num_attention_heads * size_per_head,activation=query_act,name="query",kernel_initializer=create_initializer(initializer_range))# 和query類似,`key_layer` = [B*T, N*H]key_layer = tf.layers.dense(to_tensor_2d,num_attention_heads * size_per_head,activation=key_act,name="key",kernel_initializer=create_initializer(initializer_range))# 同上,`value_layer` = [B*T, N*H]value_layer = tf.layers.dense(to_tensor_2d,num_attention_heads * size_per_head,activation=value_act,name="value",kernel_initializer=create_initializer(initializer_range))# 把query從[B*F, N*H] =[8*128, 12*64]變成[B, N, F, H]=[8, 12, 128, 64]query_layer = transpose_for_scores(query_layer, batch_size,num_attention_heads, from_seq_length,size_per_head)# 同上,key也變成[8, 12, 128, 64]key_layer = transpose_for_scores(key_layer, batch_size, num_attention_heads,to_seq_length, size_per_head)# 計算query和key的內積,得到attention scores.# [8, 12, 128, 64]*[8, 12, 64, 128]=[8, 12, 128, 128]# 最后兩維[128, 128]表示from的128個時刻attend to到to的128個score。# `attention_scores` = [B, N, F, T]attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)attention_scores = tf.multiply(attention_scores,1.0 / math.sqrt(float(size_per_head)))if attention_mask is not None:# 從[8, 128, 128]變成[8, 1, 128, 128]# `attention_mask` = [B, 1, F, T]attention_mask = tf.expand_dims(attention_mask, axis=[1])# 這個小技巧前面也用到過,如果mask是1,那么(1-1)*-10000=0,adder就是0,# 如果mask是0,那么(1-0)*-10000=-10000。adder = (1.0 - tf.cast(attention_mask, tf.float32)) * -10000.0# 我們把adder加到attention_score里,mask是1就相當于加0,mask是0就相當于加-10000。# 通常attention_score都不會很大,因此mask為0就相當于把attention_score設置為負無窮# 后面softmax的時候就趨近于0,因此相當于不能attend to Mask為0的地方。attention_scores += adder# softmax# `attention_probs` = [B, N, F, T] =[8, 12, 128, 128]attention_probs = tf.nn.softmax(attention_scores)# 對attention_probs進行dropout,這雖然有點奇怪,但是Transformer的原始論文就是這么干的。attention_probs = dropout(attention_probs, attention_probs_dropout_prob)# 把`value_layer` reshape成[B, T, N, H]=[8, 128, 12, 64]value_layer = tf.reshape(value_layer,[batch_size, to_seq_length, num_attention_heads, size_per_head])# `value_layer`變成[B, N, T, H]=[8, 12, 128, 64]value_layer = tf.transpose(value_layer, [0, 2, 1, 3])# 計算`context_layer` = [8, 12, 128, 128]*[8, 12, 128, 64]=[8, 12, 128, 64]=[B, N, F, H]context_layer = tf.matmul(attention_probs, value_layer)# `context_layer` 變換成 [B, F, N, H]=[8, 128, 12, 64]context_layer = tf.transpose(context_layer, [0, 2, 1, 3])if do_return_2d_tensor:# `context_layer` = [B*F, N*V]context_layer = tf.reshape(context_layer,[batch_size * from_seq_length, num_attention_heads * size_per_head])else:# `context_layer` = [B, F, N*V]context_layer = tf.reshape(context_layer,[batch_size, from_seq_length, num_attention_heads * size_per_head])return context_layer

九、自己進行Pretraining

雖然Google提供了Pretraining的模型,但是我們可以也會需要自己通過Mask LM和Next Sentence Prediction進行Pretraining。當然如果我們數據和計算資源都足夠多,那么我們可以從頭開始Pretraining,如果我們有一些領域的數據,那么我們也可以進行Pretraining,但是可以用Google提供的checkpoint作為初始值。

要進行Pretraining首先需要有數據,前面講過,數據由很多”文檔”組成,每篇文檔的句子之間是有關系的。如果只能拿到沒有關系的句子則是無法訓練的。我們的訓練數據需要變成如下的格式:

~/codes/bert$ cat sample_text.txt This text is included to make sure Unicode is handled properly: 力加勝北區?????????? Text should be one-sentence-per-line, with empty lines between documents. This sample text is public domain and was randomly selected from Project Guttenberg.The rain had only ceased with the gray streaks of morning at Blazing Star, and the settlement awoke to a moral sense of cleanliness, and the finding of forgotten knives, tin cups, and smaller camp utensils, where the heavy showers had washed away the debris and dust heaps before the cabin doors. Indeed, it was recorded in Blazing Star that a fortunate early riser had once picked up on the highway a solid chunk of gold quartz which the rain had freed from its incumbering soil, and washed into immediate and glittering popularity. Possibly this may have been the reason why early risers in that locality, during the rainy season, adopted a thoughtful habit of body, and seldom lifted their eyes to the rifted or india-ink washed skies above them. "Cass" Beard had risen early that morning, but not with a view to discovery. ...省略了很多行

數據是文本文件,每一行表示一個句子,空行表示一個文檔的結束(新文檔的開始),比如上面的例子,總共有2個文檔,第一個文檔只有3個句子,第二個文檔有很多句子。

我們首先需要使用create_pretraining_data.py把文本文件變成TFRecord格式,便于后面的代碼進行Pretraining。由于這個腳本會把整個文本文件加載到內存,因此這個文件不能太大。如果讀者有很多文檔要訓練,比如1000萬。那么我們可以把這1000萬文檔拆分成1萬個文件,每個文件1000個文檔,從而生成1000個TFRecord文件。

我們先看create_pretraining_data.py的用法:

python create_pretraining_data.py --input_file=./sample_text.txt --output_file=./imdb/tf_examples.tfrecord --vocab_file=./vocab.txt --do_lower_case=True --max_seq_length=128 --max_predictions_per_seq=20 --masked_lm_prob=0.15 --random_seed=12345 --dupe_factor=5
  • max_seq_length Token序列的最大長度
  • max_predictions_per_seq 最多生成多少個MASK
  • masked_lm_prob 多少比例的Token變成MASK
  • dupe_factor 一個文檔重復多少次

首先說一下參數dupe_factor,比如一個句子”it is a good day”,為了充分利用數據,我們可以多次隨機的生成MASK,比如第一次可能生成”it is a [MASK] day”,第二次可能生成”it [MASK] a good day”。這個參數控制重復的次數。

masked_lm_prob就是論文里的參數15%。max_predictions_per_seq是一個序列最多MASK多少個Token,它通常等于max_seq_length * masked_lm_prob。這么看起來這個參數沒有必要提供,但是后面的腳本也需要用到這個同樣的值,而后面的腳本并沒有這兩個參數。

我們先看main函數。

def main(_): tokenizer = tokenization.FullTokenizer(vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)input_files = []# 省略了文件通配符的處理,我們假設輸入的文件已經傳入input_filesrng = random.Random(FLAGS.random_seed)instances = create_training_instances(input_files, tokenizer, FLAGS.max_seq_length, FLAGS.dupe_factor,FLAGS.short_seq_prob, FLAGS.masked_lm_prob, FLAGS.max_predictions_per_seq,rng)output_files = ....write_instance_to_example_files(instances, tokenizer, FLAGS.max_seq_length,FLAGS.max_predictions_per_seq, output_files)

main函數很簡單,輸入文本文件列表是input_files,通過函數create_training_instances構建訓練的instances,然后調用write_instance_to_example_files以TFRecord格式寫到output_files。

我們先來看一個訓練樣本的格式,這是用類TrainingInstance來表示的:

class TrainingInstance(object):def __init__(self, tokens, segment_ids, masked_lm_positions, masked_lm_labels,is_random_next):self.tokens = tokensself.segment_ids = segment_idsself.is_random_next = is_random_nextself.masked_lm_positions = masked_lm_positionsself.masked_lm_labels = masked_lm_labels

假設原始兩個句子為:”it is a good day”和”I want to go out”,那么處理后的TrainingInstance可能為:

1. tokens = ["[CLS], "it", "is" "a", "[MASK]", "day", "[SEP]", "I", "apple", "to", "go", "out", "[SEP]"] 2. segment_ids=[0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] 3. is_random_next=False 4. masked_lm_positions=[4, 8, 9] 表示Mask后為["[CLS], "it", "is" "a", "[MASK]", "day", "[SEP]", "I", "[MASK]", "to", "go", "out", "[SEP]"] 5. masked_lm_labels=["good", "want", "to"]

is_random_next表示這兩句話是有關聯的,預測句子關系的分類器應該把這個輸入判斷為1。masked_lm_positions記錄哪些位置被Mask了,而masked_lm_labels記錄被Mask之前的詞。

注意:tokens已經處理過了,good被替換成[MASK],而want被替換成apple,而to還是被替換成它自己,原因前面的理論部分已經介紹過了。因此根據masked_lm_positions、masked_lm_labels和tokens是可以恢復出原始(分詞后的)句子的。

create_training_instances函數的代碼為:

def create_training_instances(input_files, tokenizer, max_seq_length,dupe_factor, short_seq_prob, masked_lm_prob,max_predictions_per_seq, rng):"""從原始文本創建`TrainingInstance`"""all_documents = [[]]# 輸入文件格式: # (1) 每行一個句子。這應該是實際的句子,不應該是整個段落或者段落的隨機片段(span),因為我們需# 要使用句子邊界來做下一個句子的預測。 # (2) 文檔之間有一個空行。我們會認為同一個文檔的相鄰句子是有關系的。# 下面的代碼讀取所有文件,然后根據空行切分Document# all_documents是list的list,第一層list表示document,第二層list表示document里的多個句子。 for input_file in input_files:with tf.gfile.GFile(input_file, "r") as reader:while True:line = tokenization.convert_to_unicode(reader.readline())if not line:breakline = line.strip()# 空行表示舊文檔的結束和新文檔的開始。if not line:#添加一個新的空文檔all_documents.append([])tokens = tokenizer.tokenize(line)if tokens:all_documents[-1].append(tokens)# 刪除空文檔all_documents = [x for x in all_documents if x]rng.shuffle(all_documents)vocab_words = list(tokenizer.vocab.keys())instances = []# 重復dup_factor次for _ in range(dupe_factor):# 遍歷所有文檔for document_index in range(len(all_documents)):# 從一個文檔(下標為document_index)里抽取多個TrainingInstanceinstances.extend(create_instances_from_document(all_documents, document_index, max_seq_length, short_seq_prob,masked_lm_prob, max_predictions_per_seq, vocab_words, rng))rng.shuffle(instances)return instances

上面的函數會調用create_instances_from_document來從一個文檔里抽取多個訓練數據(TrainingInstance)。普通的語言模型只要求連續的字符串就行,通常是把所有的文本(比如維基百科的內容)拼接成一個很大很大的文本文件,然后訓練的時候隨機的從里面抽取固定長度的字符串作為一個”句子”。但是BERT要求我們的輸入是一個一個的Document,每個Document有很多句子,這些句子是連貫的真實的句子,需要正確的分句,而不能隨機的(比如按照固定長度)切分句子。代碼如下:

def create_instances_from_document(all_documents, document_index, max_seq_length, short_seq_prob,masked_lm_prob, max_predictions_per_seq, vocab_words, rng):"""從一個文檔里創建多個`TrainingInstance`。"""document = all_documents[document_index]# 為[CLS], [SEP], [SEP]預留3個位置。max_num_tokens = max_seq_length - 3# 我們通常希望Token序列長度為最大的max_seq_length,否則padding后的計算是無意義的,浪費計# 算資源。但是有的時候我們有希望生成一些短的句子,因為在實際應用中會有短句,如果都是# 長句子,那么就很容易出現Mismatch,所有我們以short_seq_prob == 0.1 == 10%的概率生成# 短句子。target_seq_length = max_num_tokens# 以0.1的概率生成隨機(2-max_num_tokens)的長度。if rng.random() < short_seq_prob:target_seq_length = rng.randint(2, max_num_tokens)# 我們不能把一個文檔的所有句子的Token拼接起來,然后隨機的選擇兩個片段。# 因為這樣很可能這兩個片段是同一個句子(至少很可能第二個片段的開頭和第一個片段的結尾是同一個# 句子),這樣預測是否相關句子的任務太簡單,學習不到深層的語義關系。# 這里我們使用"真實"的句子邊界。instances = []current_chunk = []current_length = 0i = 0while i < len(document):segment = document[i]current_chunk.append(segment)current_length += len(segment)if i == len(document) - 1 or current_length >= target_seq_length:if current_chunk:# `a_end`是第一個句子A(在current_chunk里)結束的下標 a_end = 1# 隨機選擇切分邊界if len(current_chunk) >= 2:a_end = rng.randint(1, len(current_chunk) - 1)tokens_a = []for j in range(a_end):tokens_a.extend(current_chunk[j])tokens_b = []# 是否Random nextis_random_next = Falseif len(current_chunk) == 1 or rng.random() < 0.5:is_random_next = Truetarget_b_length = target_seq_length - len(tokens_a)# 隨機的挑選另外一篇文檔的隨機開始的句子# 但是理論上有可能隨機到的文檔就是當前文檔,因此需要一個while循環# 這里只while循環10次,理論上還是有重復的可能性,但是我們忽略for _ in range(10):random_document_index = rng.randint(0, len(all_documents) - 1)# 不是當前文檔,則找到了random_document_indexif random_document_index != document_index:break# 隨機挑選的文檔random_document = all_documents[random_document_index]# 隨機選擇開始句子random_start = rng.randint(0, len(random_document) - 1)# 把Token加到tokens_b里,如果Token數量夠了(target_b_length)就break。for j in range(random_start, len(random_document)):tokens_b.extend(random_document[j])if len(tokens_b) >= target_b_length:break# 之前我們雖然挑選了len(current_chunk)個句子,但是a_end之后的句子替換成隨機的其它# 文檔的句子,因此我們并沒有使用a_end之后的句子,因此我們修改下標i,使得下一次循環# 可以再次使用這些句子(把它們加到新的chunk里),避免浪費。num_unused_segments = len(current_chunk) - a_endi -= num_unused_segments# 真實的下一句else:is_random_next = Falsefor j in range(a_end, len(current_chunk)):tokens_b.extend(current_chunk[j])# 如果太多了,隨機去掉一些。 truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng)tokens = []segment_ids = []# 處理句子Atokens.append("[CLS]")segment_ids.append(0)for token in tokens_a:tokens.append(token)segment_ids.append(0)# A的結束tokens.append("[SEP]")segment_ids.append(0)# 處理句子Bfor token in tokens_b:tokens.append(token)segment_ids.append(1)# B的結束tokens.append("[SEP]")segment_ids.append(1)(tokens, masked_lm_positions,masked_lm_labels) = create_masked_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq, vocab_words, rng)instance = TrainingInstance(tokens=tokens,segment_ids=segment_ids,is_random_next=is_random_next,masked_lm_positions=masked_lm_positions,masked_lm_labels=masked_lm_labels)instances.append(instance)current_chunk = []current_length = 0i += 1return instances

代碼有點長,但是邏輯很簡單,比如有一篇文檔有n個句子:

w11,w12,....., w21,w22,.... wn1,wn2,....

那么算法首先找到一個chunk,它會不斷往chunk加入一個句子的所有Token,使得chunk里的token數量大于等于target_seq_length。通常我們期望target_seq_length為max_num_tokens(128-3),這樣padding的盡量少,訓練的效率高。但是有時候我們也需要生成一些短的序列,否則會出現訓練與實際使用不匹配的問題。

找到一個chunk之后,比如這個chunk有5個句子,那么我們隨機的選擇一個切分點,比如3。把前3個句子當成句子A,后兩個句子當成句子B。這是兩個句子A和B有關系的樣本(is_random_next=False)。為了生成無關系的樣本,我們還以50%的概率把B用隨機從其它文檔抽取的句子替換掉,這樣就得到無關系的樣本(is_random_next=True)。如果是這種情況,后面兩個句子需要放回去,以便在下一層循環中能夠被再次利用。

有了句子A和B之后,我們就可以填充tokens和segment_ids,這里會加入特殊的[CLS]和[SEP]。接下來使用create_masked_lm_predictions來隨機的選擇某些Token,把它變成[MASK]。其代碼為:

def create_masked_lm_predictions(tokens, masked_lm_prob,max_predictions_per_seq, vocab_words, rng):# 首先找到可以被替換的下標,[CLS]和[SEP]是不能用于MASK的。cand_indexes = []for (i, token) in enumerate(tokens):if token == "[CLS]" or token == "[SEP]":continuecand_indexes.append(i)# 隨機打散rng.shuffle(cand_indexes)output_tokens = list(tokens)# 構造一個namedtuple,包括index和label兩個屬性。masked_lm = collections.namedtuple("masked_lm", ["index", "label"])# 需要被模型預測的Token個數:min(max_predictions_per_seq(20),實際Token數*15%)num_to_predict = min(max_predictions_per_seq,max(1, int(round(len(tokens) * masked_lm_prob))))masked_lms = []covered_indexes = set()# 隨機的挑選num_to_predict個需要預測的Token# 因為cand_indexes打散過,因此順序的取就行for index in cand_indexes:# 夠了if len(masked_lms) >= num_to_predict:break# 已經挑選過了?似乎沒有必要判斷,因為set會去重。 if index in covered_indexes:continuecovered_indexes.add(index)masked_token = None# 80%的概率把它替換成[MASK]if rng.random() < 0.8:masked_token = "[MASK]"else:# 10%的概率保持不變 if rng.random() < 0.5:masked_token = tokens[index]# 10%的概率隨機替換成詞典里的一個詞。 else:masked_token = vocab_words[rng.randint(0, len(vocab_words) - 1)]output_tokens[index] = masked_tokenmasked_lms.append(masked_lm(index=index, label=tokens[index]))# 按照下標排序,保證是句子中出現的順序。masked_lms = sorted(masked_lms, key=lambda x: x.index)masked_lm_positions = []masked_lm_labels = []for p in masked_lms:masked_lm_positions.append(p.index)masked_lm_labels.append(p.label)return (output_tokens, masked_lm_positions, masked_lm_labels)

最后是使用函數write_instance_to_example_files把前面得到的TrainingInstance用TFRecord的個數寫到文件里,這個函數的核心代碼是:

def write_instance_to_example_files(instances, tokenizer, max_seq_length,max_predictions_per_seq, output_files):features = collections.OrderedDict()features["input_ids"] = create_int_feature(input_ids)features["input_mask"] = create_int_feature(input_mask)features["segment_ids"] = create_int_feature(segment_ids)features["masked_lm_positions"] = create_int_feature(masked_lm_positions)features["masked_lm_ids"] = create_int_feature(masked_lm_ids)features["masked_lm_weights"] = create_float_feature(masked_lm_weights)features["next_sentence_labels"] = create_int_feature([next_sentence_label])tf_example = tf.train.Example(features=tf.train.Features(feature=features))writers[writer_index].write(tf_example.SerializeToString())

接下來我們使用run_pretraining.py腳本進行Pretraining。用法為:

python run_pretraining.py \--input_file=/tmp/tf_examples.tfrecord \--output_dir=/tmp/pretraining_output \--do_train=True \--do_eval=True \--bert_config_file=$BERT_BASE_DIR/bert_config.json \--init_checkpoint=$BERT_BASE_DIR/bert_model.ckpt \--train_batch_size=32 \--max_seq_length=128 \--max_predictions_per_seq=20 \--num_train_steps=20 \--num_warmup_steps=10 \--learning_rate=2e-5

參數都比較容易理解,通常我們需要調整的是num_train_steps、num_warmup_steps和learning_rate。run_pretraining.py的代碼和run_classifier.py很類似,都是用BertModel構建Transformer模型,唯一的區別在于損失函數不同:

def model_fn(features, labels, mode, params): input_ids = features["input_ids"]input_mask = features["input_mask"]segment_ids = features["segment_ids"]masked_lm_positions = features["masked_lm_positions"]masked_lm_ids = features["masked_lm_ids"]masked_lm_weights = features["masked_lm_weights"]next_sentence_labels = features["next_sentence_labels"]is_training = (mode == tf.estimator.ModeKeys.TRAIN)model = modeling.BertModel(config=bert_config,is_training=is_training,input_ids=input_ids,input_mask=input_mask,token_type_ids=segment_ids,use_one_hot_embeddings=use_one_hot_embeddings)(masked_lm_loss,masked_lm_example_loss, masked_lm_log_probs) = get_masked_lm_output(bert_config, model.get_sequence_output(), model.get_embedding_table(),masked_lm_positions, masked_lm_ids, masked_lm_weights)(next_sentence_loss, next_sentence_example_loss,next_sentence_log_probs) = get_next_sentence_output(bert_config, model.get_pooled_output(), next_sentence_labels)total_loss = masked_lm_loss + next_sentence_loss

get_masked_lm_output函數用于計算語言模型的Loss(Mask位置預測的詞和真實的詞是否相同)。

def get_masked_lm_output(bert_config, input_tensor, output_weights, positions,label_ids, label_weights):"""得到masked LM的loss和log概率"""# 只需要Mask位置的Token的輸出。input_tensor = gather_indexes(input_tensor, positions)with tf.variable_scope("cls/predictions"):# 在輸出之前再加一個非線性變換,這些參數只是用于訓練,在Fine-Tuning的時候就不用了。with tf.variable_scope("transform"):input_tensor = tf.layers.dense(input_tensor,units=bert_config.hidden_size,activation=modeling.get_activation(bert_config.hidden_act),kernel_initializer=modeling.create_initializer(bert_config.initializer_range))input_tensor = modeling.layer_norm(input_tensor)# output_weights是復用輸入的word Embedding,所以是傳入的,# 這里再多加一個bias。output_bias = tf.get_variable("output_bias",shape=[bert_config.vocab_size],initializer=tf.zeros_initializer())logits = tf.matmul(input_tensor, output_weights, transpose_b=True)logits = tf.nn.bias_add(logits, output_bias)log_probs = tf.nn.log_softmax(logits, axis=-1)# label_ids的長度是20,表示最大的MASK的Token數# label_ids里存放的是MASK過的Token的idlabel_ids = tf.reshape(label_ids, [-1])label_weights = tf.reshape(label_weights, [-1])one_hot_labels = tf.one_hot(label_ids, depth=bert_config.vocab_size, dtype=tf.float32)# 但是由于實際MASK的可能不到20,比如只MASK18,那么label_ids有2個0(padding)# 而label_weights=[1, 1, ...., 0, 0],說明后面兩個label_id是padding的,計算loss要去掉。per_example_loss = -tf.reduce_sum(log_probs * one_hot_labels, axis=[-1])numerator = tf.reduce_sum(label_weights * per_example_loss)denominator = tf.reduce_sum(label_weights) + 1e-5loss = numerator / denominatorreturn (loss, per_example_loss, log_probs)

get_next_sentence_output函數用于計算預測下一個句子的loss,代碼為:

def get_next_sentence_output(bert_config, input_tensor, labels):"""預測下一個句子是否相關的loss和log概率"""# 簡單的2分類,0表示真的下一個句子,1表示隨機的。這個分類器的參數在實際的Fine-Tuning# 會丟棄掉。 with tf.variable_scope("cls/seq_relationship"):output_weights = tf.get_variable("output_weights",shape=[2, bert_config.hidden_size],initializer=modeling.create_initializer(bert_config.initializer_range))output_bias = tf.get_variable("output_bias", shape=[2], initializer=tf.zeros_initializer())logits = tf.matmul(input_tensor, output_weights, transpose_b=True)logits = tf.nn.bias_add(logits, output_bias)log_probs = tf.nn.log_softmax(logits, axis=-1)labels = tf.reshape(labels, [-1])one_hot_labels = tf.one_hot(labels, depth=2, dtype=tf.float32)per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)loss = tf.reduce_mean(per_example_loss)return (loss, per_example_loss, log_probs)

十、性能測試

本節主要對BERT在工業部署情況的性能測評。性能測試部分主要參考肖涵大神的本篇文章(github上bert-as-service的作者)。因個人硬件配置有限,后續有機會再進行測試補充。

(一)關于max_seq_len對速度的影響

從性能上來講,過大的max_seq_len?會拖慢計算速度,并很有可能造成內存 OOM。

(二)client_batch_size對速度的影響

出于性能考慮,請盡可能每次傳入較多的句子而非一次只傳一個。比如,使用下列方法調用:

#?prepare?your?sent?in?advance bc?=?BertClient() my_sentences?=?[s?for?s?in?my_corpus.iter()] #?doing?encoding?in?one-shot vec?=?bc.encode(my_sentences)


而不要使用:

bc?=?BertClient() vec?=?[] for?s?in?my_corpus.iter():vec.append(bc.encode(s))


如果把 bc = BertClient() 放在了循環之內,則性能會更差。

當然在一些時候,一次僅傳入一個句子無法避免,尤其是在小流量在線環境中。

?

(三)num_client?對并發性和速度的影響

可以看到一個客戶端、一塊 GPU 的處理速度是每秒 381 個句子(句子的長度為 40),兩個客戶端、兩個 GPU 是每秒 402 個,四個客戶端、四個 GPU 的速度是每秒 413 個。當 GPU 的數量增多時,服務對每個客戶端請求的處理速度保持穩定甚至略有增高(因為空隙時刻被更有效地利用)。

?

總結

以上是生活随笔為你收集整理的一本读懂BERT(实践篇)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。