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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. # BERT Example
  2. ## Description
  3. This example implements pre-training, fine-tuning and evaluation of [BERT-base](https://github.com/google-research/bert) and [BERT-NEZHA](https://github.com/huawei-noah/Pretrained-Language-Model).
  4. ## Requirements
  5. - Install [MindSpore](https://www.mindspore.cn/install/en).
  6. - Download the zhwiki dataset for pre-training. Extract and clean text in the dataset with [WikiExtractor](https://github.com/attardi/wikiextractor). Convert the dataset to TFRecord format and move the files to a specified path.
  7. - Download dataset for fine-tuning and evaluation such as CLUENER, TNEWS, SQuAD v1.1, etc.
  8. - Convert dataset files from json format to tfrecord format, please refer to run_classifier.py which in [BERT](https://github.com/google-research/bert) repository.
  9. > Notes:
  10. If you are running a fine-tuning or evaluation task, prepare a checkpoint from pre-train.
  11. ## Running the Example
  12. ### Pre-Training
  13. - Set options in `config.py`, including lossscale, optimizer and network. Click [here](https://www.mindspore.cn/tutorial/zh-CN/master/use/data_preparation/loading_the_datasets.html#tfrecord) for more information about dataset and the json schema file.
  14. - Run `run_standalone_pretrain.sh` for non-distributed pre-training of BERT-base and BERT-NEZHA model.
  15. ``` bash
  16. sh scripts/run_standalone_pretrain.sh DEVICE_ID EPOCH_SIZE DATA_DIR SCHEMA_DIR
  17. ```
  18. - Run `run_distribute_pretrain.sh` for distributed pre-training of BERT-base and BERT-NEZHA model.
  19. ``` bash
  20. sh scripts/run_distribute_pretrain.sh DATA_DIR RANK_TABLE_FILE
  21. ```
  22. ### Fine-Tuning and Evaluation
  23. - Including three kinds of task: Classification, NER(Named Entity Recognition) and SQuAD(Stanford Question Answering Dataset)
  24. - Set bert network config and optimizer hyperparameters in `finetune_eval_config.py`.
  25. - Classification task: Set task related hyperparameters in scripts/run_classifier.sh.
  26. - Run `bash scripts/run_classifier.py` for fine-tuning of BERT-base and BERT-NEZHA model.
  27. ```bash
  28. bash scripts/run_classifier.sh
  29. ```
  30. - NER task: Set task related hyperparameters in scripts/run_ner.sh.
  31. - Run `bash scripts/run_ner.py` for fine-tuning of BERT-base and BERT-NEZHA model.
  32. ```bash
  33. bash scripts/run_ner.sh
  34. ```
  35. - SQuAD task: Set task related hyperparameters in scripts/run_squad.sh.
  36. - Run `bash scripts/run_squad.py` for fine-tuning of BERT-base and BERT-NEZHA model.
  37. ```bash
  38. bash scripts/run_squad.sh
  39. ```
  40. ## Usage
  41. ### Pre-Training
  42. ```
  43. usage: run_pretrain.py [--distribute DISTRIBUTE] [--epoch_size N] [----device_num N] [--device_id N]
  44. [--enable_save_ckpt ENABLE_SAVE_CKPT]
  45. [--enable_lossscale ENABLE_LOSSSCALE] [--do_shuffle DO_SHUFFLE]
  46. [--enable_data_sink ENABLE_DATA_SINK] [--data_sink_steps N] [--checkpoint_path CHECKPOINT_PATH]
  47. [--save_checkpoint_steps N] [--save_checkpoint_num N]
  48. [--data_dir DATA_DIR] [--schema_dir SCHEMA_DIR]
  49. options:
  50. --distribute pre_training by serveral devices: "true"(training by more than 1 device) | "false", default is "false"
  51. --epoch_size epoch size: N, default is 1
  52. --device_num number of used devices: N, default is 1
  53. --device_id device id: N, default is 0
  54. --enable_save_ckpt enable save checkpoint: "true" | "false", default is "true"
  55. --enable_lossscale enable lossscale: "true" | "false", default is "true"
  56. --do_shuffle enable shuffle: "true" | "false", default is "true"
  57. --enable_data_sink enable data sink: "true" | "false", default is "true"
  58. --data_sink_steps set data sink steps: N, default is 1
  59. --checkpoint_path path to save checkpoint files: PATH, default is ""
  60. --save_checkpoint_steps steps for saving checkpoint files: N, default is 1000
  61. --save_checkpoint_num number for saving checkpoint files: N, default is 1
  62. --data_dir path to dataset directory: PATH, default is ""
  63. --schema_dir path to schema.json file, PATH, default is ""
  64. ```
  65. ### Fine-Tuning and Evaluation
  66. ```
  67. usage: run_ner.py [--device_target DEVICE_TARGET] [--do_train DO_TRAIN] [----do_eval DO_EVAL]
  68. [--assessment_method ASSESSMENT_METHOD] [--use_crf USE_CRF]
  69. [--device_id N] [--epoch_num N] [--vocab_file_path VOCAB_FILE_PATH]
  70. [--label2id_file_path LABEL2ID_FILE_PATH]
  71. [--save_finetune_checkpoint_path SAVE_FINETUNE_CHECKPOINT_PATH]
  72. [--load_pretrain_checkpoint_path LOAD_PRETRAIN_CHECKPOINT_PATH]
  73. [--train_data_file_path TRAIN_DATA_FILE_PATH]
  74. [--eval_data_file_path EVAL_DATA_FILE_PATH]
  75. [--schema_file_path SCHEMA_FILE_PATH]
  76. options:
  77. --device_target targeted device to run task: Ascend | GPU
  78. --do_train whether to run training on training set: true | false
  79. --do_eval whether to run eval on dev set: true | false
  80. --assessment_method assessment method to do evaluation: f1 | clue_benchmark
  81. --use_crf whether to use crf to calculate loss: true | false
  82. --device_id device id to run task
  83. --epoch_num total number of training epochs to perform
  84. --num_class number of classes to do labeling
  85. --vocab_file_path the vocabulary file that the BERT model was trained on
  86. --label2id_file_path label to id json file
  87. --save_finetune_checkpoint_path path to save generated finetuning checkpoint
  88. --load_pretrain_checkpoint_path initial checkpoint (usually from a pre-trained BERT model)
  89. --load_finetune_checkpoint_path give a finetuning checkpoint path if only do eval
  90. --train_data_file_path ner tfrecord for training. E.g., train.tfrecord
  91. --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
  92. --schema_file_path path to datafile schema file
  93. usage: run_squad.py [--device_target DEVICE_TARGET] [--do_train DO_TRAIN] [----do_eval DO_EVAL]
  94. [--device_id N] [--epoch_num N] [--num_class N]
  95. [--vocab_file_path VOCAB_FILE_PATH]
  96. [--eval_json_path EVAL_JSON_PATH]
  97. [--save_finetune_checkpoint_path SAVE_FINETUNE_CHECKPOINT_PATH]
  98. [--load_pretrain_checkpoint_path LOAD_PRETRAIN_CHECKPOINT_PATH]
  99. [--load_finetune_checkpoint_path LOAD_FINETUNE_CHECKPOINT_PATH]
  100. [--train_data_file_path TRAIN_DATA_FILE_PATH]
  101. [--eval_data_file_path EVAL_DATA_FILE_PATH]
  102. [--schema_file_path SCHEMA_FILE_PATH]
  103. options:
  104. --device_target targeted device to run task: Ascend | GPU
  105. --do_train whether to run training on training set: true | false
  106. --do_eval whether to run eval on dev set: true | false
  107. --device_id device id to run task
  108. --epoch_num total number of training epochs to perform
  109. --num_class number of classes to classify, usually 2 for squad task
  110. --vocab_file_path the vocabulary file that the BERT model was trained on
  111. --eval_json_path path to squad dev json file
  112. --save_finetune_checkpoint_path path to save generated finetuning checkpoint
  113. --load_pretrain_checkpoint_path initial checkpoint (usually from a pre-trained BERT model)
  114. --load_finetune_checkpoint_path give a finetuning checkpoint path if only do eval
  115. --train_data_file_path squad tfrecord for training. E.g., train1.1.tfrecord
  116. --eval_data_file_path squad tfrecord for predictions. E.g., dev1.1.tfrecord
  117. --schema_file_path path to datafile schema file
  118. usage: run_classifier.py [--device_target DEVICE_TARGET] [--do_train DO_TRAIN] [----do_eval DO_EVAL]
  119. [--assessment_method ASSESSMENT_METHOD] [--device_id N] [--epoch_num N] [--num_class N]
  120. [--save_finetune_checkpoint_path SAVE_FINETUNE_CHECKPOINT_PATH]
  121. [--load_pretrain_checkpoint_path LOAD_PRETRAIN_CHECKPOINT_PATH]
  122. [--load_finetune_checkpoint_path LOAD_FINETUNE_CHECKPOINT_PATH]
  123. [--train_data_file_path TRAIN_DATA_FILE_PATH]
  124. [--eval_data_file_path EVAL_DATA_FILE_PATH]
  125. [--schema_file_path SCHEMA_FILE_PATH]
  126. options:
  127. --device_target targeted device to run task: Ascend | GPU
  128. --do_train whether to run training on training set: true | false
  129. --do_eval whether to run eval on dev set: true | false
  130. --assessment_method assessment method to do evaluation: accuracy | f1 | mcc | spearman_correlation
  131. --device_id device id to run task
  132. --epoch_num total number of training epochs to perform
  133. --num_class number of classes to do labeling
  134. --save_finetune_checkpoint_path path to save generated finetuning checkpoint
  135. --load_pretrain_checkpoint_path initial checkpoint (usually from a pre-trained BERT model)
  136. --load_finetune_checkpoint_path give a finetuning checkpoint path if only do eval
  137. --train_data_file_path tfrecord for training. E.g., train.tfrecord
  138. --eval_data_file_path tfrecord for predictions. E.g., dev.tfrecord
  139. --schema_file_path path to datafile schema file
  140. ```
  141. ## Options and Parameters
  142. It contains of parameters of BERT model and options for training, which is set in file `config.py` and `finetune_eval_config.py` respectively.
  143. ### Options:
  144. ```
  145. config.py:
  146. bert_network version of BERT model: base | nezha, default is base
  147. loss_scale_value initial value of loss scale: N, default is 2^32
  148. scale_factor factor used to update loss scale: N, default is 2
  149. scale_window steps for once updatation of loss scale: N, default is 1000
  150. optimizer optimizer used in the network: AdamWerigtDecayDynamicLR | Lamb | Momentum, default is "Lamb"
  151. ```
  152. ### Parameters:
  153. ```
  154. Parameters for dataset and network (Pre-Training/Fine-Tuning/Evaluation):
  155. batch_size batch size of input dataset: N, default is 16
  156. seq_length length of input sequence: N, default is 128
  157. vocab_size size of each embedding vector: N, must be consistant with the dataset you use. Default is 21136
  158. hidden_size size of bert encoder layers: N, default is 768
  159. num_hidden_layers number of hidden layers: N, default is 12
  160. num_attention_heads number of attention heads: N, default is 12
  161. intermediate_size size of intermediate layer: N, default is 3072
  162. hidden_act activation function used: ACTIVATION, default is "gelu"
  163. hidden_dropout_prob dropout probability for BertOutput: Q, default is 0.1
  164. attention_probs_dropout_prob dropout probability for BertAttention: Q, default is 0.1
  165. max_position_embeddings maximum length of sequences: N, default is 512
  166. type_vocab_size size of token type vocab: N, default is 16
  167. initializer_range initialization value of TruncatedNormal: Q, default is 0.02
  168. use_relative_positions use relative positions or not: True | False, default is False
  169. input_mask_from_dataset use the input mask loaded form dataset or not: True | False, default is True
  170. token_type_ids_from_dataset use the token type ids loaded from dataset or not: True | False, default is True
  171. dtype data type of input: mstype.float16 | mstype.float32, default is mstype.float32
  172. compute_type compute type in BertTransformer: mstype.float16 | mstype.float32, default is mstype.float16
  173. Parameters for optimizer:
  174. AdamWeightDecay:
  175. decay_steps steps of the learning rate decay: N
  176. learning_rate value of learning rate: Q
  177. end_learning_rate value of end learning rate: Q, must be positive
  178. power power: Q
  179. warmup_steps steps of the learning rate warm up: N
  180. weight_decay weight decay: Q
  181. eps term added to the denominator to improve numerical stability: Q
  182. Lamb:
  183. decay_steps steps of the learning rate decay: N
  184. learning_rate value of learning rate: Q
  185. end_learning_rate value of end learning rate: Q
  186. power power: Q
  187. warmup_steps steps of the learning rate warm up: N
  188. weight_decay weight decay: Q
  189. Momentum:
  190. learning_rate value of learning rate: Q
  191. momentum momentum for the moving average: Q
  192. ```