You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 38 kB

4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. # Contents
  2. [查看中文](./README_CN.md)
  3. - [Contents](#contents)
  4. - [BERT Description](#bert-description)
  5. - [Model Architecture](#model-architecture)
  6. - [Dataset](#dataset)
  7. - [Environment Requirements](#environment-requirements)
  8. - [Quick Start](#quick-start)
  9. - [Script Description](#script-description)
  10. - [Script and Sample Code](#script-and-sample-code)
  11. - [Script Parameters](#script-parameters)
  12. - [Pre-Training](#pre-training)
  13. - [Fine-Tuning and Evaluation](#fine-tuning-and-evaluation)
  14. - [Options and Parameters](#options-and-parameters)
  15. - [Options](#options)
  16. - [Parameters](#parameters)
  17. - [Training Process](#training-process)
  18. - [Training](#training)
  19. - [Running on Ascend](#running-on-ascend)
  20. - [running on GPU](#running-on-gpu)
  21. - [Distributed Training](#distributed-training)
  22. - [Running on Ascend](#running-on-ascend-1)
  23. - [running on GPU](#running-on-gpu-1)
  24. - [Evaluation Process](#evaluation-process)
  25. - [Evaluation](#evaluation)
  26. - [evaluation on cola dataset when running on Ascend](#evaluation-on-cola-dataset-when-running-on-ascend)
  27. - [evaluation on cluener dataset when running on Ascend](#evaluation-on-cluener-dataset-when-running-on-ascend)
  28. - [evaluation on msra dataset when running on Ascend](#evaluation-on-msra-dataset-when-running-on-ascend)
  29. - [evaluation on squad v1.1 dataset when running on Ascend](#evaluation-on-squad-v11-dataset-when-running-on-ascend)
  30. - [Model Description](#model-description)
  31. - [Performance](#performance)
  32. - [Pretraining Performance](#pretraining-performance)
  33. - [Inference Performance](#inference-performance)
  34. - [Description of Random Situation](#description-of-random-situation)
  35. - [ModelZoo Homepage](#modelzoo-homepage)
  36. # [BERT Description](#contents)
  37. The BERT network was proposed by Google in 2018. The network has made a breakthrough in the field of NLP. The network uses pre-training to achieve a large network structure without modifying, and only by adding an output layer to achieve multiple text-based tasks in fine-tuning. The backbone code of BERT adopts the Encoder structure of Transformer. The attention mechanism is introduced to enable the output layer to capture high-latitude global semantic information. The pre-training uses denoising and self-encoding tasks, namely MLM(Masked Language Model) and NSP(Next Sentence Prediction). No need to label data, pre-training can be performed on massive text data, and only a small amount of data to fine-tuning downstream tasks to obtain good results. The pre-training plus fune-tuning mode created by BERT is widely adopted by subsequent NLP networks.
  38. [Paper](https://arxiv.org/abs/1810.04805): Jacob Devlin, Ming-Wei Chang, Kenton Lee, Kristina Toutanova. [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding]((https://arxiv.org/abs/1810.04805)). arXiv preprint arXiv:1810.04805.
  39. [Paper](https://arxiv.org/abs/1909.00204): Junqiu Wei, Xiaozhe Ren, Xiaoguang Li, Wenyong Huang, Yi Liao, Yasheng Wang, Jiashu Lin, Xin Jiang, Xiao Chen, Qun Liu. [NEZHA: Neural Contextualized Representation for Chinese Language Understanding](https://arxiv.org/abs/1909.00204). arXiv preprint arXiv:1909.00204.
  40. # [Model Architecture](#contents)
  41. The backbone structure of BERT is transformer. For BERT_base, the transformer contains 12 encoder modules, each module contains one self-attention module and each self-attention module contains one attention module. For BERT_NEZHA, the transformer contains 24 encoder modules, each module contains one self-attention module and each self-attention module contains one attention module. The difference between BERT_base and BERT_NEZHA is that BERT_base uses absolute position encoding to produce position embedding vector and BERT_NEZHA uses relative position encoding.
  42. # [Dataset](#contents)
  43. - Download the zhwiki or enwiki dataset for pre-training. Extract and refine texts in the dataset with [WikiExtractor](https://github.com/attardi/wikiextractor). Convert the dataset to TFRecord format. Please refer to create_pretraining_data.py file in [BERT](https://github.com/google-research/bert) repository.
  44. - Download dataset for fine-tuning and evaluation such as CLUENER, TNEWS, SQuAD v1.1, etc. Convert dataset files from JSON format to TFRECORD format, please refer to run_classifier.py file in [BERT](https://github.com/google-research/bert) repository.
  45. # [Environment Requirements](#contents)
  46. - Hardware(Ascend/GPU)
  47. - Prepare hardware environment with Ascend/GPU processor. If you want to try Ascend, please send the [application form](https://obs-9be7.obs.cn-east-2.myhuaweicloud.com/file/other/Ascend%20Model%20Zoo%E4%BD%93%E9%AA%8C%E8%B5%84%E6%BA%90%E7%94%B3%E8%AF%B7%E8%A1%A8.docx) to ascend@huawei.com. Once approved, you can get access to the resources.
  48. - Framework
  49. - [MindSpore](https://gitee.com/mindspore/mindspore)
  50. - For more information, please check the resources below:
  51. - [MindSpore Tutorials](https://www.mindspore.cn/tutorial/training/en/master/index.html)
  52. - [MindSpore Python API](https://www.mindspore.cn/doc/api_python/en/master/index.html)
  53. # [Quick Start](#contents)
  54. After installing MindSpore via the official website, you can start pre-training, fine-tuning and evaluation as follows:
  55. - Running on Ascend
  56. ```bash
  57. # run standalone pre-training example
  58. bash scripts/run_standalone_pretrain_ascend.sh 0 1 /path/cn-wiki-128
  59. # run distributed pre-training example
  60. bash scripts/run_distributed_pretrain_ascend.sh /path/cn-wiki-128 /path/hccl.json
  61. # run fine-tuning and evaluation example
  62. - If you are going to run a fine-tuning task, please prepare a checkpoint generated from pre-training.
  63. - Set bert network config and optimizer hyperparameters in `finetune_eval_config.py`.
  64. - Classification task: Set task related hyperparameters in scripts/run_classifier.sh.
  65. - Run `bash scripts/run_classifier.py` for fine-tuning of BERT-base and BERT-NEZHA model.
  66. bash scripts/run_classifier.sh
  67. - NER task: Set task related hyperparameters in scripts/run_ner.sh.
  68. - Run `bash scripts/run_ner.py` for fine-tuning of BERT-base and BERT-NEZHA model.
  69. bash scripts/run_ner.sh
  70. - SQuAD task: Set task related hyperparameters in scripts/run_squad.sh.
  71. - Run `bash scripts/run_squad.py` for fine-tuning of BERT-base and BERT-NEZHA model.
  72. bash scripts/run_squad.sh
  73. ```
  74. - Running on GPU
  75. ```bash
  76. # run standalone pre-training example
  77. bash run_standalone_pretrain_for_gpu.sh 0 1 /path/cn-wiki-128
  78. # run distributed pre-training example
  79. bash scripts/run_distributed_pretrain_for_gpu.sh 8 40 /path/cn-wiki-128
  80. # run fine-tuning and evaluation example
  81. - If you are going to run a fine-tuning task, please prepare a checkpoint generated from pre-training.
  82. - Set bert network config and optimizer hyperparameters in `finetune_eval_config.py`.
  83. - Classification task: Set task related hyperparameters in scripts/run_classifier.sh.
  84. - Run `bash scripts/run_classifier.py` for fine-tuning of BERT-base and BERT-NEZHA model.
  85. bash scripts/run_classifier.sh
  86. - NER task: Set task related hyperparameters in scripts/run_ner.sh.
  87. - Run `bash scripts/run_ner.py` for fine-tuning of BERT-base and BERT-NEZHA model.
  88. bash scripts/run_ner.sh
  89. - SQuAD task: Set task related hyperparameters in scripts/run_squad.sh.
  90. - Run `bash scripts/run_squad.py` for fine-tuning of BERT-base and BERT-NEZHA model.
  91. bash scripts/run_squad.sh
  92. ```
  93. For distributed training on Ascend, an hccl configuration file with JSON format needs to be created in advance.
  94. For distributed training on single machine, [here](https://gitee.com/mindspore/mindspore/tree/master/config/hccl_single_machine_multi_rank.json) is an example hccl.json.
  95. For distributed training among multiple machines, training command should be executed on each machine in a small time interval. Thus, an hccl.json is needed on each machine. [here](https://gitee.com/mindspore/mindspore/tree/master/config/hccl_multi_machine_multi_rank.json) is an example of hccl.json for multi-machine case.
  96. Please follow the instructions in the link below to create an hccl.json file in need:
  97. [https://gitee.com/mindspore/mindspore/tree/master/model_zoo/utils/hccl_tools](https://gitee.com/mindspore/mindspore/tree/master/model_zoo/utils/hccl_tools).
  98. For dataset, if you want to set the format and parameters, a schema configuration file with JSON format needs to be created, please refer to [tfrecord](https://www.mindspore.cn/doc/programming_guide/zh-CN/master/dataset_loading.html#tfrecord) format.
  99. ```text
  100. For pretraining, schema file contains ["input_ids", "input_mask", "segment_ids", "next_sentence_labels", "masked_lm_positions", "masked_lm_ids", "masked_lm_weights"].
  101. For ner or classification task, schema file contains ["input_ids", "input_mask", "segment_ids", "label_ids"].
  102. For squad task, training: schema file contains ["start_positions", "end_positions", "input_ids", "input_mask", "segment_ids"], evaluation: schema file contains ["input_ids", "input_mask", "segment_ids"].
  103. `numRows` is the only option which could be set by user, other values must be set according to the dataset.
  104. For example, the schema file of cn-wiki-128 dataset for pretraining shows as follows:
  105. {
  106. "datasetType": "TF",
  107. "numRows": 7680,
  108. "columns": {
  109. "input_ids": {
  110. "type": "int64",
  111. "rank": 1,
  112. "shape": [128]
  113. },
  114. "input_mask": {
  115. "type": "int64",
  116. "rank": 1,
  117. "shape": [128]
  118. },
  119. "segment_ids": {
  120. "type": "int64",
  121. "rank": 1,
  122. "shape": [128]
  123. },
  124. "next_sentence_labels": {
  125. "type": "int64",
  126. "rank": 1,
  127. "shape": [1]
  128. },
  129. "masked_lm_positions": {
  130. "type": "int64",
  131. "rank": 1,
  132. "shape": [20]
  133. },
  134. "masked_lm_ids": {
  135. "type": "int64",
  136. "rank": 1,
  137. "shape": [20]
  138. },
  139. "masked_lm_weights": {
  140. "type": "float32",
  141. "rank": 1,
  142. "shape": [20]
  143. }
  144. }
  145. }
  146. ```
  147. # [Script Description](#contents)
  148. ## [Script and Sample Code](#contents)
  149. ```shell
  150. .
  151. └─bert
  152. ├─README.md
  153. ├─scripts
  154. ├─ascend_distributed_launcher
  155. ├─__init__.py
  156. ├─hyper_parameter_config.ini # hyper parameter for distributed pretraining
  157. ├─get_distribute_pretrain_cmd.py # script for distributed pretraining
  158. ├─README.md
  159. ├─run_classifier.sh # shell script for standalone classifier task on ascend or gpu
  160. ├─run_ner.sh # shell script for standalone NER task on ascend or gpu
  161. ├─run_squad.sh # shell script for standalone SQUAD task on ascend or gpu
  162. ├─run_standalone_pretrain_ascend.sh # shell script for standalone pretrain on ascend
  163. ├─run_distributed_pretrain_ascend.sh # shell script for distributed pretrain on ascend
  164. ├─run_distributed_pretrain_gpu.sh # shell script for distributed pretrain on gpu
  165. └─run_standaloned_pretrain_gpu.sh # shell script for distributed pretrain on gpu
  166. ├─src
  167. ├─__init__.py
  168. ├─assessment_method.py # assessment method for evaluation
  169. ├─bert_for_finetune.py # backbone code of network
  170. ├─bert_for_pre_training.py # backbone code of network
  171. ├─bert_model.py # backbone code of network
  172. ├─finetune_data_preprocess.py # data preprocessing
  173. ├─cluner_evaluation.py # evaluation for cluner
  174. ├─config.py # parameter configuration for pretraining
  175. ├─CRF.py # assessment method for clue dataset
  176. ├─dataset.py # data preprocessing
  177. ├─finetune_eval_config.py # parameter configuration for finetuning
  178. ├─finetune_eval_model.py # backbone code of network
  179. ├─sample_process.py # sample processing
  180. ├─utils.py # util function
  181. ├─pretrain_eval.py # train and eval net
  182. ├─run_classifier.py # finetune and eval net for classifier task
  183. ├─run_ner.py # finetune and eval net for ner task
  184. ├─run_pretrain.py # train net for pretraining phase
  185. └─run_squad.py # finetune and eval net for squad task
  186. ```
  187. ## [Script Parameters](#contents)
  188. ### Pre-Training
  189. ```text
  190. usage: run_pretrain.py [--distribute DISTRIBUTE] [--epoch_size N] [----device_num N] [--device_id N]
  191. [--enable_save_ckpt ENABLE_SAVE_CKPT] [--device_target DEVICE_TARGET]
  192. [--enable_lossscale ENABLE_LOSSSCALE] [--do_shuffle DO_SHUFFLE]
  193. [--enable_data_sink ENABLE_DATA_SINK] [--data_sink_steps N]
  194. [--accumulation_steps N]
  195. [--allreduce_post_accumulation ALLREDUCE_POST_ACCUMULATION]
  196. [--save_checkpoint_path SAVE_CHECKPOINT_PATH]
  197. [--load_checkpoint_path LOAD_CHECKPOINT_PATH]
  198. [--save_checkpoint_steps N] [--save_checkpoint_num N]
  199. [--data_dir DATA_DIR] [--schema_dir SCHEMA_DIR] [train_steps N]
  200. options:
  201. --device_target device where the code will be implemented: "Ascend" | "GPU", default is "Ascend"
  202. --distribute pre_training by several devices: "true"(training by more than 1 device) | "false", default is "false"
  203. --epoch_size epoch size: N, default is 1
  204. --device_num number of used devices: N, default is 1
  205. --device_id device id: N, default is 0
  206. --enable_save_ckpt enable save checkpoint: "true" | "false", default is "true"
  207. --enable_lossscale enable lossscale: "true" | "false", default is "true"
  208. --do_shuffle enable shuffle: "true" | "false", default is "true"
  209. --enable_data_sink enable data sink: "true" | "false", default is "true"
  210. --data_sink_steps set data sink steps: N, default is 1
  211. --accumulation_steps accumulate gradients N times before weight update: N, default is 1
  212. --allreduce_post_accumulation allreduce after accumulation of N steps or after each step: "true" | "false", default is "true"
  213. --save_checkpoint_path path to save checkpoint files: PATH, default is ""
  214. --load_checkpoint_path path to load checkpoint files: PATH, default is ""
  215. --save_checkpoint_steps steps for saving checkpoint files: N, default is 1000
  216. --save_checkpoint_num number for saving checkpoint files: N, default is 1
  217. --train_steps Training Steps: N, default is -1
  218. --data_dir path to dataset directory: PATH, default is ""
  219. --schema_dir path to schema.json file, PATH, default is ""
  220. ```
  221. ### Fine-Tuning and Evaluation
  222. ```text
  223. usage: run_ner.py [--device_target DEVICE_TARGET] [--do_train DO_TRAIN] [----do_eval DO_EVAL]
  224. [--assessment_method ASSESSMENT_METHOD] [--use_crf USE_CRF]
  225. [--device_id N] [--epoch_num N] [--vocab_file_path VOCAB_FILE_PATH]
  226. [--label2id_file_path LABEL2ID_FILE_PATH]
  227. [--train_data_shuffle TRAIN_DATA_SHUFFLE]
  228. [--eval_data_shuffle EVAL_DATA_SHUFFLE]
  229. [--save_finetune_checkpoint_path SAVE_FINETUNE_CHECKPOINT_PATH]
  230. [--load_pretrain_checkpoint_path LOAD_PRETRAIN_CHECKPOINT_PATH]
  231. [--train_data_file_path TRAIN_DATA_FILE_PATH]
  232. [--eval_data_file_path EVAL_DATA_FILE_PATH]
  233. [--schema_file_path SCHEMA_FILE_PATH]
  234. options:
  235. --device_target device where the code will be implemented: "Ascend" | "GPU", default is "Ascend"
  236. --do_train whether to run training on training set: true | false
  237. --do_eval whether to run eval on dev set: true | false
  238. --assessment_method assessment method to do evaluation: f1 | clue_benchmark
  239. --use_crf whether to use crf to calculate loss: true | false
  240. --device_id device id to run task
  241. --epoch_num total number of training epochs to perform
  242. --num_class number of classes to do labeling
  243. --train_data_shuffle Enable train data shuffle, default is true
  244. --eval_data_shuffle Enable eval data shuffle, default is true
  245. --vocab_file_path the vocabulary file that the BERT model was trained on
  246. --label2id_file_path label to id json file
  247. --save_finetune_checkpoint_path path to save generated finetuning checkpoint
  248. --load_pretrain_checkpoint_path initial checkpoint (usually from a pre-trained BERT model)
  249. --load_finetune_checkpoint_path give a finetuning checkpoint path if only do eval
  250. --train_data_file_path ner tfrecord for training. E.g., train.tfrecord
  251. --eval_data_file_path ner tfrecord for predictions if f1 is used to evaluate result, ner json for predictions if clue_benchmark is used to evaluate result
  252. --dataset_format dataset format, support mindrecord or tfrecord
  253. --schema_file_path path to datafile schema file
  254. usage: run_squad.py [--device_target DEVICE_TARGET] [--do_train DO_TRAIN] [----do_eval DO_EVAL]
  255. [--device_id N] [--epoch_num N] [--num_class N]
  256. [--vocab_file_path VOCAB_FILE_PATH]
  257. [--eval_json_path EVAL_JSON_PATH]
  258. [--train_data_shuffle TRAIN_DATA_SHUFFLE]
  259. [--eval_data_shuffle EVAL_DATA_SHUFFLE]
  260. [--save_finetune_checkpoint_path SAVE_FINETUNE_CHECKPOINT_PATH]
  261. [--load_pretrain_checkpoint_path LOAD_PRETRAIN_CHECKPOINT_PATH]
  262. [--load_finetune_checkpoint_path LOAD_FINETUNE_CHECKPOINT_PATH]
  263. [--train_data_file_path TRAIN_DATA_FILE_PATH]
  264. [--eval_data_file_path EVAL_DATA_FILE_PATH]
  265. [--schema_file_path SCHEMA_FILE_PATH]
  266. options:
  267. --device_target device where the code will be implemented: "Ascend" | "GPU", default is "Ascend"
  268. --do_train whether to run training on training set: true | false
  269. --do_eval whether to run eval on dev set: true | false
  270. --device_id device id to run task
  271. --epoch_num total number of training epochs to perform
  272. --num_class number of classes to classify, usually 2 for squad task
  273. --train_data_shuffle Enable train data shuffle, default is true
  274. --eval_data_shuffle Enable eval data shuffle, default is true
  275. --vocab_file_path the vocabulary file that the BERT model was trained on
  276. --eval_json_path path to squad dev json file
  277. --save_finetune_checkpoint_path path to save generated finetuning checkpoint
  278. --load_pretrain_checkpoint_path initial checkpoint (usually from a pre-trained BERT model)
  279. --load_finetune_checkpoint_path give a finetuning checkpoint path if only do eval
  280. --train_data_file_path squad tfrecord for training. E.g., train1.1.tfrecord
  281. --eval_data_file_path squad tfrecord for predictions. E.g., dev1.1.tfrecord
  282. --schema_file_path path to datafile schema file
  283. usage: run_classifier.py [--device_target DEVICE_TARGET] [--do_train DO_TRAIN] [----do_eval DO_EVAL]
  284. [--assessment_method ASSESSMENT_METHOD] [--device_id N] [--epoch_num N] [--num_class N]
  285. [--save_finetune_checkpoint_path SAVE_FINETUNE_CHECKPOINT_PATH]
  286. [--load_pretrain_checkpoint_path LOAD_PRETRAIN_CHECKPOINT_PATH]
  287. [--load_finetune_checkpoint_path LOAD_FINETUNE_CHECKPOINT_PATH]
  288. [--train_data_shuffle TRAIN_DATA_SHUFFLE]
  289. [--eval_data_shuffle EVAL_DATA_SHUFFLE]
  290. [--train_data_file_path TRAIN_DATA_FILE_PATH]
  291. [--eval_data_file_path EVAL_DATA_FILE_PATH]
  292. [--schema_file_path SCHEMA_FILE_PATH]
  293. options:
  294. --device_target targeted device to run task: Ascend | GPU
  295. --do_train whether to run training on training set: true | false
  296. --do_eval whether to run eval on dev set: true | false
  297. --assessment_method assessment method to do evaluation: accuracy | f1 | mcc | spearman_correlation
  298. --device_id device id to run task
  299. --epoch_num total number of training epochs to perform
  300. --num_class number of classes to do labeling
  301. --train_data_shuffle Enable train data shuffle, default is true
  302. --eval_data_shuffle Enable eval data shuffle, default is true
  303. --save_finetune_checkpoint_path path to save generated finetuning checkpoint
  304. --load_pretrain_checkpoint_path initial checkpoint (usually from a pre-trained BERT model)
  305. --load_finetune_checkpoint_path give a finetuning checkpoint path if only do eval
  306. --train_data_file_path tfrecord for training. E.g., train.tfrecord
  307. --eval_data_file_path tfrecord for predictions. E.g., dev.tfrecord
  308. --schema_file_path path to datafile schema file
  309. ```
  310. ## Options and Parameters
  311. Parameters for training and evaluation can be set in file `config.py` and `finetune_eval_config.py` respectively.
  312. ### Options
  313. ```text
  314. config for lossscale and etc.
  315. bert_network version of BERT model: base | nezha, default is base
  316. batch_size batch size of input dataset: N, default is 16
  317. loss_scale_value initial value of loss scale: N, default is 2^32
  318. scale_factor factor used to update loss scale: N, default is 2
  319. scale_window steps for once updatation of loss scale: N, default is 1000
  320. optimizer optimizer used in the network: AdamWerigtDecayDynamicLR | Lamb | Momentum, default is "Lamb"
  321. ```
  322. ### Parameters
  323. ```text
  324. Parameters for dataset and network (Pre-Training/Fine-Tuning/Evaluation):
  325. seq_length length of input sequence: N, default is 128
  326. vocab_size size of each embedding vector: N, must be consistent with the dataset you use. Default is 21128.
  327. Usually, we use 21128 for CN vocabs and 30522 for EN vocabs according to the origin paper.
  328. hidden_size size of bert encoder layers: N, default is 768
  329. num_hidden_layers number of hidden layers: N, default is 12
  330. num_attention_heads number of attention heads: N, default is 12
  331. intermediate_size size of intermediate layer: N, default is 3072
  332. hidden_act activation function used: ACTIVATION, default is "gelu"
  333. hidden_dropout_prob dropout probability for BertOutput: Q, default is 0.1
  334. attention_probs_dropout_prob dropout probability for BertAttention: Q, default is 0.1
  335. max_position_embeddings maximum length of sequences: N, default is 512
  336. type_vocab_size size of token type vocab: N, default is 16
  337. initializer_range initialization value of TruncatedNormal: Q, default is 0.02
  338. use_relative_positions use relative positions or not: True | False, default is False
  339. dtype data type of input: mstype.float16 | mstype.float32, default is mstype.float32
  340. compute_type compute type in BertTransformer: mstype.float16 | mstype.float32, default is mstype.float16
  341. Parameters for optimizer:
  342. AdamWeightDecay:
  343. decay_steps steps of the learning rate decay: N
  344. learning_rate value of learning rate: Q
  345. end_learning_rate value of end learning rate: Q, must be positive
  346. power power: Q
  347. warmup_steps steps of the learning rate warm up: N
  348. weight_decay weight decay: Q
  349. eps term added to the denominator to improve numerical stability: Q
  350. Lamb:
  351. decay_steps steps of the learning rate decay: N
  352. learning_rate value of learning rate: Q
  353. end_learning_rate value of end learning rate: Q
  354. power power: Q
  355. warmup_steps steps of the learning rate warm up: N
  356. weight_decay weight decay: Q
  357. Momentum:
  358. learning_rate value of learning rate: Q
  359. momentum momentum for the moving average: Q
  360. ```
  361. ## [Training Process](#contents)
  362. ### Training
  363. #### Running on Ascend
  364. ```bash
  365. bash scripts/run_standalone_pretrain_ascend.sh 0 1 /path/cn-wiki-128
  366. ```
  367. The command above will run in the background, you can view training logs in pretraining_log.txt. After training finished, you will get some checkpoint files under the script folder by default. The loss values will be displayed as follows:
  368. ```text
  369. # grep "epoch" pretraining_log.txt
  370. epoch: 0.0, current epoch percent: 0.000, step: 1, outputs are (Tensor(shape=[1], dtype=Float32, [ 1.0856101e+01]), Tensor(shape=[], dtype=Bool, False), Tensor(shape=[], dtype=Float32, 65536))
  371. epoch: 0.0, current epoch percent: 0.000, step: 2, outputs are (Tensor(shape=[1], dtype=Float32, [ 1.0821701e+01]), Tensor(shape=[], dtype=Bool, False), Tensor(shape=[], dtype=Float32, 65536))
  372. ...
  373. ```
  374. #### running on GPU
  375. ```bash
  376. bash scripts/run_standalone_pretrain_for_gpu.sh 0 1 /path/cn-wiki-128
  377. ```
  378. The command above will run in the background, you can view the results the file pretraining_log.txt. After training, you will get some checkpoint files under the script folder by default. The loss value will be achieved as follows:
  379. ```bash
  380. # grep "epoch" pretraining_log.txt
  381. epoch: 0.0, current epoch percent: 0.000, step: 1, outputs are (Tensor(shape=[1], dtype=Float32, [ 1.0856101e+01]), Tensor(shape=[], dtype=Bool, False), Tensor(shape=[], dtype=Float32, 65536))
  382. epoch: 0.0, current epoch percent: 0.000, step: 2, outputs are (Tensor(shape=[1], dtype=Float32, [ 1.0821701e+01]), Tensor(shape=[], dtype=Bool, False), Tensor(shape=[], dtype=Float32, 65536))
  383. ...
  384. ```
  385. > **Attention** If you are running with a huge dataset on Ascend, it's better to add an external environ variable to make sure the hccl won't timeout.
  386. >
  387. > ```bash
  388. > export HCCL_CONNECT_TIMEOUT=600
  389. > ```
  390. >
  391. > This will extend the timeout limits of hccl from the default 120 seconds to 600 seconds.
  392. > **Attention** If you are running with a big bert model, some error of protobuf may occurs while saving checkpoints, try with the following environ set.
  393. >
  394. > ```bash
  395. > export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python
  396. > ```
  397. ### Distributed Training
  398. #### Running on Ascend
  399. ```bash
  400. bash scripts/run_distributed_pretrain_ascend.sh /path/cn-wiki-128 /path/hccl.json
  401. ```
  402. The command above will run in the background, you can view training logs in pretraining_log.txt. After training finished, you will get some checkpoint files under the LOG* folder by default. The loss value will be displayed as follows:
  403. ```bash
  404. # grep "epoch" LOG*/pretraining_log.txt
  405. epoch: 0.0, current epoch percent: 0.001, step: 100, outputs are (Tensor(shape=[1], dtype=Float32, [ 1.08209e+01]), Tensor(shape=[], dtype=Bool, False), Tensor(shape=[], dtype=Float32, 65536))
  406. epoch: 0.0, current epoch percent: 0.002, step: 200, outputs are (Tensor(shape=[1], dtype=Float32, [ 1.07566e+01]), Tensor(shape=[], dtype=Bool, False), Tensor(shape=[], dtype=Float32, 65536))
  407. ...
  408. epoch: 0.0, current epoch percent: 0.001, step: 100, outputs are (Tensor(shape=[1], dtype=Float32, [ 1.08218e+01]), Tensor(shape=[], dtype=Bool, False), Tensor(shape=[], dtype=Float32, 65536))
  409. epoch: 0.0, current epoch percent: 0.002, step: 200, outputs are (Tensor(shape=[1], dtype=Float32, [ 1.07770e+01]), Tensor(shape=[], dtype=Bool, False), Tensor(shape=[], dtype=Float32, 65536))
  410. ...
  411. ```
  412. #### running on GPU
  413. ```bash
  414. bash scripts/run_distributed_pretrain_for_gpu.sh /path/cn-wiki-128
  415. ```
  416. The command above will run in the background, you can view the results the file pretraining_log.txt. After training, you will get some checkpoint files under the LOG* folder by default. The loss value will be achieved as follows:
  417. ```bash
  418. # grep "epoch" LOG*/pretraining_log.txt
  419. epoch: 0.0, current epoch percent: 0.001, step: 100, outputs are (Tensor(shape=[1], dtype=Float32, [ 1.08209e+01]), Tensor(shape=[], dtype=Bool, False), Tensor(shape=[], dtype=Float32, 65536))
  420. epoch: 0.0, current epoch percent: 0.002, step: 200, outputs are (Tensor(shape=[1], dtype=Float32, [ 1.07566e+01]), Tensor(shape=[], dtype=Bool, False), Tensor(shape=[], dtype=Float32, 65536))
  421. ...
  422. epoch: 0.0, current epoch percent: 0.001, step: 100, outputs are (Tensor(shape=[1], dtype=Float32, [ 1.08218e+01]), Tensor(shape=[], dtype=Bool, False), Tensor(shape=[], dtype=Float32, 65536))
  423. epoch: 0.0, current epoch percent: 0.002, step: 200, outputs are (Tensor(shape=[1], dtype=Float32, [ 1.07770e+01]), Tensor(shape=[], dtype=Bool, False), Tensor(shape=[], dtype=Float32, 65536))
  424. ...
  425. ```
  426. > **Attention** This will bind the processor cores according to the `device_num` and total processor numbers. If you don't expect to run pretraining with binding processor cores, remove the operations about `taskset` in `scripts/ascend_distributed_launcher/get_distribute_pretrain_cmd.py`
  427. ## [Evaluation Process](#contents)
  428. ### Evaluation
  429. #### evaluation on cola dataset when running on Ascend
  430. Before running the command below, please check the load pretrain checkpoint path has been set. Please set the checkpoint path to be the absolute full path, e.g:"/username/pretrain/checkpoint_100_300.ckpt".
  431. ```bash
  432. bash scripts/run_classifier.sh
  433. ```
  434. The command above will run in the background, you can view training logs in classfier_log.txt.
  435. If you choose accuracy as assessment method, the result will be as follows:
  436. ```text
  437. acc_num XXX, total_num XXX, accuracy 0.588986
  438. ```
  439. #### evaluation on cluener dataset when running on Ascend
  440. ```bash
  441. bash scripts/ner.sh
  442. ```
  443. The command above will run in the background, you can view training logs in ner_log.txt.
  444. If you choose F1 as assessment method, the result will be as follows:
  445. ```text
  446. Precision 0.920507
  447. Recall 0.948683
  448. F1 0.920507
  449. ```
  450. #### evaluation on msra dataset when running on Ascend
  451. For preprocess, you can first convert the original txt format of MSRA dataset into mindrecord by run the command as below:
  452. ```python
  453. python src/finetune_data_preprocess.py ----data_dir=/path/msra_dataset.txt --vocab_file=/path/vacab_file --save_path=/path/msra_dataset.mindrecord --label2id=/path/label2id_file --max_seq_len=seq_len
  454. ```
  455. For finetune and evaluation, just do
  456. ```bash
  457. bash scripts/ner.sh
  458. ```
  459. The command above will run in the background, you can view training logs in ner_log.txt.
  460. If you choose SpanF1 as assessment method and mode use_crf is set to be "true", the result will be as follows if evaluation is done after finetuning 10 epoches:
  461. ```text
  462. Precision 0.953826
  463. Recall 0.957749
  464. F1 0.955784
  465. ```
  466. #### evaluation on squad v1.1 dataset when running on Ascend
  467. ```bash
  468. bash scripts/squad.sh
  469. ```
  470. The command above will run in the background, you can view training logs in squad_log.txt.
  471. The result will be as follows:
  472. ```text
  473. {"exact_match": 80.3878923040233284, "f1": 87.6902384023850329}
  474. ```
  475. ## [Model Description](#contents)
  476. ## [Performance](#contents)
  477. ### Pretraining Performance
  478. | Parameters | Ascend | GPU |
  479. | -------------------------- | ---------------------------------------------------------- | ------------------------- |
  480. | Model Version | BERT_base | BERT_base |
  481. | Resource | Ascend 910, cpu:2.60GHz 192cores, memory:755G | NV SMX2 V100-16G, cpu: Intel(R) Xeon(R) Platinum 8160 CPU @2.10GHz, memory: 256G |
  482. | uploaded Date | 08/22/2020 | 05/06/2020 |
  483. | MindSpore Version | 1.0.0 | 1.0.0 |
  484. | Dataset | cn-wiki-128(4000w) | cn-wiki-128(4000w) |
  485. | Training Parameters | src/config.py | src/config.py |
  486. | Optimizer | Lamb | AdamWeightDecay |
  487. | Loss Function | SoftmaxCrossEntropy | SoftmaxCrossEntropy |
  488. | outputs | probability | probability |
  489. | Epoch | 40 | 40 |
  490. | Batch_size | 256*8 | 32*8 |
  491. | Loss | 1.7 | 1.7 |
  492. | Speed | 340ms/step | 290ms/step |
  493. | Total time | 73h | 610H |
  494. | Params (M) | 110M | 110M |
  495. | Checkpoint for Fine tuning | 1.2G(.ckpt file) | 1.2G(.ckpt file) |
  496. | Scripts | [BERT_base](https://gitee.com/mindspore/mindspore/tree/master/model_zoo/official/nlp/bert) | [BERT_base](https://gitee.com/mindspore/mindspore/tree/master/model_zoo/official/nlp/bert) |
  497. | Parameters | Ascend |
  498. | -------------------------- | ---------------------------------------------------------- |
  499. | Model Version | BERT_NEZHA |
  500. | Resource | Ascend 910, cpu:2.60GHz 192cores, memory:755G |
  501. | uploaded Date | 08/20/2020 |
  502. | MindSpore Version | 1.0.0 |
  503. | Dataset | cn-wiki-128(4000w) |
  504. | Training Parameters | src/config.py |
  505. | Optimizer | Lamb |
  506. | Loss Function | SoftmaxCrossEntropy |
  507. | outputs | probability |
  508. | Epoch | 40 |
  509. | Batch_size | 96*8 |
  510. | Loss | 1.7 |
  511. | Speed | 360ms/step |
  512. | Total time | 200h |
  513. | Params (M) | 340M |
  514. | Checkpoint for Fine tuning | 3.2G(.ckpt file) |
  515. | Scripts | [BERT_NEZHA](https://gitee.com/mindspore/mindspore/tree/master/model_zoo/official/nlp/bert) |
  516. #### Inference Performance
  517. | Parameters | Ascend |
  518. | -------------------------- | ----------------------------- |
  519. | Model Version | |
  520. | Resource | Ascend 910 |
  521. | uploaded Date | 08/22/2020 |
  522. | MindSpore Version | 1.0.0 |
  523. | Dataset | cola, 1.2W |
  524. | batch_size | 32(1P) |
  525. | Accuracy | 0.588986 |
  526. | Speed | 59.25ms/step |
  527. | Total time | 15min |
  528. | Model for inference | 1.2G(.ckpt file) |
  529. # [Description of Random Situation](#contents)
  530. In run_standalone_pretrain.sh and run_distributed_pretrain.sh, we set do_shuffle to True to shuffle the dataset by default.
  531. In run_classifier.sh, run_ner.sh and run_squad.sh, we set train_data_shuffle and eval_data_shuffle to True to shuffle the dataset by default.
  532. In config.py, we set the hidden_dropout_prob and attention_pros_dropout_prob to 0.1 to dropout some network node by default.
  533. In run_pretrain.py, we set a random seed to make sure that each node has the same initial weight in distribute training.
  534. # [ModelZoo Homepage](#contents)
  535. Please check the official [homepage](https://gitee.com/mindspore/mindspore/tree/master/model_zoo).