Hugging face 是一家总部位于纽约的聊天机器人初创服务商,开发的应用在青少年中颇受欢迎,相比于其他公司,Hugging Face更加注重产品带来的情感以及环境因素。官网链接在此 https://huggingface.co/ 。
但更令它广为人知的是Hugging Face专注于NLP技术,拥有大型的开源社区。尤其是在github上开源的自然语言处理,预训练模型库 Transformers,已被下载超过一百万次,github上超过24000个star。Transformers 提供了NLP领域大量state-of-art的 预训练语言模型结构的模型和调用框架。以下是repo的链接(https://github.com/huggingface/transformers)
这个库最初的名称是pytorch-pretrained-bert,它随着BERT一起应运而生。Google2018年10月底在 https://github.com/google-research/bert 开源了BERT的tensorflow实现。当时,BERT以其强劲的性能,引起NLPer的广泛关注。几乎与此同时,pytorch-pretrained-bert也开始了它的第一次提交。pytorch-pretrained-bert 用当时已有大量支持者的pytorch框架复现了BERT的性能,并提供预训练模型的下载,使没有足够算力的开发者们也能够在几分钟内就实现 state-of-art-fine-tuning。到目前为止,transformers 提供了超过100种语言的,32种预训练语言模型,简单,强大,高性能,是新手入门的不二选择。
CL2020 Best Paper有一篇论文提名奖,《Don’t Stop Pretraining: Adapt Language Models to Domains and Tasks》。这篇论文做了很多语言模型预训练的实验,系统的分析了语言模型预训练对子任务的效果提升情况。有几个主要结论:
- 在目标领域的数据集上继续预训练(DAPT)可以提升效果;目标领域的语料与RoBERTa的原始预训练语料越不相关,DAPT效果则提升更明显。
- 在具体任务的数据集上继续预训练(TAPT)可以十分“廉价”地提升效果。
- 结合二者(先进行DAPT,再进行TAPT)可以进一步提升效果。
- 如果能获取更多的、任务相关的无标注数据继续预训练(Curated-TAPT),效果则最佳。
- 如果无法获取更多的、任务相关的无标注数据,采取一种十分轻量化的简单数据选择策略,效果也会提升。
知乎专栏《高能NLP》 https://zhuanlan.zhihu.com/p/149210123
虽然在bert上语言模型预训练在算法比赛中已经是一个稳定的上分操作。但是上面这篇文章难能可贵的是对这个操作进行了系统分析。大部分中文语言模型都是在tensorflow上训练的,一个常见例子是中文roberta项目。可以参考
https://github.com/brightmart/roberta_zh
使用pytorch进行中文bert语言模型预训练的例子比较少。在huggingface的Transformers中,有一部分代码支持语言模型预训练(不是很丰富,很多功能都不支持比如wwm)。
为了用最少的代码成本完成bert语言模型预训练,本文借鉴了里面的一些现成代码。也尝试分享一下使用pytorch进行语言模型预训练的一些经验。主要有三个常见的中文bert语言模型
- bert-base-chinese
- roberta-wwm-ext
- ernie
1 bert-base-chinese
(https://huggingface.co/bert-base-chinese)
这是最常见的中文bert语言模型,基于中文维基百科相关语料进行预训练。把它作为baseline,在领域内无监督数据进行语言模型预训练很简单。只需要使用官方给的例子就好。
https://github.com/huggingface/transformers/tree/master/examples/language-modeling
(本文使用的transformers更新到3.0.2)
其中$TRAIN_FILE 代表领域相关中文语料地址。
python run_language_modeling.py \
--output_dir=output \
--model_type=bert \
--model_name_or_path=bert-base-chinese \
--do_train \
--train_data_file=$TRAIN_FILE \
--do_eval \
--eval_data_file=$TEST_FILE \
--mlm
2 roberta-wwm-ext
(https://github.com/ymcui/Chinese-BERT-wwm)
哈工大讯飞联合实验室发布的预训练语言模型。预训练的方式是采用roberta类似的方法,比如动态mask,更多的训练数据等等。在很多任务中,该模型效果要优于bert-base-chinese。
对于中文roberta类的pytorch模型,使用方法如下
import torch
from transformers import BertTokenizer, BertModel
tokenizer = BertTokenizer.from_pretrained("hfl/chinese-roberta-wwm-ext")
roberta = BertModel.from_pretrained("hfl/chinese-roberta-wwm-ext")
切记不可使用官方推荐的
tokenizer = AutoTokenizer.from_pretrained("hfl/chinese-roberta-wwm-ext")
model = AutoModel.from_pretrained("hfl/chinese-roberta-wwm-ext")
因为中文roberta类的配置文件比如vocab.txt,都是采用bert的方法设计的。英文roberta模型读取配置文件的格式默认是vocab.json。对于一些英文roberta模型,倒是可以通过AutoModel自动读取。这就解释了huggingface的模型库的中文roberta示例代码为什么跑不通。
如果要基于上面的代码run_language_modeling.py继续预训练roberta。还需要做两个改动。
- 下载roberta-wwm-ext到本地目录hflroberta,在config.json中修改“model_type”:"roberta"为"model_type":"bert"。
- 对上面的run_language_modeling.py中的AutoModel和AutoTokenizer都进行替换为BertModel和BertTokenizer。
python run_language_modeling_roberta.py \
--output_dir=output \
--model_type=bert \
--model_name_or_path=hflroberta \
--do_train \
--train_data_file=$TRAIN_FILE \
--do_eval \
--eval_data_file=$TEST_FILE \
--mlm
3 ernie
(https://github.com/nghuyong/ERNIE-Pytorch)
ernie是百度发布的基于百度知道贴吧等中文语料结合实体预测等任务生成的预训练模型。这个模型的准确率在某些任务上要优于bert-base-chinese和roberta。如果基于ernie1.0模型做领域数据预训练的话只需要一步修改。
下载ernie1.0到本地目录ernie,在config.json中增加字段"model_type":"bert"。
python run_language_modeling.py \
--output_dir=output \
--model_type=bert \
--model_name_or_path=ernie \
--do_train \
--train_data_file=$TRAIN_FILE \
--do_eval \
--eval_data_file=$TEST_FILE \
--mlm
最后,huggingface项目中语言模型预训练用mask方式如下。仍是按照15%的数据随机mask然后预测自身。如果要做一些高级操作比如whole word masking或者实体预测,可以自行修改transformers.DataCollatorForLanguageModeling。
def mask_tokens(self, inputs: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original.
"""
if self.tokenizer.mask_token is None:
raise ValueError(
"This tokenizer does not have a mask token which is necessary for masked language modeling. Remove the --mlm flag if you want to use this tokenizer."
)
labels = inputs.clone()
# We sample a few tokens in each sequence for masked-LM training (with probability args.mlm_probability defaults to 0.15 in Bert/RoBERTa)
probability_matrix = torch.full(labels.shape, self.mlm_probability)
special_tokens_mask = [
self.tokenizer.get_special_tokens_mask(val, already_has_special_tokens=True) for val in labels.tolist()
]
probability_matrix.masked_fill_(torch.tensor(special_tokens_mask, dtype=torch.bool), value=0.0)
if self.tokenizer._pad_token is not None:
padding_mask = labels.eq(self.tokenizer.pad_token_id)
probability_matrix.masked_fill_(padding_mask, value=0.0)
masked_indices = torch.bernoulli(probability_matrix).bool()
labels[~masked_indices] = -100 # We only compute loss on masked tokens
# 80% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK])
indices_replaced = torch.bernoulli(torch.full(labels.shape, 0.8)).bool() & masked_indices
inputs[indices_replaced] = self.tokenizer.convert_tokens_to_ids(self.tokenizer.mask_token)
# 10% of the time, we replace masked input tokens with random word
indices_random = torch.bernoulli(torch.full(labels.shape, 0.5)).bool() & masked_indices & ~indices_replaced
random_words = torch.randint(len(self.tokenizer), labels.shape, dtype=torch.long)
inputs[indices_random] = random_words[indices_random]
# The rest of the time (10% of the time) we keep the masked input tokens unchanged
return inputs, labels
本文实验代码库。拿来即用!
https://github.com/zhusleep/pytorch_chinese_lm_pretrain