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.

test_bert_train.py 8.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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. """Bert test."""
  16. # pylint: disable=missing-docstring, arguments-differ, W0612
  17. import os
  18. import mindspore.common.dtype as mstype
  19. import mindspore.context as context
  20. from mindspore import Tensor
  21. from mindspore.model_zoo.Bert_NEZHA import BertConfig, BertNetworkWithLoss, BertTrainOneStepCell, \
  22. BertTrainOneStepWithLossScaleCell
  23. from mindspore.nn.optim import AdamWeightDecayDynamicLR
  24. from mindspore.train.loss_scale_manager import DynamicLossScaleManager
  25. from ...dataset_mock import MindData
  26. from ...ops_common import nn, np, batch_tuple_tensor, build_construct_graph
  27. _current_dir = os.path.dirname(os.path.realpath(__file__)) + "/../python/test_data"
  28. context.set_context(mode=context.GRAPH_MODE)
  29. def get_dataset(batch_size=1):
  30. dataset_types = (np.int32, np.int32, np.int32, np.int32, np.int32, np.int32, np.int32)
  31. dataset_shapes = ((batch_size, 128), (batch_size, 128), (batch_size, 128), (batch_size, 1), \
  32. (batch_size, 20), (batch_size, 20), (batch_size, 20))
  33. dataset = MindData(size=2, batch_size=batch_size,
  34. np_types=dataset_types,
  35. output_shapes=dataset_shapes,
  36. input_indexs=(0, 1))
  37. return dataset
  38. def load_test_data(batch_size=1):
  39. dataset = get_dataset(batch_size)
  40. ret = dataset.next()
  41. ret = batch_tuple_tensor(ret, batch_size)
  42. return ret
  43. def get_config(version='base', batch_size=1):
  44. """
  45. get_config definition
  46. """
  47. if version == 'base':
  48. return BertConfig(
  49. batch_size=batch_size,
  50. seq_length=128,
  51. vocab_size=21128,
  52. hidden_size=768,
  53. num_hidden_layers=12,
  54. num_attention_heads=12,
  55. intermediate_size=3072,
  56. hidden_act="gelu",
  57. hidden_dropout_prob=0.1,
  58. attention_probs_dropout_prob=0.1,
  59. max_position_embeddings=512,
  60. type_vocab_size=2,
  61. initializer_range=0.02,
  62. use_relative_positions=True,
  63. input_mask_from_dataset=True,
  64. token_type_ids_from_dataset=True,
  65. dtype=mstype.float32,
  66. compute_type=mstype.float32)
  67. if version == 'large':
  68. return BertConfig(
  69. batch_size=batch_size,
  70. seq_length=128,
  71. vocab_size=21128,
  72. hidden_size=1024,
  73. num_hidden_layers=24,
  74. num_attention_heads=16,
  75. intermediate_size=4096,
  76. hidden_act="gelu",
  77. hidden_dropout_prob=0.1,
  78. attention_probs_dropout_prob=0.1,
  79. max_position_embeddings=512,
  80. type_vocab_size=2,
  81. initializer_range=0.02,
  82. use_relative_positions=True,
  83. input_mask_from_dataset=True,
  84. token_type_ids_from_dataset=True,
  85. dtype=mstype.float32,
  86. compute_type=mstype.float32)
  87. return BertConfig(batch_size=batch_size)
  88. def test_bert_train():
  89. """
  90. the main function
  91. """
  92. class ModelBert(nn.Cell):
  93. """
  94. ModelBert definition
  95. """
  96. def __init__(self, network, optimizer=None):
  97. super(ModelBert, self).__init__()
  98. self.optimizer = optimizer
  99. self.train_network = BertTrainOneStepCell(network, self.optimizer)
  100. self.train_network.set_train()
  101. def construct(self, arg0, arg1, arg2, arg3, arg4, arg5, arg6):
  102. return self.train_network(arg0, arg1, arg2, arg3, arg4, arg5, arg6)
  103. version = os.getenv('VERSION', 'large')
  104. batch_size = int(os.getenv('BATCH_SIZE', '1'))
  105. inputs = load_test_data(batch_size)
  106. config = get_config(version=version, batch_size=batch_size)
  107. netwithloss = BertNetworkWithLoss(config, True)
  108. optimizer = AdamWeightDecayDynamicLR(netwithloss.trainable_params(), 10)
  109. net = ModelBert(netwithloss, optimizer=optimizer)
  110. net.set_train()
  111. build_construct_graph(net, *inputs, execute=False)
  112. def test_bert_withlossscale_train():
  113. class ModelBert(nn.Cell):
  114. def __init__(self, network, optimizer=None):
  115. super(ModelBert, self).__init__()
  116. self.optimizer = optimizer
  117. self.train_network = BertTrainOneStepWithLossScaleCell(network, self.optimizer)
  118. self.train_network.set_train()
  119. def construct(self, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7):
  120. return self.train_network(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7)
  121. version = os.getenv('VERSION', 'base')
  122. batch_size = int(os.getenv('BATCH_SIZE', '1'))
  123. scaling_sens = Tensor(np.ones([1]).astype(np.float32))
  124. inputs = load_test_data(batch_size) + (scaling_sens,)
  125. config = get_config(version=version, batch_size=batch_size)
  126. netwithloss = BertNetworkWithLoss(config, True)
  127. optimizer = AdamWeightDecayDynamicLR(netwithloss.trainable_params(), 10)
  128. net = ModelBert(netwithloss, optimizer=optimizer)
  129. net.set_train()
  130. build_construct_graph(net, *inputs, execute=True)
  131. def bert_withlossscale_manager_train():
  132. class ModelBert(nn.Cell):
  133. def __init__(self, network, optimizer=None):
  134. super(ModelBert, self).__init__()
  135. self.optimizer = optimizer
  136. manager = DynamicLossScaleManager()
  137. update_cell = LossScaleUpdateCell(manager)
  138. self.train_network = BertTrainOneStepWithLossScaleCell(network, self.optimizer,
  139. scale_update_cell=update_cell)
  140. self.train_network.set_train()
  141. def construct(self, arg0, arg1, arg2, arg3, arg4, arg5, arg6):
  142. return self.train_network(arg0, arg1, arg2, arg3, arg4, arg5, arg6)
  143. version = os.getenv('VERSION', 'base')
  144. batch_size = int(os.getenv('BATCH_SIZE', '1'))
  145. inputs = load_test_data(batch_size)
  146. config = get_config(version=version, batch_size=batch_size)
  147. netwithloss = BertNetworkWithLoss(config, True)
  148. optimizer = AdamWeightDecayDynamicLR(netwithloss.trainable_params(), 10)
  149. net = ModelBert(netwithloss, optimizer=optimizer)
  150. net.set_train()
  151. build_construct_graph(net, *inputs, execute=True)
  152. def bert_withlossscale_manager_train_feed():
  153. class ModelBert(nn.Cell):
  154. def __init__(self, network, optimizer=None):
  155. super(ModelBert, self).__init__()
  156. self.optimizer = optimizer
  157. manager = DynamicLossScaleManager()
  158. update_cell = LossScaleUpdateCell(manager)
  159. self.train_network = BertTrainOneStepWithLossScaleCell(network, self.optimizer,
  160. scale_update_cell=update_cell)
  161. self.train_network.set_train()
  162. def construct(self, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7):
  163. return self.train_network(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7)
  164. version = os.getenv('VERSION', 'base')
  165. batch_size = int(os.getenv('BATCH_SIZE', '1'))
  166. scaling_sens = Tensor(np.ones([1]).astype(np.float32))
  167. inputs = load_test_data(batch_size) + (scaling_sens,)
  168. config = get_config(version=version, batch_size=batch_size)
  169. netwithloss = BertNetworkWithLoss(config, True)
  170. optimizer = AdamWeightDecayDynamicLR(netwithloss.trainable_params(), 10)
  171. net = ModelBert(netwithloss, optimizer=optimizer)
  172. net.set_train()
  173. build_construct_graph(net, *inputs, execute=True)