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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

一本读懂BERT

發布時間:2023/12/15 编程问答 48 豆豆
生活随笔 收集整理的這篇文章主要介紹了 一本读懂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是在現有預訓練工作的基礎上對現有的技術的良好整合與一定的創新。現有的這些模型都是單向或淺雙向的。每個單詞僅使用左側(或右側)的單詞進行語境化。例如,在句子中

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:
  • continue
  • guid = "%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_tokens
  • def 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):
  • continue
  • if _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 False
  • cat = unicodedata.category(char)
  • if cat.startswith("C"):
  • return True
  • return 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 True
  • cat = unicodedata.category(char)
  • if cat == "Zs":
  • return True
  • return 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 True
  • return 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":
  • continue
  • output.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 True
  • cat = unicodedata.category(char)
  • # category是P開頭的都是標點,參考https://en.wikipedia.org/wiki/Unicode_character_property
  • if cat.startswith("P"):
  • return True
  • return 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)
  • continue
  • is_bad = False
  • start = 0
  • sub_tokens = []
  • while start < len(chars):
  • end = len(chars)
  • cur_substr = None
  • while start < end:
  • substr = "".join(chars[start:end])
  • if start > 0:
  • substr = "##" + substr
  • if substr in self.vocab:
  • cur_substr = substr
  • break
  • end -= 1
  • if cur_substr is None:
  • is_bad = True
  • break
  • sub_tokens.append(cur_substr)
  • start = end
  • if 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 = None
  • num_train_steps = None
  • num_warmup_steps = None
  • if 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或者CPU
  • estimator = 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 = None
  • eval_drop_remainder = True if FLAGS.use_tpu else False
  • eval_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 False
  • predict_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 f
  • features = 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] = i
  • tokens_a = tokenizer.tokenize(example.text_a)
  • tokens_b = None
  • if 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_length
  • while 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:
  • break
  • if 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] = t
  • return example
  • def 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 d
  • return 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
  • # 構造訓練的spec
  • if 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的spec
  • elif 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)
  • # 預測的spec
  • else:
  • output_spec = tf.contrib.tpu.TPUEstimatorSpec(
  • mode=mode,
  • predictions=probabilities,
  • scaffold_fn=scaffold_fn)
  • return output_spec
  • return 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()
  • # 默認是768
  • hidden_size = output_layer.shape[-1].value
  • output_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的概率會dropout
  • output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)
  • # 對[CLS]輸出的768的向量再做一個線性變換,輸出為label的個數。得到logits
  • logits = 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=3
  • input_ids = tf.constant([[31, 51, 99], [15, 5, 0]])
  • # 第一個例子實際長度為3,第二個例子長度為2
  • input_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,全連接層的隱單元是1024
  • config = modeling.BertConfig(vocab_size=32000, hidden_size=512,
  • num_hidden_layers=8, num_attention_heads=6, intermediate_size=1024)
  • # 創建BertModel
  • model = modeling.BertModel(config=config, is_training=True,
  • input_ids=input_ids, input_mask=input_mask, token_type_ids=token_type_ids)
  • # label_embeddings用于把512的隱單元變換成logits
  • label_embeddings = tf.get_variable(...)
  • # 得到[CLS]最后一層輸出,把它看成句子的Embedding(Encoding)
  • pooled_output = model.get_pooled_output()
  • # 計算logits
  • logits = 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.0
  • config.attention_probs_dropout_prob = 0.0
  • input_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 embedding
  • Args:
  • input_ids: int32 Tensor shape為[batch_size, seq_length],表示WordPiece的id
  • vocab_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`的Embedding
  • token_type_ids: (可選) int32 Tensor shape為[batch_size, seq_length]
  • 如果`use_token_type`為True則必須有值
  • token_type_vocab_size: int Token Type的個數,通常是2
  • token_type_embedding_name: string Token type Embedding的名字
  • use_position_embeddings: bool 是否使用位置Embedding
  • position_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_tensor
  • if 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_embeddings
  • if 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_embeddings
  • num_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_embeddings
  • output = 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_mask
  • return 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.03762
  • Also see:
  • https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/models/transformer.py
  • Args:
  • 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. 全連接層的隱單元個數
  • 總結

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

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