1. 基本用法
Hugging face提供的transformers庫(kù)主要用于預(yù)訓(xùn)練模型的載入舟肉,需要載入三個(gè)基本對(duì)象
from transformers import BertConfig
from transformers import BertModel
from transformers import BertTokenizer
BertConfig
是該庫(kù)中模型配置的class扔涧。
BertModel
模型的class(還有其它的繼承BertPreTrainedModel
的派生類依痊,對(duì)應(yīng)不同的Bert任務(wù)隧饼,BertForNextSentencePrediction
以及BertForSequenceClassification
)促脉。
BertTokenizer
分詞的class(這個(gè)分詞對(duì)象比BERT官方代碼的好用覆旭,輸入文本中的[SEP]
等特殊字符不會(huì)被切開,而是作為一個(gè)整體保留下來)钉蒲。
推薦使用科大訊飛的pytorch版預(yù)訓(xùn)練模型切端,中文BERT-wwm系列模型,也可以自己手動(dòng)把tensorflow的checkpoint文件轉(zhuǎn)化為pytorch模型顷啼。以訊飛下載的模型為例:
tokenizer = BertTokenizer.from_pretrained('chinese_roberta_wwm_ext_pytorch') # 默認(rèn)回去讀取文件下的vocab.txt文件
model = BertModel.from_pretrained('chinese_roberta_wwm_ext_pytorch') # 應(yīng)該會(huì)報(bào)錯(cuò), 默認(rèn)讀取config.json, 需要重命名bert_config.json
# 或者這樣改, 手動(dòng)指定config對(duì)象
config = BertConfig.from_json_file('model_path/bert_config.json')
model = BertModel.from_pretrained('model_path', config=config)
至此踏枣,預(yù)訓(xùn)練模型和分詞工具已經(jīng)載入完成昌屉,下面是一個(gè)簡(jiǎn)單的實(shí)例。
s_a, s_b = "李白拿了個(gè)錘子", "錘子茵瀑?"
# 分詞是tokenizer.tokenize, 分詞并轉(zhuǎn)化為id是tokenier.encode
# 簡(jiǎn)單調(diào)用一下, 不作任何處理經(jīng)過transformer
input_id = tokenizer.encode(s_a)
input_id = torch.tensor([input_id]) # 輸入數(shù)據(jù)是tensor且batch形式的
sequence_output, pooled_output = model(input_id) # 輸出形狀分別是[1, 9, 768], [1, 768]
# 但是輸入BertModel的還需要指示前后句子的信息的token type, 以及遮掉PAD部分的attention mask
inputs = tokenizer.encode_plus(s_a, text_pair=s_b, return_tensors="pt") # 還有些常用的可選參數(shù)max_length, pad_to_max_length等
print(inputs.keys()) # 返回的是一個(gè)包含id, mask信息的字典
# dict_keys(['input_ids', 'token_type_ids', 'attention_mask']
sequence_output, pooled_output = model(**inputs)
2. 關(guān)于Fine-tuning
不推薦自己從頭開始寫下游任務(wù)的fine-tuning流程间驮,數(shù)據(jù)預(yù)處理加上訓(xùn)練流程巨煩人。如果再加上warm up马昨,weight decay竞帽,甚至多卡訓(xùn)練,簡(jiǎn)直爆炸鸿捧。推薦在transformers提供的栗子上面修改屹篓,比如官方給的xnli數(shù)據(jù)集上的樣例。
主要需要修改run_xnli.py文件import的幾個(gè)數(shù)據(jù)結(jié)構(gòu)
from transformers import xnli_compute_metric as compute_metric
from transformers import xnli_output_modes as output_modes
from transformers import xnli_processors as processors
# 注釋掉以上三行, 我們重新寫這些模塊
# compute_metric是evaluation階段的評(píng)估函數(shù), xnli是文本分類任務(wù)
def compute_metric(task_name, preds, labels):
assert len(preds) == len(labels)
if task_name == "your_task":
return {"acc": (preds == labels).mean()}
else:
raise KeyError(task_name)
# output_modes任務(wù)輸出形式
output_modes = {"your_task": "classification"} # 回歸任務(wù)則是"regression"
processor
類似于google Bert代碼中的寫法匙奴,參考此處TextProcessor的寫法堆巧。另外有個(gè)地方和google不一樣。
# DataProcessor基類多了一個(gè)方法, 用于載入tensorflow Dataset的數(shù)據(jù),
# 一般沒有這個(gè)需求, 就不用去管它泼菌。
def get_example_from_tensor_dict(self, tensor_dict):
pass
processors = {"your_task": YourProcessor}
采用這里的Processor和數(shù)據(jù)形式恳邀,給出一個(gè)運(yùn)行腳本的樣例:
#!/bin/bash
export DATA_DIR=/data_path # 數(shù)據(jù)路徑
export MODEL_PATH=/model_path # 與訓(xùn)練模型路徑
CUDA_VISIBLE_DEVICES=0 python run_xnli.py \
--model_type bert \
--model_name_or_path ${MODEL_PATH} \
--task_name your_task \
--do_train \
--do_eval \
--do_lower_case \
--data_dir ${DATA_DIR} \
--max_seq_length 64 \
--per_gpu_train_batch_size 32 \
--per_gpu_eval_batch_size 32 \
--warmup_steps 100 \
--learning_rate 5e-5 \
--num_train_epochs 5.0 \
--output_dir /model_output_dir \
--overwrite_output_dir