谷歌BERT預訓練源碼解析(一):訓練數據生成


目錄
預訓練源碼結構簡介
輸入輸出
源碼解析
參數
主函數
創建訓練實例
下一句預測&實例生成
隨機遮蔽
輸出
結果一覽
預訓練源碼結構簡介
關於BERT,簡單來說,它是一個基於Transformer架構,結合遮蔽詞預測和上下句識別的預訓練NLP模型。至於效果:在11種不同NLP測試中創出最佳成績
關於介紹BERT的文章我看了一些,個人感覺介紹的最全面的是機器之心
再放上谷歌官方源碼鏈接:BERT官方源碼
在看本博客之前,讀者先要了解:
1.Transformer架構
2.BERT模型的創新之處
3.python語言及tensorflow框架
我會在代碼中直接指出對應的原理,如果沒有了解架構直接剛代碼可能會有些吃力
BERT的預訓練主要分為三個部分:
1.預訓練數據的預處理(create_pretraining_data.py)
2.核心模型的構建(modeling.py)
3.訓練過程(run_pretraining.py)
我將分三次分別介紹這三個部分的源碼,這次先介紹訓練數據的訓練數據生成腳本即create_pretraining_data.py。

輸入輸出
關於輸入和輸出,我們可以直接從官方提供的訓練命令行中窺之一二

python create_pretraining_data.py \
--input_file=./sample_text.txt \
--output_file=/tmp/tf_examples.tfrecord \
--vocab_file=$BERT_BASE_DIR/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
1
2
3
4
5
6
7
8
9
10
可以看到 這里谷歌為我們提供了一個小的訓練樣本sample_text.txt(輸入),將這個訓練樣本進行處理后輸出到**tf_examples.tfrecord(輸出)**這個文件。在sample_text.txt中,空行前后是不同的文章,每個文章中的每句話都占一行(也就是說每篇文章的上下兩行是一篇文章的上下句)。vocab_file是官方模型中提供的詞匯表。
sample_text.txt


源碼解析
參數
input_file:指定輸入文檔路徑
output_file:指定輸出路徑
vocab_file:指定詞典路徑(谷歌已在預訓練模型中提供)
do_lower_case:為True則忽略大小寫
max_seq_length:每一條訓練數據(兩句話)相加后的最大長度限制
max_predictions_per_seq:每一條訓練數據mask的最大數量
random_seed:一個隨機種子
dupe_factor:對文檔多次重復隨機產生訓練集,隨機的次數
masked_lm_prob:一條訓練數據產生mask的概率,即每條訓練數據隨機產生max_predictions_per_seq×masked_lm_prob數量的mask
short_seq_prob:為了縮小預訓練和微調過程的差距,以此概率產生小於max_seq_length的訓練數據

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import collections
import random

import tokenization
import tensorflow as tf

flags = tf.flags

FLAGS = flags.FLAGS

flags.DEFINE_string("input_file", None,
"Input raw text file (or comma-separated list of files).")

flags.DEFINE_string(
"output_file", None,
"Output TF example file (or comma-separated list of files).")

flags.DEFINE_string("vocab_file", None,
"The vocabulary file that the BERT model was trained on.")

flags.DEFINE_bool(
"do_lower_case", True,
"Whether to lower case the input text. Should be True for uncased "
"models and False for cased models.")

flags.DEFINE_integer("max_seq_length", 128, "Maximum sequence length.")

flags.DEFINE_integer("max_predictions_per_seq", 20,
"Maximum number of masked LM predictions per sequence.")

flags.DEFINE_integer("random_seed", 12345, "Random seed for data generation.")

flags.DEFINE_integer(
"dupe_factor", 10,
"Number of times to duplicate the input data (with different masks).")

flags.DEFINE_float("masked_lm_prob", 0.15, "Masked LM probability.")

flags.DEFINE_float(
"short_seq_prob", 0.1,
"Probability of creating sequences which are shorter than the "
"maximum length.")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
主函數
首先獲取輸入文本列表,對輸入文本創建訓練實例,再進行輸出
簡要介紹一下FullTokenizer這個類,它以vocab_file為詞典,將詞轉化為該詞對應的id,對於某些特殊詞,如johanson,會先將johanson按照最大長度拆分,再看拆分的部分是否在vocab_file里。vocab_file里有沒有"johanson"這個詞,但有"johan"和"##son"這兩個詞,所以將"johanson"這個詞拆分成兩個詞(##表示非開頭匹配)

def main(_):
tf.logging.set_verbosity(tf.logging.INFO)

tokenizer = tokenization.FullTokenizer(
vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)

input_files = []
for input_pattern in FLAGS.input_file.split(","):
input_files.extend(tf.gfile.Glob(input_pattern)) #獲得輸入文件列表

tf.logging.info("*** Reading from input files ***")
for input_file in input_files:
tf.logging.info(" %s", input_file)

rng = 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 = FLAGS.output_file.split(",")
tf.logging.info("*** Writing to output files ***")
for output_file in output_files:
tf.logging.info(" %s", output_file)

write_instance_to_example_files(instances, tokenizer, FLAGS.max_seq_length, #輸出
FLAGS.max_predictions_per_seq, output_files)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
創建訓練實例
這部分先將文章和每篇文章的每個句子加到二維列表,再將列表傳入create_instances_from_document生成訓練實例.
返回值:instances 一個列表 里面包含每個樣例的TrainingInstance類

def create_training_instances(input_files, tokenizer, max_seq_length,
dupe_factor, short_seq_prob, masked_lm_prob,
max_predictions_per_seq, rng):
"""Create `TrainingInstance`s from raw text."""
all_documents = [[]]

# Input file format:
# (1) One sentence per line. These should ideally be actual sentences, not
# entire paragraphs or arbitrary spans of text. (Because we use the
# sentence boundaries for the "next sentence prediction" task).
# (2) Blank lines between documents. Document boundaries are needed so
# that the "next sentence prediction" task doesn't span between documents.
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:
break
line = line.strip()

# Empty lines are used as document delimiters
if not line:
all_documents.append([])
tokens = tokenizer.tokenize(line)
if tokens:
all_documents[-1].append(tokens) #二維列表 [文章,句子]

# Remove empty documents
all_documents = [x for x in all_documents if x] #刪除空列表
rng.shuffle(all_documents) #隨機排序

vocab_words = list(tokenizer.vocab.keys())
instances = []
for _ in range(dupe_factor):
for document_index in range(len(all_documents)):
instances.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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
下一句預測&實例生成
這部分是生成訓練數據的具體過程,對每條數據生成TrainingInstance。這里的每條數據其實包含兩個句子的信息。TrainingInstance包括tokens,segement_ids,is_random_next,masked_lm_positions,masked_lm_labels。下面給出這些屬性的含義
tokens:詞
segement_id:句子編碼 第一句為0 第二句為1
is_random_next:第二句是隨機查找,還是為第一句的下文
masked_lm_positions:tokens中被mask的位置
masked_lm_labels:tokens中被mask的原來的詞
本部分含有BERT的創新點之一:下一句預測 類標的生成
返回值:instances
以下在關鍵代碼出進行注釋

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):
"""Creates `TrainingInstance`s for a single document."""
document = all_documents[document_index]

# Account for [CLS], [SEP], [SEP]
max_num_tokens = max_seq_length - 3

# We *usually* want to fill up the entire sequence since we are padding
# to `max_seq_length` anyways, so short sequences are generally wasted
# computation. However, we *sometimes*
# (i.e., short_seq_prob == 0.1 == 10% of the time) want to use shorter
# sequences to minimize the mismatch between pre-training and fine-tuning.
# The `target_seq_length` is just a rough target however, whereas
# `max_seq_length` is a hard limit.
target_seq_length = max_num_tokens
if rng.random() < short_seq_prob: #產生一個隨機數如果小於short_seq_prob 則產生一個較短的訓練序列
target_seq_length = rng.randint(2, max_num_tokens)

# We DON'T just concatenate all of the tokens from a document into a long
# sequence and choose an arbitrary split point because this would make the
# next sentence prediction task too easy. Instead, we split the input into
# segments "A" and "B" based on the actual "sentences" provided by the user
# input.
instances = []
current_chunk = [] #產生訓練集的候選集
current_length = 0
i = 0
while 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` is how many segments from `current_chunk` go into the `A`
# (first) sentence.
a_end = 1
if len(current_chunk) >= 2:
a_end = rng.randint(1, len(current_chunk) - 1) #從current_chunk中隨機選出一個文檔作為句子1的截止文檔

tokens_a = []
for j in range(a_end):
tokens_a.extend(current_chunk[j]) #將截止文檔之前的文檔都加入到tokens_a

tokens_b = []
# Random next
is_random_next = False
if len(current_chunk) == 1 or rng.random() < 0.5: #候選集只有一句的情況則隨機抽取句子作為句子2;或以0.5的概率隨機抽取句子作為句子2
is_random_next = True
target_b_length = target_seq_length - len(tokens_a)

# This should rarely go for more than one iteration for large
# corpora. However, just to be careful, we try to make sure that
# the random document is not the same as the document
# we're processing.
for _ in range(10):
random_document_index = rng.randint(0, len(all_documents) - 1)
if random_document_index != document_index:
break

random_document = all_documents[random_document_index] #隨機找一個文檔作為截止文檔
random_start = rng.randint(0, len(random_document) - 1) #隨機找一個初始文檔
for j in range(random_start, len(random_document)):
tokens_b.extend(random_document[j]) #將隨機文檔加入到token_b
if len(tokens_b) >= target_b_length:
break
# We didn't actually use these segments so we "put them back" so
# they don't go to waste.
num_unused_segments = len(current_chunk) - a_end
i -= num_unused_segments
# Actual next
else:
is_random_next = False 以第1句的后續作為句子2
for 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) #對兩個句子進行長度剪裁

assert len(tokens_a) >= 1
assert len(tokens_b) >= 1

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)

for token in tokens_b:
tokens.append(token)
segment_ids.append(1)
tokens.append("[SEP]")
segment_ids.append(1)

(tokens, masked_lm_positions,
masked_lm_labels) = create_masked_lm_predictions( #對token創建mask
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 = 0
i += 1

return instances
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
隨機遮蔽
這部分對token進行隨機mask。這部分是BERT的創新點之二,隨機遮蔽。為了防止雙向模型在多層之后“看到自己”。這里對一部分詞進行隨機遮蔽,並在預訓練中進行預測。遮蔽方案:
1.以80%的概率直接變成[MASK]
2.以10%的概率保留原詞
3.以10%的概率在詞典中隨機找一個詞替代
返回值:經過隨機遮蔽后的(詞,遮蔽位置,遮蔽前原詞)

def create_masked_lm_predictions(tokens, masked_lm_prob,
max_predictions_per_seq, vocab_words, rng):
"""Creates the predictions for the masked LM objective."""

cand_indexes = []
for (i, token) in enumerate(tokens):
if token == "[CLS]" or token == "[SEP]":
continue
cand_indexes.append(i)

rng.shuffle(cand_indexes) #打亂順序

output_tokens = list(tokens)

masked_lm = collections.namedtuple("masked_lm", ["index", "label"]) # p定義一個名為masked_lm的元組,里面有兩個屬性

num_to_predict = min(max_predictions_per_seq,
max(1, int(round(len(tokens) * masked_lm_prob)))) #所有要mask的詞的數量為定值,取兩個定義好參數的最小值

masked_lms = []
covered_indexes = set()
for index in cand_indexes:
if len(masked_lms) >= num_to_predict:
break
if index in covered_indexes:
continue
covered_indexes.add(index) #要被mask的詞的index

masked_token = None
# 80% of the time, replace with [MASK]
if rng.random() < 0.8:
masked_token = "[MASK]"
else:
# 10% of the time, keep original
if rng.random() < 0.5:
masked_token = tokens[index]
# 10% of the time, replace with random word
else:
masked_token = vocab_words[rng.randint(0, len(vocab_words) - 1)]

output_tokens[index] = masked_token #用masked_token替換原詞

masked_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) #被mask的index
masked_lm_labels.append(p.label) #被mask的label(即原詞)

return (output_tokens, masked_lm_positions, masked_lm_labels)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
輸出
最后是將處理好的數據保存為tfrecord文件。首先將token轉為id,增加input_mask用於記錄實句長度。最后將不到最大長度的部分用0補齊。

def write_instance_to_example_files(instances, tokenizer, max_seq_length,
max_predictions_per_seq, output_files):
"""Create TF example files from `TrainingInstance`s."""
writers = []
for output_file in output_files:
writers.append(tf.python_io.TFRecordWriter(output_file))

writer_index = 0

total_written = 0
for (inst_index, instance) in enumerate(instances):
input_ids = tokenizer.convert_tokens_to_ids(instance.tokens) #詞轉id
input_mask = [1] * len(input_ids)
segment_ids = list(instance.segment_ids)
assert len(input_ids) <= max_seq_length

while len(input_ids) < max_seq_length: #未到最大長度時后面補0
input_ids.append(0)
input_mask.append(0)
segment_ids.append(0)

assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length

masked_lm_positions = list(instance.masked_lm_positions) #mask位置記錄
masked_lm_ids = tokenizer.convert_tokens_to_ids(instance.masked_lm_labels) #mask預測值轉id
masked_lm_weights = [1.0] * len(masked_lm_ids) #mask位置的權重都為1,用於排除后續的“0”以便loss計算

while len(masked_lm_positions) < max_predictions_per_seq: #補0
masked_lm_positions.append(0)
masked_lm_ids.append(0)
masked_lm_weights.append(0.0)

next_sentence_label = 1 if instance.is_random_next else 0

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()) #輸出到文件
writer_index = (writer_index + 1) % len(writers)

total_written += 1

if inst_index < 20: 對前20個訓練樣例進行打印
tf.logging.info("*** Example ***")
tf.logging.info("tokens: %s" % " ".join(
[tokenization.printable_text(x) for x in instance.tokens]))

for feature_name in features.keys():
feature = features[feature_name]
values = []
if feature.int64_list.value:
values = feature.int64_list.value
elif feature.float_list.value:
values = feature.float_list.value
tf.logging.info(
"%s: %s" % (feature_name, " ".join([str(x) for x in values])))

for writer in writers:
writer.close()

tf.logging.info("Wrote %d total instances", total_written)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
結果一覽
最后打印的結果是這醬的

 

谷歌對訓練數據的處理就介紹這么多,如果有錯誤歡迎大家批評指正,如果有問題也歡迎大家提問互相探討。關於模型篇的代碼解析我會在下一篇博客中給出。
---------------------
作者:保持一份率性
來源:CSDN
原文:https://blog.csdn.net/weixin_39470744/article/details/84373933
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM