偶然在看到了这个项目,感觉很厉害,于是就折腾了下,跑了一跑
项目地址:https://github.com/Morizeyao/GPT2-Chinese
如果Github下载太慢的可以用这个代下载:https://toolwa.com/github/

环境准备

1.pytorch 的安装
由情况选择版本安装,安装CPU版本梢简单

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
# 安装时官方源下载比较慢,要换源
conda install pytorch torchvision cpuonly -c pytorch

# 如果cnda装不了 选择pip的方式进行安装
# pip也要指定源
pip install torch==1.5.1+cpu torchvision==0.6.1+cpu -f https://download.pytorch.org/whl/torch_stable.html

Anacoda 换源

onda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
# 设置搜索时显示通道地址
conda config --set show_channel_urls yes

使用后在用户-username-.condarc可进行编辑

如果要建立自己的词表的话,要安装tensorflow,版本要对上,否则可能会出错

# Current stable release for CPU and GPU
pip install transformers==2.1.1

安装成后,执行以下验证安装效果

python -c "import tensorflow as tf;print(tf.reduce_sum(tf.random.normal([1000, 1000])))"
#报错
DLL load failed: 找不到指定模块
Failed to load the native TensorFlow runtime.

安装VC++2019就能解决问题了
64位地址:x64
32位地址:x86

如要在cmd或GitBash中使用conda 命令要配置Anaconda的环境变量,

conda env list #列出已有环境
conda info -e  #列出已有环境

conda create -n env_name python=version  #创建一个新的虚拟环境
conda activate env_name   #激活并进入虚拟环境

conda deactivate       #退出虚拟环境 进入标准环境中
conda env remove -n env_name   #删除一个已有的虚拟环境

conda install package_name   #下载安装包
conda install package_name=version   #下载包同时指定版本

conda remove package_name   #删除包

conda list   #列出已经安装的包
codna search package_name  #查找包的版本信息
codna install package_name -n env_name  #管理指定虚拟环境的包

pip freeze > d:\superset.txt    #导出本虚拟环境
pip install -r d:\superset.txt  #导入虚拟环境
conda env export --file d:\superset.yml   #导出虚拟环境
conda env create -f d:\superset.yml       #导入虚拟环境
conda create -n superset2 --clone superset  #虚拟环境备份

来源:Anaconda与windows cmd环境的使用与基本命令

如此在GitBash中可能还是会遇到一个问题,Anaconda虚拟环境激活不了,报错:

CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'.

可以执行以下命令后就能激活环境了:

# 激活环境
source activate
# 退出环境
source deactivate

来源:Git Bash使用conda命令activate env

开始训练

刚开始遇到的问题就是编码的问题,我的语料是放在train.json中是UTF8的编码

如果要执行.sh的脚本要使用Gitbash

如果样本的量比较小的时候,可以自己生成词库,减少乱码的可能。

同样遇到了这个问题,是词库导致的,默认使用的是cache/vocab_small.txt,里面13317个单词,包括各种符号,当样本量小的时候,结果就会有很多乱码。可以根据自己的data,生成vocab文件(当然这样的话,单词来源受限于样本了) 步骤如下:

# 生成vocab_user.txt文件
cd cache/
bash make_vocab.sh
# 根据vocab_user.txt内单词个数,调整配置文件config/model_config_small.json的vocab_size字段

# train
python train.py --raw --min_length 4 --tokenizer_path cache/vocab_user.txt
# generate
python ./generate.py --length=50 --nsamples=4 --prefix=你好 --fast_pattern --tokenizer_path cache/vocab_user.txt

来源:生成的文本都是乱码
issue#88

注:自己的机器,特别是只要CPU跑的话,即使语料很小,也要很久,推荐有能力的朋友在Colab上跑比较方便,基本环境都有,训练的速度也会快很多。

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄