世界上存在海量的语言与词汇,在处理多语言场景时,传统预训练模型采用的 Vocab 和 Tokenization 方案难免会遇到 Out of Vocabulary 和 Unkonw Token 的情况。 Canine 提供了 tokenization-free 的预训练模型方案,解决了 Out of Vocabulary 问题的同时,提高了模型在多语言任务下的能力。
☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 免费无限量使用 DeepSeek R1 模型☜☜☜

202562cb9ffec011fe3>In [1]
# 在开始之前,请运行它来切换你的工作目录!import osprint(f"current dir at {os.getcwd()}")if os.getcwd() == '/home/aistudio': os.chdir("./work/canine_paddle") print(f"changing working dir into {os.getcwd()}")
current dir at /home/aistudiochanging working dir into /home/aistudio/work/canine_paddle
Canine Paddle 复现
1. 简介
世界上存在海量的语言与词汇,在处理多语言场景时,传统预训练模型采用的 Vocab 和 Tokenization 方案难免会遇到 Out of Vocabulary 和 Unkonw Token 的情况。 Canine 提供了 tokenization-free 的预训练模型方案,解决了 Out of Vocabulary 问题的同时,提高了模型在多语言任务下的能力。
论文链接:CANINE: Pre-training an Efficient Tokenization-Free Encoder for Language Representation
Canine Paddle 复现仓库地址:kevinng77/canine_paddle
【备注】本仓库项目主要对复现操作做整理以及说明,关于更多的 Canine 复现经验和碎碎念分享,欢迎查看 我的博客
2.数据集和复现精度
本次复现使用 tydiqa 数据集 tydiqa 官方repo,数据处理操作参考了 canine/tydiqa 官方。
TydiQA 为多语言阅读理解数据集。Tydi数据库中包含了 18万+篇 wiki 百科语料,20万+ 文章与问题对,共涉及 11 种不同的语言。
Pas sage Selection Task (SELECTP)63.2%66.0%65.92%Minimal Answer Span Task (MINSPAN)51.2%52.8%55.04%
指标为macro F1;本仓库展示的复现结果为多次微调、预测、评估后的平均值。
3. 环境准备
3.1 设备环境
框架:paddlepaddle==2.3.0硬件:微调需要 GPU V100 显存 32G,内存 32GB;
【提示】本章中的 3.3 数据准备 小节存在大量CPU计算,需要占用约3小时+,因此笔者建议想要复现的伙伴在 AiStudio CPU 环境下执行完 3.3 数据准备。而后再切换到 AiStudio GPU 环境下执行剩余部分。
In [ ]
# 复现 TydiQA 任务需要用到 h5py, absl-py 库,更新好 paddlenlp==2.3.1 后,你可能需要重新启动以下 notebook!pip install paddlenlp==2.3.1 h5py absl-py -q
3.2 模型准备
【提示】paddle权重已上传至 data/paddle_weight,使用 model.from_pretrained(‘data/paddle_weight’) 时会自动加载。因此若想直接体验微调流程,可跳过 3.2 模型准备 本章节,直接进入到 3.3 数据准备。 若读者正在复现其他模型,那么这一节或许能够为你提供一些帮助。
【提示】为支持一键运行 notebook,该节中的代码将以 MARKDOWN 形式呈现。请需要运行此节的读者使用终端,并在 work/canine_paddle 目录下运行。
3.2.1 模型框架编写
编写模型的 modeling.py 以及 tokenizer.py 文件。 通过阅读和观察 Canine论文及源码,会发现 Canine 模型框架与 Bert 类似,都采用了 Transformer Encoder 作为模型主体。不同的是 Canine:
在 Transformer Encoder 前后都采用了卷积层来对序列进行压缩和采样。使用了 Hash Embedding 来减小模型的大小。在 Embedding 和 Transformer Encoder 之间加入了 Local Attention Encoder,来对局部的字符信息进行学习。使用 Unicode 进行编码,而非 WordPiece或BPE。
基于以上四点,模型搭建思路也就很明确了:先参考 paddlenlp/transformers/bert/modeling.py 文件进行修改,实现 Canine 框架的主体,而后分别添加 Hash_Embedding, Local_Attention_Encoder,Projection_Conv 来实现以上四个不同点。
编写后的模型放置于 paddlenlp/transformers/canine/modeling.py
3.2.2 预训练权重转换
权重转换需要:(只有3.2节会用到,微调时或者在 Aistudio GPU 环境下请勿安装)
pip install transformers==4.19.2 torch==1.11.0
首先下载 hugging face的canine torch 权重:
cd ./work/canine_paddlewget -O data/huggingface_weight/model.bin https://huggingface.co/google/canine-s/resolve/main/pytorch_model.bin
根据 huggingface canine 和 我们实现的 canine 框架构造权重映射,具体可查看 reproduction_utils 中的 weight_mapping.py 文件。该步骤生成 torch_paddle_layer_map.json 文件,该文件储存了 Canine 每个 torch Layer 权重对应的 paddle Layer 名称以及形状,方便查看与debug。
运行 convert_weight.py 转换权重:
python -m reproduction_utils.weight_convert_files.convert_weight --pytorch_checkpoint_path=data/huggingface_weight/model.bin --paddle_dump_path=data/paddle_weight/model_state.pdparams --layer_mapping_file=reproduction_utils/weight_convert_files/torch_paddle_layer_map.json
3.2.3 前向传导核对精度
(执行该步需要安装torch与transformers)请在 CPU 环境下进行前项传导核对。
验证过程中,运行 torch canine 模型时会出现 Using unk_token, but it is not set yet. ,属于正常提示。经过多次随机样本验证,paddle模型与huggingface模型精度能保持在 e−5e−5 至 e−7e−7 级别。
python -m reproduction_utils.token_checkpython -m reproduction_utils.forward_ppg_check --model_dir="./data/paddle_weight"
3.3 数据准备
3.3.1 下载Tydi数据集
【提示】 AiStudio 下载速度有时候会很慢,尝试在终止该单元格运行后重新执行看看。运气好下载速度可以达到 3M+/s :)
In [ ]
!wget -O data/tydi/tydiqa-v1.0-dev.jsonl.gz https://storage.googleapis.com/tydiqa/v1.0/tydiqa-v1.0-dev.jsonl.gz!wget -O data/tydi/tydiqa-v1.0-train.jsonl.gz https://storage.googleapis.com/tydiqa/v1.0/tydiqa-v1.0-train.jsonl.gz
3.3.2 处理数据集
【提示】该步骤耗时约4小时,建议在 CPU 环境上运行,数据将保存在 work/canine_paddle/data 文件夹中,因此在切换 AiStudio 环境时不会丢失。详细的数据处理配置请在 tydi_canine 文件夹中查看。
方案一:直接下载并解压处理好的训练和测试数据。
链接:https://pan.baidu.com/s/1QVHh3cTztKAgAEEXUlqxWg?pwd=ia6i ;提取码:ia6i
下载后将两个 h5df 数据库放在 data/tydi 目录,如下:
./canine_paddle # 仓库根目录|--data # 仓库数据目录| ├── tydi # tydi数据| ├── dev.h5df # 从tydiqa-v1.0-dev.jsonl.gz提取的测试数据 | ├── train.h5df # 从tydiqa-v1.0-train.jsonl.gz提取的训练数据
你可以考虑将文件保存到自己的百度云盘,而后使用 bypy 库下载到 Aistuio 上。
方案二:处理官方的原数据集
执行以下代码生成测试数据集 dev.h5df,用时约40分钟,生成数据大小2.5GB,包括35万+个样本。
In [3]
!python3 -m tydi_canine.prepare_tydi_data --input_jsonl="**/tydiqa-v1.0-dev.jsonl.gz" --output_dir=data/tydi/dev.h5df --max_seq_length=2048 --doc_stride=512 --max_question_length=256 --logging_steps=3000 --is_training=false
I0624 16:35:16.286553 139650475759360 prepare_tydi_data.py:134] >>> input features will be store at data/tydi/dev.h5dfI0624 16:35:16.396667 139650475759360 pd_io.py:53] >>> loading file from data/tydi/tydiqa-v1.0-dev.jsonl.gzI0624 16:35:16.449943 139650475759360 prepare_tydi_data.py:187] Examples processed: 0I0624 16:39:11.050059 139650475759360 prepare_tydi_data.py:187] Examples processed: 3000I0624 16:43:06.520539 139650475759360 prepare_tydi_data.py:187] Examples processed: 6000I0624 16:47:03.243960 139650475759360 prepare_tydi_data.py:187] Examples processed: 9000I0624 16:51:02.098562 139650475759360 prepare_tydi_data.py:187] Examples processed: 12000I0624 16:54:55.408642 139650475759360 prepare_tydi_data.py:187] Examples processed: 15000I0624 16:58:50.746861 139650475759360 prepare_tydi_data.py:187] Examples processed: 18000I0624 17:00:13.173192 139650475759360 prepare_tydi_data.py:211] Examples with correct context retained: 9212 of 18670I0624 17:00:13.173460 139650475759360 prepare_tydi_data.py:216] Number of total features 336499time cose: 24.96 min
执行以下代码生成训练数据集 train.h5df,用时约3小时,生成数据大小1.4GB,包括46万+ 个样本。
AVCLabs
AI移除视频背景,100%自动和免费
268 查看详情
In [4]
!python3 -m tydi_canine.prepare_tydi_data --input_jsonl="**/tydiqa-v1.0-train.jsonl.gz" --output_dir=data/tydi/train.h5df --max_seq_length=2048 --doc_stride=512 --max_question_length=256 --include_unknowns=0.1 --logging_steps=30000 --is_training=true
I0624 17:00:14.680838 140086686390016 prepare_tydi_data.py:134] >>> input features will be store at data/tydi/train.h5dfI0624 17:00:14.683240 140086686390016 pd_io.py:53] >>> loading file from data/tydi/tydiqa-v1.0-train.jsonl.gzI0624 17:00:14.737086 140086686390016 prepare_tydi_data.py:187] Examples processed: 0I0624 17:36:17.786075 140086686390016 prepare_tydi_data.py:187] Examples processed: 30000I0624 18:11:26.206844 140086686390016 prepare_tydi_data.py:187] Examples processed: 60000I0624 18:47:06.246754 140086686390016 prepare_tydi_data.py:187] Examples processed: 90000I0624 19:22:25.193837 140086686390016 prepare_tydi_data.py:187] Examples processed: 120000I0624 19:58:38.454844 140086686390016 prepare_tydi_data.py:187] Examples processed: 150000I0624 20:18:25.707869 140086686390016 prepare_tydi_data.py:211] Examples with correct context retained: 64991 of 166916I0624 20:18:25.708129 140086686390016 prepare_tydi_data.py:216] Number of total features 459947time cose: 198.19 min
In [ ]
# 处理完数据后可以将 **/tydiqa-v1.0-train.jsonl.gz 文件删除,之后不需要用到!rm ./data/tydi/tydiqa-v1.0-train.jsonl.gz
4 模型使用
4.1 使用案例
In [5]
from canine import CanineTokenizerfrom canine import CanineModelimport paddlepretrained_model_path = "data/paddle_weight/"model = CanineModel.from_pretrained(pretrained_model_path)tokenizer = CanineTokenizer.from_pretrained(pretrained_model_path)text = ["canine is tokenization-free"]inputs = tokenizer(text, padding="longest", return_attention_mask=True, return_token_type_ids=True, )pd_inputs = {k: paddle.to_tensor(v) for (k, v) in inputs.items()}seq_outputs, pooling_outputs = model(**pd_inputs)print(seq_outputs.shape)print(pooling_outputs.shape)
W0624 20:18:29.014458 165 gpu_context.cc:278] Please NOTE: device: 0, GPU Compute Capability: 7.0, Driver API Version: 11.2, Runtime API Version: 10.1W0624 20:18:29.019143 165 gpu_context.cc:306] device: 0, cuDNN Version: 7.6.
[1, 29, 768][1, 768]
4.2 TydiQA 任务复现
训练参数信息可在 run_tydi.py 中查看。关于训练的超参、优化器、loss等选择,请查看根目录下的 note.md。
注意: 由于官方论文中并没有提到微调的参数配置,因此本次复现参考并分别尝试了 canine官方仓库 的微调配置(batch_size=512,epoch=10, lr=5e-5),以及 tydiqa 基线仓库 的微调配置(batch_size=16,epoch=3,lr=5e-5)。其中 batch_size=512 通过梯度累加来近似模拟。
实验中发现,10个epoch训练存在明显的过拟合,并且 2-3 个 epoch 的效果普遍比 10 个 epoch 高出 2-3 %。
4.2.1 模型训练
单卡 V100 32G 训练需要8小时左右(多卡仅改动启动方式为 !python -m paddle.distributed.launch –selected_gpus=’0,1,2,3′ run_tydi.py)。
In [4]
# !python -m paddle.distributed.launch --selected_gpus='0,1,2,3' run_tydi.py # 多卡训练使用!python run_tydi.py --train_input_dir=data/tydi/train.h5df --do_train --max_seq_length=2048 --train_batch_size=20 --learning_rate=5e-5 --num_train_epochs=2 --warmup_proportion=0.1 --logging_steps=500 --checkout_steps=50000 --seed=2022 --fp16 --gradient_accumulation_steps=1 --output_dir=data/tydiqa_baseline_model/train
W0624 20:21:53.680686 27743 gpu_context.cc:278] Please NOTE: device: 0, GPU Compute Capability: 7.0, Driver API Version: 11.2, Runtime API Version: 10.1W0624 20:21:53.685145 27743 gpu_context.cc:306] device: 0, cuDNN Version: 7.6.[2022-06-24 20:21:58,763] [ INFO] - Weights of CanineForTydiQA not initialized from pretrained model: ['span_classifier.weight', 'span_classifier.bias', 'answer_type_classifier.weight', 'answer_type_classifier.bias']Found inf or nan, current scale is: 131072.0, decrease to: 131072.0*0.5Found inf or nan, current scale is: 131072.0, decrease to: 131072.0*0.5Found inf or nan, current scale is: 131072.0, decrease to: 131072.0*0.5Found inf or nan, current scale is: 131072.0, decrease to: 131072.0*0.5Found inf or nan, current scale is: 131072.0, decrease to: 131072.0*0.5Found inf or nan, current scale is: 131072.0, decrease to: 131072.0*0.5Found inf or nan, current scale is: 131072.0, decrease to: 131072.0*0.5Found inf or nan, current scale is: 131072.0, decrease to: 131072.0*0.5Found inf or nan, current scale is: 131072.0, decrease to: 131072.0*0.5Found inf or nan, current scale is: 131072.0, decrease to: 131072.0*0.5Found inf or nan, current scale is: 131072.0, decrease to: 131072.0*0.5Found inf or nan, current scale is: 131072.0, decrease to: 131072.0*0.5
训练日志在 work/canine_paddle/data/tydiqa_baseline_model/trian 中可以查看。同时可以使用 Paddle 的 VisualDL 可视化工具查看:1. 选择 notebook 左侧的数据模型可视化。2. 添加 /home/aistudio/log/train 目录为 logdir
4.2.2 tydi任务评测
【备注】测评环节根据 tydi 官方 指示进行。 我们使用训练结束的权重进行测试,不考虑中间的checkout point。 测评过程中会生成./data/tydiqa_baseline_model/predict/pred.jsonl ,其为格式满足 TydiQA 评测要求的文件,格式要求可以参考:TydiQA 评测文件示例
步骤一: 运行以下代码,生成任务评测文件 pred.jsonl ,由于 tydiQA任务的评估方式较为特殊,因此可以采用单卡或者多卡进行(多卡仅改动启动方式为 !python -m paddle.distributed.launch –selected_gpus=’0,1,2,3′ run_tydi.py):
In [5]
# !python3 -m paddle.distributed.launch --selected_gpus='0,1,2,3' run_tydi.py # 多卡训练使用!python3 run_tydi.py --state_dict_path=data/tydiqa_baseline_model/train --predict_file=data/tydi/tydiqa-v1.0-dev.jsonl.gz --precomputed_predict_file=data/tydi/dev.h5df --do_predict --max_seq_length=2048 --max_answer_length=100 --candidate_beam=30 --predict_batch_size=32 --logging_steps=1000 --seed=2022 --output_dir=data/tydiqa_baseline_model/predict --output_prediction_file=data/tydiqa_baseline_model/predict/pred.jsonl
W0625 03:29:33.173774 13821 gpu_context.cc:278] Please NOTE: device: 0, GPU Compute Capability: 7.0, Driver API Version: 11.2, Runtime API Version: 10.1W0625 03:29:33.178153 13821 gpu_context.cc:306] device: 0, cuDNN Version: 7.6.[2022-06-25 03:29:38,250] [ INFO] - Weights of CanineForTydiQA not initialized from pretrained model: ['span_classifier.weight', 'span_classifier.bias', 'answer_type_classifier.weight', 'answer_type_classifier.bias']
测评日志在 work/canine_paddle/data/tydiqa_baseline_model/predict 中可以查看。
超参说明:
–state_dict_path:存放微调权重的文件路径;若为文件夹路径,则会读取该文件夹下的 tydi_seed_{seed}.pdparams 权重。
–predict_file:从官方下载的 tydiqa-v1.0-dev.jsonl.gz 文件路径。
–output_dir:输出运行日志
–output_prediction_file:输出 JSON 评估文件路径。
步骤二: 运行 tydi 官方跑分程序:将 predictions_path 对应到上一步中的 pred.jsonl 位置。
其中 Tydi 测评所需要的 tydi_eval.py, eval_utils.py 源于 tydi 官方。
运行下方代码,可以看到,仅训练 2个 Epoch(官方仓库的配置是10个epoch),CANINE 在 TydiQA 数据集上的指标均比 Tydi mBert 基线高出了3%+。
In [6]
!python3 official_tydi/tydi_eval.py --gold_path=data/tydi/tydiqa-v1.0-dev.jsonl.gz --predictions_path=data/tydiqa_baseline_model/predict/pred.jsonl --verbose=False
I0625 09:06:43.232116 140451243751168 eval_utils.py:291] Parsing data/tydi/tydiqa-v1.0-dev.jsonl.gz (gzip)...I0625 09:06:50.419521 140451243751168 tydi_eval.py:479] 7556 examples have minimal answersI0625 09:06:50.419761 140451243751168 tydi_eval.py:480] ****************************************I0625 09:06:50.419822 140451243751168 eval_utils.py:211] Reading predictions from file: data/tydiqa_baseline_model/predict/pred.jsonlW0625 09:06:50.718449 140451243751168 tydi_eval.py:233] Predictions missing for 1 examples.I0625 09:06:50.718697 140451243751168 tydi_eval.py:234] Missing ids: [483185134238717036]Passage & english & fpr{61.9}{66.2}{58.1}Minimal Answer & english & fpr{49.9}{61.6}{41.9}********************Passage & arabic & fpr{83.0}{85.2}{80.9}Minimal Answer & arabic & fpr{70.7}{80.0}{63.4}********************Passage & bengali & fpr{65.1}{74.7}{57.7}Minimal Answer & bengali & fpr{54.3}{62.7}{47.8}********************Passage & finnish & fpr{64.1}{65.5}{62.8}Minimal Answer & finnish & fpr{56.1}{63.5}{50.2}********************W0625 09:06:50.812115 140451243751168 tydi_eval.py:233] Predictions missing for 1 examples.I0625 09:06:50.812309 140451243751168 tydi_eval.py:234] Missing ids: [15806027368664557]Passage & indonesian & fpr{64.7}{66.0}{63.5}Minimal Answer & indonesian & fpr{56.6}{61.7}{52.3}********************Passage & japanese & fpr{52.8}{65.6}{44.2}Minimal Answer & japanese & fpr{44.5}{55.0}{37.4}********************Passage & swahili & fpr{68.9}{76.5}{62.7}Minimal Answer & swahili & fpr{60.7}{74.7}{51.1}********************Passage & korean & fpr{63.1}{71.1}{56.7}Minimal Answer & korean & fpr{39.0}{43.8}{35.2}********************Passage & russian & fpr{64.6}{65.1}{64.1}Minimal Answer & russian & fpr{50.2}{61.3}{42.5}********************W0625 09:06:50.966964 140451243751168 tydi_eval.py:233] Predictions missing for 2 examples.I0625 09:06:50.967158 140451243751168 tydi_eval.py:234] Missing ids: [-6397488112403382620, 7216454742149172827]Passage & telugu & fpr{83.5}{83.6}{83.4}Minimal Answer & telugu & fpr{77.5}{86.3}{70.3}********************Passage & thai & fpr{62.4}{64.9}{60.1}Minimal Answer & thai & fpr{49.8}{55.1}{45.5}********************Total # examples in gold: 18670, # ex. in pred: 18666 (including english)*** Macro Over 10 Languages, excluding English **Passage F1:0.672 P:0.718 R:0.635978fpr{67.2}{71.8}{63.6}Minimal F1:0.560 P:0.644 R:0.495881fpr{56.0}{64.4}{49.6}*** / Aggregate Scores ****{"avg_passage_f1": 0.672270647476107, "avg_passage_recall": 0.6359777874965081, "avg_passage_precision": 0.7183519530345681, "avg_minimal_f1": 0.5595748224545292, "avg_minimal_recall": 0.4958814852655177, "avg_minimal_precision": 0.6441669216190516}
–gold_path:从官方下载的 tydiqa-v1.0-dev.jsonl.gz 文件路径。
–predictions_path:步骤一种输出 JSON 评估文件的路径。 步骤三: 清理过程文件
在 data/tydiqa_baseline_model/predict 文件夹下会生成用于储存 logits 的 results_gpu_*.pickle 文件。测试结束后可以将其删除。
In [7]
# 删除预测中的过程文件!rm -r `find ./data -name "results_gpu_*"`
4.2.3 复现结果
以下复现结果为多次微调、预测、评估后的 macro F1 平均值:
Passage Selection Task (SELECTP)63.2%66.0%65.92%Minimal Answer Span Task (MINSPAN)51.2%52.8%55.04%
各次微调的日志、评估文件等可以在 logs 文件夹中查看,这边对所有训练结果进行整理:
V100161162021366.01%55.77%V10016116666367.02%56.17%v100163251251211064.35%53.58%v1001632512555466.29%54.12%3090*41495045123465.93%55.60%—-
平均65.92%55.04%
此外,以下展示了 所有 复现过程中进行过的其他微调结果,由于参数配置问题,他们不被计入论文复现精度,但仍可以为该模型在Tydi任务上的训练效果提供一些信息。
V100*120255006否100.0164.38%53.73%3090*410124806否100.0165.23%53.49%3090*4101406否100.0167.31%53.11%V100*4161642022是30.0167.26%56.41%V100*4161642020是30.0167.29%56.42%V100*481322020是30.167.26%56.37%A4000*481322020是30.167.43%55.91%——-平均66.59%55.06%
备注:
官方 warm up 比例为 0.1;此处理论 batch_size = batch_size * accumulate_gradient_steps * number_GPU除上述两者外,其他训练配置均与官方相同。在 Tydi Leaderboard 上,TydiQA SelectP 任务的 Top5/Top1 成绩为 72.5%/79.5%。而 TydiQA MinSpan 的 Top5/Top1 成绩为 63.4%/72.35%。canine 与 SOTA 还是有点差距的。
以上就是【复现赛 NLP】 基于 Paddle 实现 Canine 模型的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/737120.html
微信扫一扫
支付宝扫一扫