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

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

谷歌BERT预训练源码解析(一):训练数据生成

發(fā)布時(shí)間:2023/11/28 生活经验 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 谷歌BERT预训练源码解析(一):训练数据生成 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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

輸入輸出
關(guān)于輸入和輸出,我們可以直接從官方提供的訓(xùn)練命令行中窺之一二
?

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

可以看到 這里谷歌為我們提供了一個(gè)小的訓(xùn)練樣本sample_text.txt(輸入),將這個(gè)訓(xùn)練樣本進(jìn)行處理后輸出到**tf_examples.tfrecord(輸出)**這個(gè)文件。在sample_text.txt中,空行前后是不同的文章,每個(gè)文章中的每句話都占一行(也就是說每篇文章的上下兩行是一篇文章的上下句)。vocab_file是官方模型中提供的詞匯表。
sample_text.txt
?

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

from __future__ import absolute_import
from __future__ import division
from __future__ import print_functionimport collections
import randomimport tokenization
import tensorflow as tfflags = tf.flagsFLAGS = flags.FLAGSflags.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.")

主函數(shù)
首先獲取輸入文本列表,對輸入文本創(chuàng)建訓(xùn)練實(shí)例,再進(jìn)行輸出
簡要介紹一下FullTokenizer這個(gè)類,它以vocab_file為詞典,將詞轉(zhuǎn)化為該詞對應(yīng)的id,對于某些特殊詞,如johanson,會(huì)先將johanson按照最大長度拆分,再看拆分的部分是否在vocab_file里。vocab_file里有沒有"johanson"這個(gè)詞,但有"johan"和"##son"這兩個(gè)詞,所以將"johanson"這個(gè)詞拆分成兩個(gè)詞(##表示非開頭匹配)
?

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(      #創(chuàng)建訓(xùn)練實(shí)例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)

創(chuàng)建訓(xùn)練實(shí)例

這部分先將文章和每篇文章的每個(gè)句子加到二維列表,再將列表傳入create_instances_from_document生成訓(xùn)練實(shí)例.
返回值:instances 一個(gè)列表 里面包含每個(gè)樣例的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:breakline = line.strip()# Empty lines are used as document delimitersif not line:all_documents.append([])tokens = tokenizer.tokenize(line)if tokens:all_documents[-1].append(tokens)    #二維列表  [文章,句子]# Remove empty documentsall_documents = [x for x in all_documents if x]   #刪除空列表rng.shuffle(all_documents)   #隨機(jī)排序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

?

下一句預(yù)測&實(shí)例生成
這部分是生成訓(xùn)練數(shù)據(jù)的具體過程,對每條數(shù)據(jù)生成TrainingInstance。這里的每條數(shù)據(jù)其實(shí)包含兩個(gè)句子的信息。TrainingInstance包括tokens,segement_ids,is_random_next,masked_lm_positions,masked_lm_labels。下面給出這些屬性的含義
tokens:詞
segement_id:句子編碼 第一句為0 第二句為1
is_random_next:第二句是隨機(jī)查找,還是為第一句的下文
masked_lm_positions:tokens中被mask的位置
masked_lm_labels:tokens中被mask的原來的詞
本部分含有BERT的創(chuàng)新點(diǎn)之一:下一句預(yù)測 類標(biāo)的生成
返回值:instances
以下在關(guān)鍵代碼出進(jìn)行注釋
?

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_tokensif rng.random() < short_seq_prob:         #產(chǎn)生一個(gè)隨機(jī)數(shù)如果小于short_seq_prob 則產(chǎn)生一個(gè)較短的訓(xùn)練序列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 = []    #產(chǎn)生訓(xùn)練集的候選集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` is how many segments from `current_chunk` go into the `A`# (first) sentence.a_end = 1if len(current_chunk) >= 2:a_end = rng.randint(1, len(current_chunk) - 1)           #從current_chunk中隨機(jī)選出一個(gè)文檔作為句子1的截止文檔tokens_a = []for j in range(a_end):tokens_a.extend(current_chunk[j])   #將截止文檔之前的文檔都加入到tokens_atokens_b = []# Random nextis_random_next = Falseif len(current_chunk) == 1 or rng.random() < 0.5:    #候選集只有一句的情況則隨機(jī)抽取句子作為句子2;或以0.5的概率隨機(jī)抽取句子作為句子2is_random_next = Truetarget_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:breakrandom_document = all_documents[random_document_index]        #隨機(jī)找一個(gè)文檔作為截止文檔random_start = rng.randint(0, len(random_document) - 1)                #隨機(jī)找一個(gè)初始文檔for j in range(random_start, len(random_document)):                      tokens_b.extend(random_document[j])                                           #將隨機(jī)文檔加入到token_bif 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_endi -= num_unused_segments# Actual nextelse:is_random_next = False                       以第1句的后續(xù)作為句子2for 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)      #對兩個(gè)句子進(jìn)行長度剪裁assert len(tokens_a) >= 1assert len(tokens_b) >= 1tokens = []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創(chuàng)建masktokens, 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

隨機(jī)遮蔽
這部分對token進(jìn)行隨機(jī)mask。這部分是BERT的創(chuàng)新點(diǎn)之二,隨機(jī)遮蔽。為了防止雙向模型在多層之后“看到自己”。這里對一部分詞進(jìn)行隨機(jī)遮蔽,并在預(yù)訓(xùn)練中進(jìn)行預(yù)測。遮蔽方案:
1.以80%的概率直接變成[MASK]
2.以10%的概率保留原詞
3.以10%的概率在詞典中隨機(jī)找一個(gè)詞替代
返回值:經(jīng)過隨機(jī)遮蔽后的(詞,遮蔽位置,遮蔽前原詞)
?

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]":continuecand_indexes.append(i)rng.shuffle(cand_indexes)                 #打亂順序output_tokens = list(tokens)masked_lm = collections.namedtuple("masked_lm", ["index", "label"])  # p定義一個(gè)名為masked_lm的元組,里面有兩個(gè)屬性num_to_predict = min(max_predictions_per_seq,max(1, int(round(len(tokens) * masked_lm_prob))))  #所有要mask的詞的數(shù)量為定值,取兩個(gè)定義好參數(shù)的最小值masked_lms = []
covered_indexes = set()
for index in cand_indexes:if len(masked_lms) >= num_to_predict:breakif index in covered_indexes:continuecovered_indexes.add(index)              #要被mask的詞的indexmasked_token = None# 80% of the time, replace with [MASK]          if rng.random() < 0.8:masked_token = "[MASK]"else:# 10% of the time, keep originalif rng.random() < 0.5:masked_token = tokens[index]# 10% of the time, replace with random wordelse: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的indexmasked_lm_labels.append(p.label)                 #被mask的label(即原詞)return (output_tokens, masked_lm_positions, masked_lm_labels)

?

輸出

最后是將處理好的數(shù)據(jù)保存為tfrecord文件。首先將token轉(zhuǎn)為id,增加input_mask用于記錄實(shí)句長度。最后將不到最大長度的部分用0補(bǔ)齊。

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 = 0total_written = 0for (inst_index, instance) in enumerate(instances):input_ids = tokenizer.convert_tokens_to_ids(instance.tokens)      #詞轉(zhuǎn)idinput_mask = [1] * len(input_ids)                                    segment_ids = list(instance.segment_ids)        assert len(input_ids) <= max_seq_lengthwhile len(input_ids) < max_seq_length:            #未到最大長度時(shí)后面補(bǔ)0input_ids.append(0)input_mask.append(0)segment_ids.append(0)assert len(input_ids) == max_seq_lengthassert len(input_mask) == max_seq_lengthassert len(segment_ids) == max_seq_lengthmasked_lm_positions = list(instance.masked_lm_positions)                      #mask位置記錄masked_lm_ids = tokenizer.convert_tokens_to_ids(instance.masked_lm_labels)    #mask預(yù)測值轉(zhuǎn)idmasked_lm_weights = [1.0] * len(masked_lm_ids)              #mask位置的權(quán)重都為1,用于排除后續(xù)的“0”以便loss計(jì)算while len(masked_lm_positions) < max_predictions_per_seq:      #補(bǔ)0masked_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 0features = 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))      #生成訓(xùn)練樣例writers[writer_index].write(tf_example.SerializeToString())     #輸出到文件writer_index = (writer_index + 1) % len(writers)   total_written += 1if inst_index < 20:               對前20個(gè)訓(xùn)練樣例進(jìn)行打印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.valueelif feature.float_list.value:values = feature.float_list.valuetf.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)

?

結(jié)果一覽

最后打印的結(jié)果是這醬的

?

?

谷歌對訓(xùn)練數(shù)據(jù)的處理就介紹這么多,如果有錯(cuò)誤歡迎大家批評指正,如果有問題也歡迎大家提問互相探討。關(guān)于模型篇的代碼解析我會(huì)在下一篇博客中給出。

?

?

?

?

?

?

?

?

?

?

?

總結(jié)

以上是生活随笔為你收集整理的谷歌BERT预训练源码解析(一):训练数据生成的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。