1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > NLP Transformer 模型中 BPE(byte pair encoding 英文分词)详解 GPT-2 中的实现

NLP Transformer 模型中 BPE(byte pair encoding 英文分词)详解 GPT-2 中的实现

时间:2023-05-27 02:40:10

相关推荐

NLP Transformer 模型中 BPE(byte pair encoding 英文分词)详解 GPT-2 中的实现

NLP 中Tranformer模型的BPE详解(GPT-2)

简单解释概念 BPE—byte pair encoding:GPT-2 中的实现gpt-2 代码解读

简单解释概念 BPE—byte pair encoding:

Transformer NLP 预训练模型都通过 embedding 词典来表征词义,

当遇见没见过的词的时候以前是用"< u nk>"代替,这样会造成对新事物(新词、网络词、简写词)理解能力很差,BPE就是来解决这个问题的。

英文中会有词根和造词现象

例如:“greenhand”如果你的词典中没有这个词,那么就可以把它拆成 **“green”,“hand”**两个词,这里green 向量 会跟发芽一类的词相近有新生的意思hand有操作手的意思那么就不难推测出greenhand是新手。

这个过程中会参考一个词典,这个词典从上往下是一个个词对,对应的顺序就是它出现的频率 越往上的词越高频率。

对应中文 相当于分词了。

GPT-2 中的实现

"""Byte pair encoding utilities"""import osimport jsonimport regex as refrom functools import lru_cache# 生成把bytes抓华为unicode词典 {97:“a”...}@lru_cache()def bytes_to_unicode():"""Returns list of utf-8 byte and a corresponding list of unicode strings.The reversible bpe codes work on unicode strings.This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.This is a signficant percentage of your normal, say, 32K bpe vocab.To avoid that, we want lookup tables between utf-8 bytes and unicode strings.And avoids mapping to whitespace/control characters the bpe code barfs on."""bs = list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))cs = bs[:]n = 0for b in range(2 ** 8):if b not in bs:bs.append(b)cs.append(2 ** 8 + n)n += 1cs = [chr(n) for n in cs]return dict(zip(bs, cs))# 把words做成一对一对的 传入"ABCD" 输出(('B', 'C'), ('A', 'B'), ('C', 'D'))def get_pairs(word):"""Return set of symbol pairs in a word.Word is represented as tuple of symbols (symbols being variable-length strings)."""pairs = set()prev_char = word[0]for char in word[1:]:pairs.add((prev_char, char))prev_char = charreturn pairsclass Encoder:def __init__(self, encoder, bpe_merges, errors='replace'):self.encoder = encoder #外部embedding词典self.decoder = {v: k for k, v in self.encoder.items()}self.errors = errors # how to handle errors in decodingself.byte_encoder = bytes_to_unicode()self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}self.bpe_ranks = dict(zip(bpe_merges,range(len(bpe_merges)))) # bpe_merges 是一个类似(Ġ t)(这里的这两个元素 是未来要用的 a b ) 元组 然后在用0123..的常用频率压缩起来成一个{(Ġ t):1}# bpe_merges里面是各种零散词的常用程度排名self.cache = {}# Should haved added re.IGNORECASE so BPE merges can happen for capitalized versions of contractionsself.pat = pile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")# 用来识别未见过的词语 把词拆成各个词源 例如:输入greenhand 输出"green hand"def bpe(self, token):# 如果dict(self.cache)中有token的key 那就返回对应的值(有缓存结果)if token in self.cache:return self.cache[token]word = tuple(token) # 把list 转成 tuple# 下面就是把一个词,拆散了 输入(fiend) 输出((f,i),(i,e),(e,n),(n,d)) 注意返回set无序pairs = get_pairs(word)# 词很短 拆不了 直接返回 tokenif not pairs:return token# 迭代所有的pairs 中的词对while True: # lambda 迭代对象:对应表达式# 将输入的pairs 按照.bpe文件 (常用排名)排序 这里的pair 就是 55行提到 a b# 找到最常用的哪个 pair float('inf') 表示无穷大 找不到的话 就返回无限大的值 以免被选上bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float('inf'))) # MIN MAX 中key 相当于依据什么排序# 组合不在bpe表格中 pairs中不能再拆了 循环结束if bigram not in self.bpe_ranks:break# 拿到第一个词 第二个词first, second = bigram # 拿到拆开的的对里 在表格里最常用的那一对new_word = []i = 0# 查找子串while i < len(word):try:j = word.index(first, i) # i指的是从第I个开始查找 #查找list.index(x,起始位置,终止位置) #从传入的word里 查找第一个单词# 这里的意思是 因为pair 是无序的 要找到其在输入词中的顺序new_word.extend(word[i:j]) # 将这个子串 first=word[i:j] 放入new_word变量中i = j # 移动指针except:new_word.extend(word[i:]) # 当J越界时候 直接将 i: 切片放进去break# 这里的意思是 如果first 和 second 这两个是连着的话 加到new_word时候 是一个整体if word[i] == first and i < len(word) - 1 and word[i + 1] == second:new_word.append(first + second)i += 2# 否则的话 只加入word[i] ??这块有点迷 后续更新一下else:new_word.append(word[i])i += 1#类似于递归查找new_word = tuple(new_word)word = new_word#串不能再拆了if len(word) == 1:breakelse:#拆开再找一遍pairs = get_pairs(word)#用空格链接所有的词 word = ' '.join(word)#增加这个词的缓存,以后再碰到就不用运算了self.cache[token] = wordreturn word# 不在self.encoder词典的词 编码过程def encode(self, text):bpe_tokens = []#self.pat .findall text 的意思是从text 中 把self.pat这里pattern找出来 其实就是she's 变成 she s两个单词for token in re.findall(self.pat, text):token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8'))#上面一句大致等价于 token = unicode(token, "utf-8") #将文字转成utf-8后 用self.byte_encoder——bytes_to_unicode()产生的dict 转回字符形式 然后将其连城字符串bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' '))#将拆完的词 在传入的embedding字典中查找,返回这个列表return bpe_tokensdef decode(self, tokens):text = ''.join([self.decoder[token] for token in tokens])text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors=self.errors)return textdef get_encoder(model_name, models_dir):with open(os.path.join(models_dir, model_name, 'encoder.json'), 'r') as f:encoder = json.load(f)with open(os.path.join(models_dir, model_name, 'vocab.bpe'), 'r', encoding="utf-8") as f:bpe_data = f.read()bpe_merges = [tuple(merge_str.split()) for merge_str in bpe_data.split('\n')[1:-1]]return Encoder(encoder=encoder,bpe_merges=bpe_merges,)

gpt-2 代码解读

gpt-2是OpenAI 旗下的 transformer 型NLP模型,对英文有着巨大的理解能力,目前最强参数达到了1.5Gb,有兴趣盆友可以上openAI看看.gpt-2跟bert应该差不多,这里建议大家学习transformer语言模型就行。如果很多人喜欢的话后面会出一个中文版的GPT-2代码解读,跟下面的原版会不太一样。基本都是代码加注释的。

下面是我找到觉得比较有用的资源

GPT-2代码详解文章:

代码详解

BPE:参考视频连接 :油管搜"BERT Research - Ep. 2 - WordPiece Embeddings" 7:32部分开始

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。