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.

train.py 4.6 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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 train.py.
  31. """
  32. import os
  33. import pytest
  34. import numpy as np
  35. from numpy import allclose
  36. from config import bert_train_cfg, bert_net_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, ModelCheckpoint, CheckpointConfig, LossMonitor
  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. def create_train_dataset(batch_size):
  49. """create train dataset"""
  50. # apply repeat operations
  51. repeat_count = bert_train_cfg.epoch_size
  52. ds = de.StorageDataset([bert_train_cfg.DATA_DIR], bert_train_cfg.SCHEMA_DIR, columns_list=["input_ids", "input_mask", "segment_ids",
  53. "next_sentence_labels", "masked_lm_positions",
  54. "masked_lm_ids", "masked_lm_weights"])
  55. type_cast_op = deMap.TypeCastOp("int32")
  56. ds = ds.map(input_columns="masked_lm_ids", operations=type_cast_op)
  57. ds = ds.map(input_columns="masked_lm_positions", operations=type_cast_op)
  58. ds = ds.map(input_columns="next_sentence_labels", operations=type_cast_op)
  59. ds = ds.map(input_columns="segment_ids", operations=type_cast_op)
  60. ds = ds.map(input_columns="input_mask", operations=type_cast_op)
  61. ds = ds.map(input_columns="input_ids", operations=type_cast_op)
  62. # apply batch operations
  63. ds = ds.batch(batch_size, drop_remainder=True)
  64. ds = ds.repeat(repeat_count)
  65. return ds
  66. def weight_variable(shape):
  67. """weight variable"""
  68. np.random.seed(1)
  69. ones = np.random.uniform(-0.1, 0.1, size=shape).astype(np.float32)
  70. return Tensor(ones)
  71. def train_bert():
  72. """train bert"""
  73. context.set_context(mode=context.GRAPH_MODE)
  74. context.set_context(device_target="Ascend")
  75. context.set_context(enable_task_sink=True)
  76. context.set_context(enable_loop_sink=True)
  77. context.set_context(enable_mem_reuse=True)
  78. ds = create_train_dataset(bert_net_cfg.batch_size)
  79. netwithloss = BertNetworkWithLoss(bert_net_cfg, True)
  80. optimizer = Lamb(netwithloss.trainable_params(), decay_steps=bert_train_cfg.decay_steps,
  81. start_learning_rate=bert_train_cfg.start_learning_rate, end_learning_rate=bert_train_cfg.end_learning_rate,
  82. power=bert_train_cfg.power, warmup_steps=bert_train_cfg.num_warmup_steps, decay_filter=lambda x: False)
  83. netwithgrads = BertTrainOneStepCell(netwithloss, optimizer=optimizer)
  84. netwithgrads.set_train(True)
  85. model = Model(netwithgrads)
  86. config_ck = CheckpointConfig(save_checkpoint_steps=bert_train_cfg.save_checkpoint_steps,
  87. keep_checkpoint_max=bert_train_cfg.keep_checkpoint_max)
  88. ckpoint_cb = ModelCheckpoint(prefix=bert_train_cfg.checkpoint_prefix, config=config_ck)
  89. model.train(ds.get_repeat_count(), ds, callbacks=[LossMonitor(), ckpoint_cb], dataset_sink_mode=False)
  90. if __name__ == '__main__':
  91. train_bert()

MindSpore is a new open source deep learning training/inference framework that could be used for mobile, edge and cloud scenarios.