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.

main.py 5.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """
  16. NEZHA (NEural contextualiZed representation for CHinese lAnguage understanding) is the Chinese pretrained language model currently based on BERT developed by Huawei.
  17. 1. Prepare data
  18. Following the data preparation as in BERT, run command as below to get dataset for training:
  19. python ./create_pretraining_data.py \
  20. --input_file=./sample_text.txt \
  21. --output_file=./examples.tfrecord \
  22. --vocab_file=./your/path/vocab.txt \
  23. --do_lower_case=True \
  24. --max_seq_length=128 \
  25. --max_predictions_per_seq=20 \
  26. --masked_lm_prob=0.15 \
  27. --random_seed=12345 \
  28. --dupe_factor=5
  29. 2. Pretrain
  30. First, prepare the distributed training environment, then adjust configurations in config.py, finally run main.py.
  31. """
  32. import os
  33. import pytest
  34. import numpy as np
  35. from numpy import allclose
  36. from config import bert_cfg as cfg
  37. import mindspore.common.dtype as mstype
  38. import mindspore.dataset.engine.datasets as de
  39. import mindspore._c_dataengine as deMap
  40. from mindspore import context
  41. from mindspore.common.tensor import Tensor
  42. from mindspore.train.model import Model
  43. from mindspore.train.callback import Callback
  44. from mindspore.model_zoo.Bert_NEZHA import BertConfig, BertNetworkWithLoss, BertTrainOneStepCell
  45. from mindspore.nn.optim import Lamb
  46. from mindspore import log as logger
  47. _current_dir = os.path.dirname(os.path.realpath(__file__))
  48. DATA_DIR = [cfg.DATA_DIR]
  49. SCHEMA_DIR = cfg.SCHEMA_DIR
  50. def me_de_train_dataset(batch_size):
  51. """test me de train dataset"""
  52. # apply repeat operations
  53. repeat_count = cfg.epoch_size
  54. ds = de.StorageDataset(DATA_DIR, SCHEMA_DIR, columns_list=["input_ids", "input_mask", "segment_ids",
  55. "next_sentence_labels", "masked_lm_positions",
  56. "masked_lm_ids", "masked_lm_weights"])
  57. type_cast_op = deMap.TypeCastOp("int32")
  58. ds = ds.map(input_columns="masked_lm_ids", operations=type_cast_op)
  59. ds = ds.map(input_columns="masked_lm_positions", operations=type_cast_op)
  60. ds = ds.map(input_columns="next_sentence_labels", operations=type_cast_op)
  61. ds = ds.map(input_columns="segment_ids", operations=type_cast_op)
  62. ds = ds.map(input_columns="input_mask", operations=type_cast_op)
  63. ds = ds.map(input_columns="input_ids", operations=type_cast_op)
  64. # apply batch operations
  65. ds = ds.batch(batch_size, drop_remainder=True)
  66. ds = ds.repeat(repeat_count)
  67. return ds
  68. def weight_variable(shape):
  69. """weight variable"""
  70. np.random.seed(1)
  71. ones = np.random.uniform(-0.1, 0.1, size=shape).astype(np.float32)
  72. return Tensor(ones)
  73. class ModelCallback(Callback):
  74. def __init__(self):
  75. super(ModelCallback, self).__init__()
  76. self.loss_list = []
  77. def step_end(self, run_context):
  78. cb_params = run_context.original_args()
  79. self.loss_list.append(cb_params.net_outputs.asnumpy()[0])
  80. logger.info("epoch: {}, outputs are {}".format(cb_params.cur_epoch_num, str(cb_params.net_outputs)))
  81. def test_bert_tdt():
  82. """test bert tdt"""
  83. context.set_context(mode=context.GRAPH_MODE)
  84. context.set_context(device_target="Ascend")
  85. context.set_context(enable_task_sink=True)
  86. context.set_context(enable_loop_sink=True)
  87. context.set_context(enable_mem_reuse=True)
  88. parallel_callback = ModelCallback()
  89. ds = me_de_train_dataset(cfg.bert_config.batch_size)
  90. config = cfg.bert_config
  91. netwithloss = BertNetworkWithLoss(config, True)
  92. optimizer = Lamb(netwithloss.trainable_params(), decay_steps=cfg.decay_steps, start_learning_rate=cfg.start_learning_rate,
  93. end_learning_rate=cfg.end_learning_rate, power=cfg.power, warmup_steps=cfg.num_warmup_steps, decay_filter=lambda x: False)
  94. netwithgrads = BertTrainOneStepCell(netwithloss, optimizer=optimizer)
  95. netwithgrads.set_train(True)
  96. model = Model(netwithgrads)
  97. config_ck = CheckpointConfig(save_checkpoint_steps=cfg.save_checkpoint_steps, keep_checkpoint_max=cfg.keep_checkpoint_max)
  98. ckpoint_cb = ModelCheckpoint(prefix=cfg.checkpoint_prefix, config=config_ck)
  99. model.train(ds.get_repeat_count(), ds, callbacks=[parallel_callback, ckpoint_cb], dataset_sink_mode=False)
  100. if __name__ == '__main__':
  101. test_bert_tdt()