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 37 kB

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
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
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. # Contents
  2. - [Contents](#contents)
  3. - [BERT Description](#bert-description)
  4. - [Model Architecture](#model-architecture)
  5. - [Dataset](#dataset)
  6. - [Environment Requirements](#environment-requirements)
  7. - [Quick Start](#quick-start)
  8. - [Script Description](#script-description)
  9. - [Script and Sample Code](#script-and-sample-code)
  10. - [Script Parameters](#script-parameters)
  11. - [Pre-Training](#pre-training)
  12. - [Fine-Tuning and Evaluation](#fine-tuning-and-evaluation)
  13. - [Options and Parameters](#options-and-parameters)
  14. - [Options:](#options)
  15. - [Parameters:](#parameters)
  16. - [Training Process](#training-process)
  17. - [Training](#training)
  18. - [Running on Ascend](#running-on-ascend)
  19. - [running on GPU](#running-on-gpu)
  20. - [Distributed Training](#distributed-training)
  21. - [Running on Ascend](#running-on-ascend-1)
  22. - [running on GPU](#running-on-gpu-1)
  23. - [Evaluation Process](#evaluation-process)
  24. - [Evaluation](#evaluation)
  25. - [evaluation on cola dataset when running on Ascend](#evaluation-on-cola-dataset-when-running-on-ascend)
  26. - [evaluation on cluener dataset when running on Ascend](#evaluation-on-cluener-dataset-when-running-on-ascend)
  27. - [evaluation on squad v1.1 dataset when running on Ascend](#evaluation-on-squad-v11-dataset-when-running-on-ascend)
  28. - [Model Description](#model-description)
  29. - [Performance](#performance)
  30. - [Pretraining Performance](#pretraining-performance)
  31. - [Inference Performance](#inference-performance)
  32. - [Description of Random Situation](#description-of-random-situation)
  33. - [ModelZoo Homepage](#modelzoo-homepage)
  34. # [BERT Description](#contents)
  35. 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.
  36. [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.
  37. [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.
  38. # [Model Architecture](#contents)
  39. 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.
  40. # [Dataset](#contents)
  41. - 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.
  42. - 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.
  43. # [Environment Requirements](#contents)
  44. - Hardware(Ascend/GPU)
  45. - 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.
  46. - Framework
  47. - [MindSpore](https://gitee.com/mindspore/mindspore)
  48. - For more information, please check the resources below:
  49. - [MindSpore Tutorials](https://www.mindspore.cn/tutorial/training/en/master/index.html)
  50. - [MindSpore Python API](https://www.mindspore.cn/doc/api_python/en/master/index.html)
  51. # [Quick Start](#contents)
  52. After installing MindSpore via the official website, you can start pre-training, fine-tuning and evaluation as follows:
  53. - Running on Ascend
  54. ```bash
  55. # run standalone pre-training example
  56. bash scripts/run_standalone_pretrain_ascend.sh 0 1 /path/cn-wiki-128
  57. # run distributed pre-training example
  58. bash scripts/run_distributed_pretrain_ascend.sh /path/cn-wiki-128 /path/hccl.json
  59. # run fine-tuning and evaluation example
  60. - If you are going to run a fine-tuning task, please prepare a checkpoint generated from pre-training.
  61. - Set bert network config and optimizer hyperparameters in `finetune_eval_config.py`.
  62. - Classification task: Set task related hyperparameters in scripts/run_classifier.sh.
  63. - Run `bash scripts/run_classifier.py` for fine-tuning of BERT-base and BERT-NEZHA model.
  64. bash scripts/run_classifier.sh
  65. - NER task: Set task related hyperparameters in scripts/run_ner.sh.
  66. - Run `bash scripts/run_ner.py` for fine-tuning of BERT-base and BERT-NEZHA model.
  67. bash scripts/run_ner.sh
  68. - SQuAD task: Set task related hyperparameters in scripts/run_squad.sh.
  69. - Run `bash scripts/run_squad.py` for fine-tuning of BERT-base and BERT-NEZHA model.
  70. bash scripts/run_squad.sh
  71. ```
  72. - Running on GPU
  73. ```bash
  74. # run standalone pre-training example
  75. bash run_standalone_pretrain_for_gpu.sh 0 1 /path/cn-wiki-128
  76. # run distributed pre-training example
  77. bash scripts/run_distributed_pretrain_for_gpu.sh 8 40 /path/cn-wiki-128
  78. # run fine-tuning and evaluation example
  79. - If you are going to run a fine-tuning task, please prepare a checkpoint generated from pre-training.
  80. - Set bert network config and optimizer hyperparameters in `finetune_eval_config.py`.
  81. - Classification task: Set task related hyperparameters in scripts/run_classifier.sh.
  82. - Run `bash scripts/run_classifier.py` for fine-tuning of BERT-base and BERT-NEZHA model.
  83. bash scripts/run_classifier.sh
  84. - NER task: Set task related hyperparameters in scripts/run_ner.sh.
  85. - Run `bash scripts/run_ner.py` for fine-tuning of BERT-base and BERT-NEZHA model.
  86. bash scripts/run_ner.sh
  87. - SQuAD task: Set task related hyperparameters in scripts/run_squad.sh.
  88. - Run `bash scripts/run_squad.py` for fine-tuning of BERT-base and BERT-NEZHA model.
  89. bash scripts/run_squad.sh
  90. ```
  91. For distributed training on Ascend, an hccl configuration file with JSON format needs to be created in advance.
  92. 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.
  93. 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.
  94. Please follow the instructions in the link below to create an hccl.json file in need:
  95. [https://gitee.com/mindspore/mindspore/tree/master/model_zoo/utils/hccl_tools](https://gitee.com/mindspore/mindspore/tree/master/model_zoo/utils/hccl_tools).
  96. 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.
  97. ```text
  98. For pretraining, schema file contains ["input_ids", "input_mask", "segment_ids", "next_sentence_labels", "masked_lm_positions", "masked_lm_ids", "masked_lm_weights"].
  99. For ner or classification task, schema file contains ["input_ids", "input_mask", "segment_ids", "label_ids"].
  100. 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"].
  101. `numRows` is the only option which could be set by user, other values must be set according to the dataset.
  102. For example, the schema file of cn-wiki-128 dataset for pretraining shows as follows:
  103. {
  104. "datasetType": "TF",
  105. "numRows": 7680,
  106. "columns": {
  107. "input_ids": {
  108. "type": "int64",
  109. "rank": 1,
  110. "shape": [128]
  111. },
  112. "input_mask": {
  113. "type": "int64",
  114. "rank": 1,
  115. "shape": [128]
  116. },
  117. "segment_ids": {
  118. "type": "int64",
  119. "rank": 1,
  120. "shape": [128]
  121. },
  122. "next_sentence_labels": {
  123. "type": "int64",
  124. "rank": 1,
  125. "shape": [1]
  126. },
  127. "masked_lm_positions": {
  128. "type": "int64",
  129. "rank": 1,
  130. "shape": [20]
  131. },
  132. "masked_lm_ids": {
  133. "type": "int64",
  134. "rank": 1,
  135. "shape": [20]
  136. },
  137. "masked_lm_weights": {
  138. "type": "float32",
  139. "rank": 1,
  140. "shape": [20]
  141. }
  142. }
  143. }
  144. ```
  145. # [Script Description](#contents)
  146. ## [Script and Sample Code](#contents)
  147. ```shell
  148. .
  149. └─bert
  150. ├─README.md
  151. ├─scripts
  152. ├─ascend_distributed_launcher
  153. ├─__init__.py
  154. ├─hyper_parameter_config.ini # hyper paramter for distributed pretraining
  155. ├─get_distribute_pretrain_cmd.py # script for distributed pretraining
  156. ├─README.md
  157. ├─run_classifier.sh # shell script for standalone classifier task on ascend or gpu
  158. ├─run_ner.sh # shell script for standalone NER task on ascend or gpu
  159. ├─run_squad.sh # shell script for standalone SQUAD task on ascend or gpu
  160. ├─run_standalone_pretrain_ascend.sh # shell script for standalone pretrain on ascend
  161. ├─run_distributed_pretrain_ascend.sh # shell script for distributed pretrain on ascend
  162. ├─run_distributed_pretrain_gpu.sh # shell script for distributed pretrain on gpu
  163. └─run_standaloned_pretrain_gpu.sh # shell script for distributed pretrain on gpu
  164. ├─src
  165. ├─__init__.py
  166. ├─assessment_method.py # assessment method for evaluation
  167. ├─bert_for_finetune.py # backbone code of network
  168. ├─bert_for_pre_training.py # backbone code of network
  169. ├─bert_model.py # backbone code of network
  170. ├─clue_classification_dataset_precess.py # data preprocessing
  171. ├─cluner_evaluation.py # evaluation for cluner
  172. ├─config.py # parameter configuration for pretraining
  173. ├─CRF.py # assessment method for clue dataset
  174. ├─dataset.py # data preprocessing
  175. ├─finetune_eval_config.py # parameter configuration for finetuning
  176. ├─finetune_eval_model.py # backbone code of network
  177. ├─sample_process.py # sample processing
  178. ├─utils.py # util function
  179. ├─pretrain_eval.py # train and eval net
  180. ├─run_classifier.py # finetune and eval net for classifier task
  181. ├─run_ner.py # finetune and eval net for ner task
  182. ├─run_pretrain.py # train net for pretraining phase
  183. └─run_squad.py # finetune and eval net for squad task
  184. ```
  185. ## [Script Parameters](#contents)
  186. ### Pre-Training
  187. ```text
  188. usage: run_pretrain.py [--distribute DISTRIBUTE] [--epoch_size N] [----device_num N] [--device_id N]
  189. [--enable_save_ckpt ENABLE_SAVE_CKPT] [--device_target DEVICE_TARGET]
  190. [--enable_lossscale ENABLE_LOSSSCALE] [--do_shuffle DO_SHUFFLE]
  191. [--enable_data_sink ENABLE_DATA_SINK] [--data_sink_steps N]
  192. [--accumulation_steps N]
  193. [--save_checkpoint_path SAVE_CHECKPOINT_PATH]
  194. [--load_checkpoint_path LOAD_CHECKPOINT_PATH]
  195. [--save_checkpoint_steps N] [--save_checkpoint_num N]
  196. [--data_dir DATA_DIR] [--schema_dir SCHEMA_DIR] [train_steps N]
  197. options:
  198. --device_target device where the code will be implemented: "Ascend" | "GPU", default is "Ascend"
  199. --distribute pre_training by serveral devices: "true"(training by more than 1 device) | "false", default is "false"
  200. --epoch_size epoch size: N, default is 1
  201. --device_num number of used devices: N, default is 1
  202. --device_id device id: N, default is 0
  203. --enable_save_ckpt enable save checkpoint: "true" | "false", default is "true"
  204. --enable_lossscale enable lossscale: "true" | "false", default is "true"
  205. --do_shuffle enable shuffle: "true" | "false", default is "true"
  206. --enable_data_sink enable data sink: "true" | "false", default is "true"
  207. --data_sink_steps set data sink steps: N, default is 1
  208. --accumulation_steps accumulate gradients N times before weight update: N, default is 1
  209. --save_checkpoint_path path to save checkpoint files: PATH, default is ""
  210. --load_checkpoint_path path to load checkpoint files: PATH, default is ""
  211. --save_checkpoint_steps steps for saving checkpoint files: N, default is 1000
  212. --save_checkpoint_num number for saving checkpoint files: N, default is 1
  213. --train_steps Training Steps: N, default is -1
  214. --data_dir path to dataset directory: PATH, default is ""
  215. --schema_dir path to schema.json file, PATH, default is ""
  216. ```
  217. ### Fine-Tuning and Evaluation
  218. ```text
  219. usage: run_ner.py [--device_target DEVICE_TARGET] [--do_train DO_TRAIN] [----do_eval DO_EVAL]
  220. [--assessment_method ASSESSMENT_METHOD] [--use_crf USE_CRF]
  221. [--device_id N] [--epoch_num N] [--vocab_file_path VOCAB_FILE_PATH]
  222. [--label2id_file_path LABEL2ID_FILE_PATH]
  223. [--train_data_shuffle TRAIN_DATA_SHUFFLE]
  224. [--eval_data_shuffle EVAL_DATA_SHUFFLE]
  225. [--save_finetune_checkpoint_path SAVE_FINETUNE_CHECKPOINT_PATH]
  226. [--load_pretrain_checkpoint_path LOAD_PRETRAIN_CHECKPOINT_PATH]
  227. [--train_data_file_path TRAIN_DATA_FILE_PATH]
  228. [--eval_data_file_path EVAL_DATA_FILE_PATH]
  229. [--schema_file_path SCHEMA_FILE_PATH]
  230. options:
  231. --device_target device where the code will be implemented: "Ascend" | "GPU", default is "Ascend"
  232. --do_train whether to run training on training set: true | false
  233. --do_eval whether to run eval on dev set: true | false
  234. --assessment_method assessment method to do evaluation: f1 | clue_benchmark
  235. --use_crf whether to use crf to calculate loss: true | false
  236. --device_id device id to run task
  237. --epoch_num total number of training epochs to perform
  238. --num_class number of classes to do labeling
  239. --train_data_shuffle Enable train data shuffle, default is true
  240. --eval_data_shuffle Enable eval data shuffle, default is true
  241. --vocab_file_path the vocabulary file that the BERT model was trained on
  242. --label2id_file_path label to id json file
  243. --save_finetune_checkpoint_path path to save generated finetuning checkpoint
  244. --load_pretrain_checkpoint_path initial checkpoint (usually from a pre-trained BERT model)
  245. --load_finetune_checkpoint_path give a finetuning checkpoint path if only do eval
  246. --train_data_file_path ner tfrecord for training. E.g., train.tfrecord
  247. --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
  248. --schema_file_path path to datafile schema file
  249. usage: run_squad.py [--device_target DEVICE_TARGET] [--do_train DO_TRAIN] [----do_eval DO_EVAL]
  250. [--device_id N] [--epoch_num N] [--num_class N]
  251. [--vocab_file_path VOCAB_FILE_PATH]
  252. [--eval_json_path EVAL_JSON_PATH]
  253. [--train_data_shuffle TRAIN_DATA_SHUFFLE]
  254. [--eval_data_shuffle EVAL_DATA_SHUFFLE]
  255. [--save_finetune_checkpoint_path SAVE_FINETUNE_CHECKPOINT_PATH]
  256. [--load_pretrain_checkpoint_path LOAD_PRETRAIN_CHECKPOINT_PATH]
  257. [--load_finetune_checkpoint_path LOAD_FINETUNE_CHECKPOINT_PATH]
  258. [--train_data_file_path TRAIN_DATA_FILE_PATH]
  259. [--eval_data_file_path EVAL_DATA_FILE_PATH]
  260. [--schema_file_path SCHEMA_FILE_PATH]
  261. options:
  262. --device_target device where the code will be implemented: "Ascend" | "GPU", default is "Ascend"
  263. --do_train whether to run training on training set: true | false
  264. --do_eval whether to run eval on dev set: true | false
  265. --device_id device id to run task
  266. --epoch_num total number of training epochs to perform
  267. --num_class number of classes to classify, usually 2 for squad task
  268. --train_data_shuffle Enable train data shuffle, default is true
  269. --eval_data_shuffle Enable eval data shuffle, default is true
  270. --vocab_file_path the vocabulary file that the BERT model was trained on
  271. --eval_json_path path to squad dev json file
  272. --save_finetune_checkpoint_path path to save generated finetuning checkpoint
  273. --load_pretrain_checkpoint_path initial checkpoint (usually from a pre-trained BERT model)
  274. --load_finetune_checkpoint_path give a finetuning checkpoint path if only do eval
  275. --train_data_file_path squad tfrecord for training. E.g., train1.1.tfrecord
  276. --eval_data_file_path squad tfrecord for predictions. E.g., dev1.1.tfrecord
  277. --schema_file_path path to datafile schema file
  278. usage: run_classifier.py [--device_target DEVICE_TARGET] [--do_train DO_TRAIN] [----do_eval DO_EVAL]
  279. [--assessment_method ASSESSMENT_METHOD] [--device_id N] [--epoch_num N] [--num_class N]
  280. [--save_finetune_checkpoint_path SAVE_FINETUNE_CHECKPOINT_PATH]
  281. [--load_pretrain_checkpoint_path LOAD_PRETRAIN_CHECKPOINT_PATH]
  282. [--load_finetune_checkpoint_path LOAD_FINETUNE_CHECKPOINT_PATH]
  283. [--train_data_shuffle TRAIN_DATA_SHUFFLE]
  284. [--eval_data_shuffle EVAL_DATA_SHUFFLE]
  285. [--train_data_file_path TRAIN_DATA_FILE_PATH]
  286. [--eval_data_file_path EVAL_DATA_FILE_PATH]
  287. [--schema_file_path SCHEMA_FILE_PATH]
  288. options:
  289. --device_target targeted device to run task: Ascend | GPU
  290. --do_train whether to run training on training set: true | false
  291. --do_eval whether to run eval on dev set: true | false
  292. --assessment_method assessment method to do evaluation: accuracy | f1 | mcc | spearman_correlation
  293. --device_id device id to run task
  294. --epoch_num total number of training epochs to perform
  295. --num_class number of classes to do labeling
  296. --train_data_shuffle Enable train data shuffle, default is true
  297. --eval_data_shuffle Enable eval data shuffle, default is true
  298. --save_finetune_checkpoint_path path to save generated finetuning checkpoint
  299. --load_pretrain_checkpoint_path initial checkpoint (usually from a pre-trained BERT model)
  300. --load_finetune_checkpoint_path give a finetuning checkpoint path if only do eval
  301. --train_data_file_path tfrecord for training. E.g., train.tfrecord
  302. --eval_data_file_path tfrecord for predictions. E.g., dev.tfrecord
  303. --schema_file_path path to datafile schema file
  304. ```
  305. ## Options and Parameters
  306. Parameters for training and evaluation can be set in file `config.py` and `finetune_eval_config.py` respectively.
  307. ### Options
  308. ```text
  309. config for lossscale and etc.
  310. bert_network version of BERT model: base | nezha, default is base
  311. batch_size batch size of input dataset: N, default is 16
  312. loss_scale_value initial value of loss scale: N, default is 2^32
  313. scale_factor factor used to update loss scale: N, default is 2
  314. scale_window steps for once updatation of loss scale: N, default is 1000
  315. optimizer optimizer used in the network: AdamWerigtDecayDynamicLR | Lamb | Momentum, default is "Lamb"
  316. ```
  317. ### Parameters
  318. ```text
  319. Parameters for dataset and network (Pre-Training/Fine-Tuning/Evaluation):
  320. seq_length length of input sequence: N, default is 128
  321. vocab_size size of each embedding vector: N, must be consistant with the dataset you use. Default is 21136
  322. hidden_size size of bert encoder layers: N, default is 768
  323. num_hidden_layers number of hidden layers: N, default is 12
  324. num_attention_heads number of attention heads: N, default is 12
  325. intermediate_size size of intermediate layer: N, default is 3072
  326. hidden_act activation function used: ACTIVATION, default is "gelu"
  327. hidden_dropout_prob dropout probability for BertOutput: Q, default is 0.1
  328. attention_probs_dropout_prob dropout probability for BertAttention: Q, default is 0.1
  329. max_position_embeddings maximum length of sequences: N, default is 512
  330. type_vocab_size size of token type vocab: N, default is 16
  331. initializer_range initialization value of TruncatedNormal: Q, default is 0.02
  332. use_relative_positions use relative positions or not: True | False, default is False
  333. dtype data type of input: mstype.float16 | mstype.float32, default is mstype.float32
  334. compute_type compute type in BertTransformer: mstype.float16 | mstype.float32, default is mstype.float16
  335. Parameters for optimizer:
  336. AdamWeightDecay:
  337. decay_steps steps of the learning rate decay: N
  338. learning_rate value of learning rate: Q
  339. end_learning_rate value of end learning rate: Q, must be positive
  340. power power: Q
  341. warmup_steps steps of the learning rate warm up: N
  342. weight_decay weight decay: Q
  343. eps term added to the denominator to improve numerical stability: Q
  344. Lamb:
  345. decay_steps steps of the learning rate decay: N
  346. learning_rate value of learning rate: Q
  347. end_learning_rate value of end learning rate: Q
  348. power power: Q
  349. warmup_steps steps of the learning rate warm up: N
  350. weight_decay weight decay: Q
  351. Momentum:
  352. learning_rate value of learning rate: Q
  353. momentum momentum for the moving average: Q
  354. ```
  355. ## [Training Process](#contents)
  356. ### Training
  357. #### Running on Ascend
  358. ```bash
  359. bash scripts/run_standalone_pretrain_ascend.sh 0 1 /path/cn-wiki-128
  360. ```
  361. 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:
  362. ```text
  363. # grep "epoch" pretraining_log.txt
  364. epoch: 0.0, current epoch percent: 0.000, step: 1, outpus are (Tensor(shape=[1], dtype=Float32, [ 1.0856101e+01]), Tensor(shape=[], dtype=Bool, False), Tensor(shape=[], dtype=Float32, 65536))
  365. epoch: 0.0, current epoch percent: 0.000, step: 2, outpus are (Tensor(shape=[1], dtype=Float32, [ 1.0821701e+01]), Tensor(shape=[], dtype=Bool, False), Tensor(shape=[], dtype=Float32, 65536))
  366. ...
  367. ```
  368. #### running on GPU
  369. ```bash
  370. bash scripts/run_standalone_pretrain_for_gpu.sh 0 1 /path/cn-wiki-128
  371. ```
  372. 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:
  373. ```bash
  374. # grep "epoch" pretraining_log.txt
  375. epoch: 0.0, current epoch percent: 0.000, step: 1, outpus are (Tensor(shape=[1], dtype=Float32, [ 1.0856101e+01]), Tensor(shape=[], dtype=Bool, False), Tensor(shape=[], dtype=Float32, 65536))
  376. epoch: 0.0, current epoch percent: 0.000, step: 2, outpus are (Tensor(shape=[1], dtype=Float32, [ 1.0821701e+01]), Tensor(shape=[], dtype=Bool, False), Tensor(shape=[], dtype=Float32, 65536))
  377. ...
  378. ```
  379. > **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.
  380. >
  381. > ```bash
  382. > export HCCL_CONNECT_TIMEOUT=600
  383. > ```
  384. >
  385. > This will extend the timeout limits of hccl from the default 120 seconds to 600 seconds.
  386. > **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.
  387. >
  388. > ```bash
  389. > export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python
  390. > ```
  391. ### Distributed Training
  392. #### Running on Ascend
  393. ```bash
  394. bash scripts/run_distributed_pretrain_ascend.sh /path/cn-wiki-128 /path/hccl.json
  395. ```
  396. 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:
  397. ```bash
  398. # grep "epoch" LOG*/pretraining_log.txt
  399. epoch: 0.0, current epoch percent: 0.001, step: 100, outpus are (Tensor(shape=[1], dtype=Float32, [ 1.08209e+01]), Tensor(shape=[], dtype=Bool, False), Tensor(shape=[], dtype=Float32, 65536))
  400. epoch: 0.0, current epoch percent: 0.002, step: 200, outpus are (Tensor(shape=[1], dtype=Float32, [ 1.07566e+01]), Tensor(shape=[], dtype=Bool, False), Tensor(shape=[], dtype=Float32, 65536))
  401. ...
  402. epoch: 0.0, current epoch percent: 0.001, step: 100, outpus are (Tensor(shape=[1], dtype=Float32, [ 1.08218e+01]), Tensor(shape=[], dtype=Bool, False), Tensor(shape=[], dtype=Float32, 65536))
  403. epoch: 0.0, current epoch percent: 0.002, step: 200, outpus are (Tensor(shape=[1], dtype=Float32, [ 1.07770e+01]), Tensor(shape=[], dtype=Bool, False), Tensor(shape=[], dtype=Float32, 65536))
  404. ...
  405. ```
  406. #### running on GPU
  407. ```bash
  408. bash scripts/run_distributed_pretrain_for_gpu.sh /path/cn-wiki-128
  409. ```
  410. 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:
  411. ```bash
  412. # grep "epoch" LOG*/pretraining_log.txt
  413. epoch: 0.0, current epoch percent: 0.001, step: 100, outpus are (Tensor(shape=[1], dtype=Float32, [ 1.08209e+01]), Tensor(shape=[], dtype=Bool, False), Tensor(shape=[], dtype=Float32, 65536))
  414. epoch: 0.0, current epoch percent: 0.002, step: 200, outpus are (Tensor(shape=[1], dtype=Float32, [ 1.07566e+01]), Tensor(shape=[], dtype=Bool, False), Tensor(shape=[], dtype=Float32, 65536))
  415. ...
  416. epoch: 0.0, current epoch percent: 0.001, step: 100, outpus are (Tensor(shape=[1], dtype=Float32, [ 1.08218e+01]), Tensor(shape=[], dtype=Bool, False), Tensor(shape=[], dtype=Float32, 65536))
  417. epoch: 0.0, current epoch percent: 0.002, step: 200, outpus are (Tensor(shape=[1], dtype=Float32, [ 1.07770e+01]), Tensor(shape=[], dtype=Bool, False), Tensor(shape=[], dtype=Float32, 65536))
  418. ...
  419. ```
  420. > **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`
  421. ## [Evaluation Process](#contents)
  422. ### Evaluation
  423. #### evaluation on cola dataset when running on Ascend
  424. 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".
  425. ```bash
  426. bash scripts/run_classifier.sh
  427. ```
  428. The command above will run in the background, you can view training logs in classfier_log.txt.
  429. If you choose accuracy as assessment method, the result will be as follows:
  430. ```text
  431. acc_num XXX, total_num XXX, accuracy 0.588986
  432. ```
  433. #### evaluation on cluener dataset when running on Ascend
  434. ```bash
  435. bash scripts/ner.sh
  436. ```
  437. The command above will run in the background, you can view training logs in ner_log.txt.
  438. If you choose F1 as assessment method, the result will be as follows:
  439. ```text
  440. Precision 0.920507
  441. Recall 0.948683
  442. F1 0.920507
  443. ```
  444. #### evaluation on squad v1.1 dataset when running on Ascend
  445. ```bash
  446. bash scripts/squad.sh
  447. ```
  448. The command above will run in the background, you can view training logs in squad_log.txt.
  449. The result will be as follows:
  450. ```text
  451. {"exact_match": 80.3878923040233284, "f1": 87.6902384023850329}
  452. ```
  453. ## [Model Description](#contents)
  454. ## [Performance](#contents)
  455. ### Pretraining Performance
  456. | Parameters | Ascend | GPU |
  457. | -------------------------- | ---------------------------------------------------------- | ------------------------- |
  458. | Model Version | BERT_base | BERT_base |
  459. | 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 |
  460. | uploaded Date | 08/22/2020 | 05/06/2020 |
  461. | MindSpore Version | 1.0.0 | 1.0.0 |
  462. | Dataset | cn-wiki-128(4000w) | cn-wiki-128(4000w) |
  463. | Training Parameters | src/config.py | src/config.py |
  464. | Optimizer | Lamb | AdamWeightDecay |
  465. | Loss Function | SoftmaxCrossEntropy | SoftmaxCrossEntropy |
  466. | outputs | probability | probability |
  467. | Epoch | 40 | 40 |
  468. | Batch_size | 256*8 | 32*8 |
  469. | Loss | 1.7 | 1.7 |
  470. | Speed | 340ms/step | 290ms/step |
  471. | Total time | 73h | 610H |
  472. | Params (M) | 110M | 110M |
  473. | Checkpoint for Fine tuning | 1.2G(.ckpt file) | 1.2G(.ckpt file) |
  474. | 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) |
  475. | Parameters | Ascend |
  476. | -------------------------- | ---------------------------------------------------------- |
  477. | Model Version | BERT_NEZHA |
  478. | Resource | Ascend 910, cpu:2.60GHz 192cores, memory:755G |
  479. | uploaded Date | 08/20/2020 |
  480. | MindSpore Version | 1.0.0 |
  481. | Dataset | cn-wiki-128(4000w) |
  482. | Training Parameters | src/config.py |
  483. | Optimizer | Lamb |
  484. | Loss Function | SoftmaxCrossEntropy |
  485. | outputs | probability |
  486. | Epoch | 40 |
  487. | Batch_size | 96*8 |
  488. | Loss | 1.7 |
  489. | Speed | 360ms/step |
  490. | Total time | 200h |
  491. | Params (M) | 340M |
  492. | Checkpoint for Fine tuning | 3.2G(.ckpt file) |
  493. | Scripts | [BERT_NEZHA](https://gitee.com/mindspore/mindspore/tree/master/model_zoo/official/nlp/bert) |
  494. #### Inference Performance
  495. | Parameters | Ascend |
  496. | -------------------------- | ----------------------------- |
  497. | Model Version | |
  498. | Resource | Ascend 910 |
  499. | uploaded Date | 08/22/2020 |
  500. | MindSpore Version | 1.0.0 |
  501. | Dataset | cola, 1.2W |
  502. | batch_size | 32(1P) |
  503. | Accuracy | 0.588986 |
  504. | Speed | 59.25ms/step |
  505. | Total time | 15min |
  506. | Model for inference | 1.2G(.ckpt file) |
  507. # [Description of Random Situation](#contents)
  508. In run_standalone_pretrain.sh and run_distributed_pretrain.sh, we set do_shuffle to True to shuffle the dataset by default.
  509. 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.
  510. In config.py, we set the hidden_dropout_prob and attention_pros_dropout_prob to 0.1 to dropout some network node by default.
  511. In run_pretrain.py, we set a random seed to make sure that each node has the same initial weight in distribute training.
  512. # [ModelZoo Homepage](#contents)
  513. Please check the official [homepage](https://gitee.com/mindspore/mindspore/tree/master/model_zoo).