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.

finetune.py 7.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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. Bert finetune script.
  17. '''
  18. import os
  19. from src.utils import BertFinetuneCell, BertCLS, BertNER, BertSquad, BertSquadCell
  20. from src.finetune_config import cfg, bert_net_cfg, tag_to_index
  21. import mindspore.common.dtype as mstype
  22. from mindspore import context
  23. import mindspore.dataset as de
  24. import mindspore.dataset.transforms.c_transforms as C
  25. from mindspore.nn.wrap.loss_scale import DynamicLossScaleUpdateCell
  26. from mindspore.nn.optim import AdamWeightDecayDynamicLR, Lamb, Momentum
  27. from mindspore.train.model import Model
  28. from mindspore.train.callback import Callback
  29. from mindspore.train.callback import CheckpointConfig, ModelCheckpoint
  30. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  31. class LossCallBack(Callback):
  32. '''
  33. Monitor the loss in training.
  34. If the loss is NAN or INF, terminate training.
  35. Note:
  36. If per_print_times is 0, do not print loss.
  37. Args:
  38. per_print_times (int): Print loss every times. Default: 1.
  39. '''
  40. def __init__(self, per_print_times=1):
  41. super(LossCallBack, self).__init__()
  42. if not isinstance(per_print_times, int) or per_print_times < 0:
  43. raise ValueError("print_step must be in and >= 0.")
  44. self._per_print_times = per_print_times
  45. def step_end(self, run_context):
  46. cb_params = run_context.original_args()
  47. with open("./loss.log", "a+") as f:
  48. f.write("epoch: {}, step: {}, outputs are {}".format(cb_params.cur_epoch_num, cb_params.cur_step_num,
  49. str(cb_params.net_outputs)))
  50. f.write("\n")
  51. def get_dataset(batch_size=1, repeat_count=1, distribute_file=''):
  52. '''
  53. get dataset
  54. '''
  55. ds = de.TFRecordDataset([cfg.data_file], cfg.schema_file, columns_list=["input_ids", "input_mask",
  56. "segment_ids", "label_ids"])
  57. type_cast_op = C.TypeCast(mstype.int32)
  58. ds = ds.map(input_columns="segment_ids", operations=type_cast_op)
  59. ds = ds.map(input_columns="input_mask", operations=type_cast_op)
  60. ds = ds.map(input_columns="input_ids", operations=type_cast_op)
  61. ds = ds.map(input_columns="label_ids", operations=type_cast_op)
  62. ds = ds.repeat(repeat_count)
  63. # apply shuffle operation
  64. buffer_size = 960
  65. ds = ds.shuffle(buffer_size=buffer_size)
  66. # apply batch operations
  67. ds = ds.batch(batch_size, drop_remainder=True)
  68. return ds
  69. def get_squad_dataset(batch_size=1, repeat_count=1, distribute_file=''):
  70. '''
  71. get SQuAD dataset
  72. '''
  73. ds = de.TFRecordDataset([cfg.data_file], cfg.schema_file, columns_list=["input_ids", "input_mask", "segment_ids",
  74. "start_positions", "end_positions",
  75. "unique_ids", "is_impossible"])
  76. type_cast_op = C.TypeCast(mstype.int32)
  77. ds = ds.map(input_columns="segment_ids", operations=type_cast_op)
  78. ds = ds.map(input_columns="input_ids", operations=type_cast_op)
  79. ds = ds.map(input_columns="input_mask", operations=type_cast_op)
  80. ds = ds.map(input_columns="start_positions", operations=type_cast_op)
  81. ds = ds.map(input_columns="end_positions", operations=type_cast_op)
  82. ds = ds.repeat(repeat_count)
  83. buffer_size = 960
  84. ds = ds.shuffle(buffer_size=buffer_size)
  85. ds = ds.batch(batch_size, drop_remainder=True)
  86. return ds
  87. def test_train():
  88. '''
  89. finetune function
  90. '''
  91. devid = int(os.getenv('DEVICE_ID'))
  92. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend", device_id=devid)
  93. #BertCLSTrain for classification
  94. #BertNERTrain for sequence labeling
  95. if cfg.task == 'NER':
  96. if cfg.use_crf:
  97. netwithloss = BertNER(bert_net_cfg, True, num_labels=len(tag_to_index), use_crf=True,
  98. tag_to_index=tag_to_index, dropout_prob=0.1)
  99. else:
  100. netwithloss = BertNER(bert_net_cfg, True, num_labels=cfg.num_labels, dropout_prob=0.1)
  101. elif cfg.task == 'SQUAD':
  102. netwithloss = BertSquad(bert_net_cfg, True, 2, dropout_prob=0.1)
  103. else:
  104. netwithloss = BertCLS(bert_net_cfg, True, num_labels=cfg.num_labels, dropout_prob=0.1)
  105. if cfg.task == 'SQUAD':
  106. dataset = get_squad_dataset(bert_net_cfg.batch_size, cfg.epoch_num)
  107. else:
  108. dataset = get_dataset(bert_net_cfg.batch_size, cfg.epoch_num)
  109. # optimizer
  110. steps_per_epoch = dataset.get_dataset_size()
  111. if cfg.optimizer == 'AdamWeightDecayDynamicLR':
  112. optimizer = AdamWeightDecayDynamicLR(netwithloss.trainable_params(),
  113. decay_steps=steps_per_epoch * cfg.epoch_num,
  114. learning_rate=cfg.AdamWeightDecayDynamicLR.learning_rate,
  115. end_learning_rate=cfg.AdamWeightDecayDynamicLR.end_learning_rate,
  116. power=cfg.AdamWeightDecayDynamicLR.power,
  117. warmup_steps=int(steps_per_epoch * cfg.epoch_num * 0.1),
  118. weight_decay=cfg.AdamWeightDecayDynamicLR.weight_decay,
  119. eps=cfg.AdamWeightDecayDynamicLR.eps)
  120. elif cfg.optimizer == 'Lamb':
  121. optimizer = Lamb(netwithloss.trainable_params(), decay_steps=steps_per_epoch * cfg.epoch_num,
  122. start_learning_rate=cfg.Lamb.start_learning_rate, end_learning_rate=cfg.Lamb.end_learning_rate,
  123. power=cfg.Lamb.power, weight_decay=cfg.Lamb.weight_decay,
  124. warmup_steps=int(steps_per_epoch * cfg.epoch_num * 0.1), decay_filter=cfg.Lamb.decay_filter)
  125. elif cfg.optimizer == 'Momentum':
  126. optimizer = Momentum(netwithloss.trainable_params(), learning_rate=cfg.Momentum.learning_rate,
  127. momentum=cfg.Momentum.momentum)
  128. else:
  129. raise Exception("Optimizer not supported.")
  130. # load checkpoint into network
  131. ckpt_config = CheckpointConfig(save_checkpoint_steps=steps_per_epoch, keep_checkpoint_max=1)
  132. ckpoint_cb = ModelCheckpoint(prefix=cfg.ckpt_prefix, directory=cfg.ckpt_dir, config=ckpt_config)
  133. param_dict = load_checkpoint(cfg.pre_training_ckpt)
  134. load_param_into_net(netwithloss, param_dict)
  135. update_cell = DynamicLossScaleUpdateCell(loss_scale_value=2**32, scale_factor=2, scale_window=1000)
  136. if cfg.task == 'SQUAD':
  137. netwithgrads = BertSquadCell(netwithloss, optimizer=optimizer, scale_update_cell=update_cell)
  138. else:
  139. netwithgrads = BertFinetuneCell(netwithloss, optimizer=optimizer, scale_update_cell=update_cell)
  140. model = Model(netwithgrads)
  141. model.train(cfg.epoch_num, dataset, callbacks=[LossCallBack(), ckpoint_cb])
  142. if __name__ == "__main__":
  143. test_train()