目前在NLP任务中,我们一般采用BPE分词。Fairseq在RoBERTa的代码中提供了这一方法。本文不再详述BPE分词,直接使用实例说明。
BPE分词
首先,需要下载bpe文件,其中包括dict.txt,encoder.json,vocab.bpe三个文件。
接下来,使用如下命令对文本进行bpe分词。
TASK=samsum
for SPLIT in train val
do
for LANG in source target
do
python -m examples.roberta.multiprocessing_bpe_encoder \
--encoder-json encoder.json \
--vocab-bpe vocab.bpe \
--inputs "$TASK/$SPLIT.$LANG" \
--outputs "$TASK/$SPLIT.bpe.$LANG" \
--workers 60 \
--keep-empty;
done
done
需要注意的是,虽然在源代码中--inputs以及--outputs为list,看似可以同时处理多个文件,但是这里有个要求是这些文件的文本条数是相同的,否则会在第一个进程完成后结束程序,导致某些文件未处理完。
parser.add_argument(
"--inputs",
nargs="+",
default=['-'],
help="input files to filter/encode",
)
parser.add_argument(
"--outputs",
nargs="+",
default=['-'],
help="path to save encoded outputs",
)
二值化
fairseq-preprocess \
--source-lang "source" \
--target-lang "target" \
--trainpref "${TASK}/train.bpe" \
--validpref "${TASK}/val.bpe" \
--destdir "${TASK}-bin/" \
--workers 60 \
--srcdict dict.txt \
--tgtdict dict.txt;
fairseq-preprocess命令会调用preprocess.py文件。在生成自定义数据时,需要修改preprocess.py,fairseq/binarizer.py以及fairseq/data/dictionary.py。
经过这两步后,会生成*.source-target.source.bin, *.source-target.target.idx,dict.source.txt以及dict.target.txt文件。
下一篇文章(三)Fairseq 模型,主要介绍fairseq自定义模型。
