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_amp.py 5.8 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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. """ auto mixed precision """
  16. import numpy as np
  17. import pytest
  18. import mindspore.context as context
  19. from mindspore import Tensor
  20. from mindspore import amp
  21. from mindspore import nn
  22. from mindspore.train import Model, ParallelMode
  23. from mindspore.common import dtype as mstype
  24. from mindspore.model_zoo.resnet import resnet50
  25. from ....dataset_mock import MindData
  26. from mindspore.parallel._auto_parallel_context import auto_parallel_context
  27. from mindspore.communication.management import init
  28. def setup_module(module):
  29. _ = module
  30. context.set_context(mode=context.GRAPH_MODE)
  31. class Net(nn.Cell):
  32. def __init__(self, in_features, out_features):
  33. super(Net, self).__init__()
  34. self.dense = nn.Dense(in_features, out_features)
  35. self.loss = nn.MSELoss()
  36. def construct(self, input_x, label):
  37. output = self.dense(input_x)
  38. loss = self.loss(output, label)
  39. return loss
  40. class NetNoLoss(nn.Cell):
  41. def __init__(self, in_features, out_features):
  42. super(NetNoLoss, self).__init__()
  43. self.dense = nn.Dense(in_features, out_features)
  44. def construct(self, input_x):
  45. return self.dense(input_x)
  46. def test_amp_o0():
  47. inputs = Tensor(np.ones([16, 16]).astype(np.float32))
  48. label = Tensor(np.zeros([16, 16]).astype(np.float32))
  49. net = Net(16, 16)
  50. optimizer = nn.Momentum(net.trainable_params(), learning_rate=0.1, momentum=0.9)
  51. train_network = amp.build_train_network(net, optimizer, level="O0")
  52. _ = train_network(inputs, label)
  53. def test_amp_o2():
  54. inputs = Tensor(np.ones([16, 16]).astype(np.float32))
  55. label = Tensor(np.zeros([16, 16]).astype(np.float32))
  56. net = Net(16, 16)
  57. optimizer = nn.Momentum(net.trainable_params(), learning_rate=0.1, momentum=0.9)
  58. train_network = amp.build_train_network(net, optimizer, level="O2")
  59. _ = train_network(inputs, label)
  60. def test_amp_o2_loss():
  61. inputs = Tensor(np.ones([16, 16]).astype(np.float32))
  62. label = Tensor(np.zeros([16, 16]).astype(np.float32))
  63. net = NetNoLoss(16, 16)
  64. loss = nn.MSELoss()
  65. optimizer = nn.Momentum(net.trainable_params(), learning_rate=0.1, momentum=0.9)
  66. train_network = amp.build_train_network(net, optimizer, loss, level="O2")
  67. _ = train_network(inputs, label)
  68. def test_amp_o0_loss():
  69. inputs = Tensor(np.ones([16, 16]).astype(np.float32))
  70. label = Tensor(np.zeros([16, 16]).astype(np.float32))
  71. net = NetNoLoss(16, 16)
  72. loss = nn.MSELoss()
  73. optimizer = nn.Momentum(net.trainable_params(), learning_rate=0.1, momentum=0.9)
  74. train_network = amp.build_train_network(net, optimizer, loss)
  75. _ = train_network(inputs, label)
  76. class MindDataSet(MindData):
  77. def __init__(self, dataset_types, dataset_shapes):
  78. super(MindDataSet, self).__init__(size=2, batch_size=32,
  79. np_types=dataset_types,
  80. output_shapes=dataset_shapes,
  81. input_indexs=(0, 1))
  82. def __next__(self):
  83. if self._size < self._iter_num:
  84. raise StopIteration
  85. self._iter_num += 1
  86. lst = []
  87. for shape_, type_ in zip(self._output_shapes, self._np_types):
  88. lst.append(Tensor(np.ones(shape_).astype(type_)))
  89. return tuple(lst)
  90. def test_compile_model_train_O0():
  91. dataset_types = (np.float32, np.float32)
  92. dataset_shapes = ((16, 16), (16, 16))
  93. dataset = MindDataSet(dataset_types, dataset_shapes)
  94. net = NetNoLoss(16, 16)
  95. loss = nn.MSELoss()
  96. optimizer = nn.Momentum(net.trainable_params(), learning_rate=0.1, momentum=0.9)
  97. model = Model(net, loss_fn=loss, optimizer=optimizer, metrics={"acc"}, amp_level="O0")
  98. model.train(2, dataset, dataset_sink_mode=False)
  99. with pytest.raises(ValueError):
  100. # not actual run, the metrics step will fail, check if compile ok.
  101. model.eval(dataset)
  102. def test_compile_model_train_O2():
  103. dataset_types = (np.float32, np.float32)
  104. dataset_shapes = ((16, 16), (16, 16))
  105. dataset = MindDataSet(dataset_types, dataset_shapes)
  106. net = NetNoLoss(16, 16)
  107. loss = nn.MSELoss()
  108. optimizer = nn.Momentum(net.trainable_params(), learning_rate=0.1, momentum=0.9)
  109. model = Model(net, loss_fn=loss, optimizer=optimizer, metrics={"acc"}, amp_level="O2")
  110. model.train(2, dataset, dataset_sink_mode=False)
  111. with pytest.raises(ValueError):
  112. # not actual run, the metrics step will fail, check if compile ok.
  113. model.eval(dataset)
  114. def test_compile_model_train_O2_parallel():
  115. dataset_types = (np.float32, np.float32)
  116. dataset_shapes = ((16, 16), (16, 16))
  117. dataset = MindDataSet(dataset_types, dataset_shapes)
  118. net = NetNoLoss(16, 16)
  119. loss = nn.MSELoss()
  120. optimizer = nn.Momentum(net.trainable_params(), 0.1, 0.9, 0.00004, 1024.0)
  121. context.set_auto_parallel_context(
  122. global_rank=0, device_num=8,
  123. mirror_mean=True, parameter_broadcast=True,
  124. parallel_mode=ParallelMode.DATA_PARALLEL)
  125. init()
  126. model = Model(net, loss_fn=loss, optimizer=optimizer, metrics={"acc"}, amp_level="O2")
  127. model.train(2, dataset, dataset_sink_mode=False)