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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. # BERT Example
  2. ## Description
  3. This example implements pre-training, fine-tuning and evaluation of [BERT-base](https://github.com/google-research/bert)(the base version of BERT model) and [BERT-NEZHA](https://github.com/huawei-noah/Pretrained-Language-Model)(a Chinese pretrained language model developed by Huawei, which introduced a improvement of Functional Relative Positional Encoding as an effective positional encoding scheme).
  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. > Notes:
  9. If you are running a fine-tuning or evaluation task, prepare a checkpoint from pre-train.
  10. ## Running the Example
  11. ### Pre-Training
  12. - 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.
  13. - Run `run_standalone_pretrain.sh` for non-distributed pre-training of BERT-base and BERT-NEZHA model.
  14. ``` bash
  15. sh scripts/run_standalone_pretrain.sh DEVICE_ID EPOCH_SIZE DATA_DIR SCHEMA_DIR
  16. ```
  17. - Run `run_distribute_pretrain.sh` for distributed pre-training of BERT-base and BERT-NEZHA model.
  18. ``` bash
  19. sh scripts/run_distribute_pretrain.sh DEVICE_NUM EPOCH_SIZE DATA_DIR SCHEMA_DIR MINDSPORE_HCCL_CONFIG_PATH
  20. ```
  21. ### Fine-Tuning and Evaluation
  22. - Set bert network config and optimizer hyperparameters in `finetune_eval_config.py`.
  23. - Set task related hyperparameters in scripts/run_XXX.sh.
  24. - Run `bash scripts/run_XXX.py` for fine-tuning of BERT-base and BERT-NEZHA model.
  25. ```bash
  26. bash scripts/run_XXX.sh
  27. ```
  28. ## Usage
  29. ### Pre-Training
  30. ```
  31. usage: run_pretrain.py [--distribute DISTRIBUTE] [--epoch_size N] [----device_num N] [--device_id N]
  32. [--enable_save_ckpt ENABLE_SAVE_CKPT]
  33. [--enable_lossscale ENABLE_LOSSSCALE] [--do_shuffle DO_SHUFFLE]
  34. [--enable_data_sink ENABLE_DATA_SINK] [--data_sink_steps N] [--checkpoint_path CHECKPOINT_PATH]
  35. [--save_checkpoint_steps N] [--save_checkpoint_num N]
  36. [--data_dir DATA_DIR] [--schema_dir SCHEMA_DIR]
  37. options:
  38. --distribute pre_training by serveral devices: "true"(training by more than 1 device) | "false", default is "false"
  39. --epoch_size epoch size: N, default is 1
  40. --device_num number of used devices: N, default is 1
  41. --device_id device id: N, default is 0
  42. --enable_save_ckpt enable save checkpoint: "true" | "false", default is "true"
  43. --enable_lossscale enable lossscale: "true" | "false", default is "true"
  44. --do_shuffle enable shuffle: "true" | "false", default is "true"
  45. --enable_data_sink enable data sink: "true" | "false", default is "true"
  46. --data_sink_steps set data sink steps: N, default is 1
  47. --checkpoint_path path to save checkpoint files: PATH, default is ""
  48. --save_checkpoint_steps steps for saving checkpoint files: N, default is 1000
  49. --save_checkpoint_num number for saving checkpoint files: N, default is 1
  50. --data_dir path to dataset directory: PATH, default is ""
  51. --schema_dir path to schema.json file, PATH, default is ""
  52. ```
  53. ## Options and Parameters
  54. It contains of parameters of BERT model and options for training, which is set in file `config.py`, `finetune_config.py` and `evaluation_config.py` respectively.
  55. ### Options:
  56. ```
  57. config.py:
  58. bert_network version of BERT model: base | nezha, default is base
  59. loss_scale_value initial value of loss scale: N, default is 2^32
  60. scale_factor factor used to update loss scale: N, default is 2
  61. scale_window steps for once updatation of loss scale: N, default is 1000
  62. optimizer optimizer used in the network: AdamWerigtDecayDynamicLR | Lamb | Momentum, default is "Lamb"
  63. scripts/run_ner.sh:
  64. device_target targeted device to run task: Ascend | GPU
  65. do_train whether to run training on training set: true | false
  66. do_eval whether to run eval on dev set: true | false
  67. assessment_method assessment method to do evaluation: f1 | clue_benchmark
  68. use_crf whether to use crf to calculate loss: true | false
  69. device_id device id to run task
  70. epoch_num total number of training epochs to perform
  71. num_class number of classes to do labeling
  72. vocab_file_path the vocabulary file that the BERT model was trained on
  73. label2id_file_path label to id json file
  74. save_finetune_checkpoint_path path to save generated finetuning checkpoint
  75. load_pretrain_checkpoint_path initial checkpoint (usually from a pre-trained BERT model)
  76. load_finetune_checkpoint_path give a finetuning checkpoint path if only do eval
  77. train_data_file_path ner tfrecord for training. E.g., train.tfrecord
  78. 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
  79. schema_file_path path to datafile schema file
  80. scripts/run_squad.sh:
  81. device_target targeted device to run task: Ascend | GPU
  82. do_train whether to run training on training set: true | false
  83. do_eval whether to run eval on dev set: true | false
  84. device_id device id to run task
  85. epoch_num total number of training epochs to perform
  86. num_class number of classes to classify, usually 2 for squad task
  87. vocab_file_path the vocabulary file that the BERT model was trained on
  88. eval_json_path path to squad dev json file
  89. save_finetune_checkpoint_path path to save generated finetuning checkpoint
  90. load_pretrain_checkpoint_path initial checkpoint (usually from a pre-trained BERT model)
  91. load_finetune_checkpoint_path give a finetuning checkpoint path if only do eval
  92. train_data_file_path squad tfrecord for training. E.g., train1.1.tfrecord
  93. eval_data_file_path squad tfrecord for predictions. E.g., dev1.1.tfrecord
  94. schema_file_path path to datafile schema file
  95. scripts/run_classifier.sh
  96. device_target targeted device to run task: Ascend | GPU
  97. do_train whether to run training on training set: true | false
  98. do_eval whether to run eval on dev set: true | false
  99. assessment_method assessment method to do evaluation: accuracy | f1 | mcc | spearman_correlation
  100. device_id device id to run task
  101. epoch_num total number of training epochs to perform
  102. num_class number of classes to do labeling
  103. save_finetune_checkpoint_path path to save generated finetuning checkpoint
  104. load_pretrain_checkpoint_path initial checkpoint (usually from a pre-trained BERT model)
  105. load_finetune_checkpoint_path give a finetuning checkpoint path if only do eval
  106. train_data_file_path tfrecord for training. E.g., train.tfrecord
  107. eval_data_file_path tfrecord for predictions. E.g., dev.tfrecord
  108. schema_file_path path to datafile schema file
  109. ```
  110. ### Parameters:
  111. ```
  112. Parameters for dataset and network (Pre-Training/Fine-Tuning/Evaluation):
  113. batch_size batch size of input dataset: N, default is 16
  114. seq_length length of input sequence: N, default is 128
  115. vocab_size size of each embedding vector: N, must be consistant with the dataset you use. Default is 21136
  116. hidden_size size of bert encoder layers: N, default is 768
  117. num_hidden_layers number of hidden layers: N, default is 12
  118. num_attention_heads number of attention heads: N, default is 12
  119. intermediate_size size of intermediate layer: N, default is 3072
  120. hidden_act activation function used: ACTIVATION, default is "gelu"
  121. hidden_dropout_prob dropout probability for BertOutput: Q, default is 0.1
  122. attention_probs_dropout_prob dropout probability for BertAttention: Q, default is 0.1
  123. max_position_embeddings maximum length of sequences: N, default is 512
  124. type_vocab_size size of token type vocab: N, default is 16
  125. initializer_range initialization value of TruncatedNormal: Q, default is 0.02
  126. use_relative_positions use relative positions or not: True | False, default is False
  127. input_mask_from_dataset use the input mask loaded form dataset or not: True | False, default is True
  128. token_type_ids_from_dataset use the token type ids loaded from dataset or not: True | False, default is True
  129. dtype data type of input: mstype.float16 | mstype.float32, default is mstype.float32
  130. compute_type compute type in BertTransformer: mstype.float16 | mstype.float32, default is mstype.float16
  131. Parameters for optimizer:
  132. AdamWeightDecayDynamicLR:
  133. decay_steps steps of the learning rate decay: N
  134. learning_rate value of learning rate: Q
  135. end_learning_rate value of end learning rate: Q, must be positive
  136. power power: Q
  137. warmup_steps steps of the learning rate warm up: N
  138. weight_decay weight decay: Q
  139. eps term added to the denominator to improve numerical stability: Q
  140. Lamb:
  141. decay_steps steps of the learning rate decay: N
  142. learning_rate value of learning rate: Q
  143. end_learning_rate value of end learning rate: Q
  144. power power: Q
  145. warmup_steps steps of the learning rate warm up: N
  146. weight_decay weight decay: Q
  147. Momentum:
  148. learning_rate value of learning rate: Q
  149. momentum momentum for the moving average: Q
  150. ```