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_mix_precision.py 7.6 kB

4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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. """Test network turn on mix_precision."""
  15. import os
  16. import re
  17. import pytest
  18. import numpy as np
  19. from mindspore.common import dtype
  20. from mindspore import nn
  21. from mindspore import ops
  22. from mindspore import amp
  23. from mindspore import Tensor
  24. from mindspore import context
  25. from mindspore.train.loss_scale_manager import FixedLossScaleManager
  26. from mindspore.train.model import Model
  27. from utils import FakeData
  28. from utils import allclose_nparray
  29. from utils import FakeDataInitMode
  30. from utils import find_newest_validateir_file
  31. from utils import clean_all_ir_files
  32. def read_validateir_file(path_folder):
  33. filename = find_newest_validateir_file(path_folder)
  34. with open(os.path.join(filename), 'r') as f:
  35. contend = f.read()
  36. return contend
  37. class Net(nn.Cell):
  38. def __init__(self, in_c, out_c):
  39. super().__init__()
  40. self.relu = nn.ReLU()
  41. self.bn1 = nn.BatchNorm2d(num_features=in_c,
  42. gamma_init='ones',
  43. beta_init='zeros',
  44. moving_mean_init='zeros',
  45. moving_var_init='ones')
  46. self.bn2 = nn.BatchNorm2d(num_features=out_c,
  47. gamma_init='ones',
  48. beta_init='zeros',
  49. moving_mean_init='zeros',
  50. moving_var_init='ones')
  51. self.conv = nn.Conv2d(in_channels=in_c,
  52. out_channels=out_c,
  53. kernel_size=3,
  54. stride=1,
  55. has_bias=True,
  56. pad_mode='same',
  57. weight_init='ones',
  58. bias_init='ones')
  59. self.mean = ops.ReduceMean(keep_dims=False)
  60. def construct(self, x):
  61. x = self.relu(x)
  62. x = self.bn1(x)
  63. x = self.conv(x)
  64. x = self.bn2(x)
  65. x = self.relu(x)
  66. x = self.mean(x, (2, 3))
  67. return x
  68. @pytest.mark.level0
  69. @pytest.mark.platform_arm_ascend_training
  70. @pytest.mark.platform_x86_ascend_training
  71. @pytest.mark.platform_x86_gpu_training
  72. @pytest.mark.env_onecard
  73. def test_sit_auto_mix_precision_train_o3():
  74. input_data = np.random.randn(32, 3, 224, 224).astype(np.float64)
  75. label_data = np.random.randn(32, 10).astype(np.float32)
  76. # graph mode
  77. context.set_context(mode=context.GRAPH_MODE)
  78. net = Net(3, 10)
  79. opt = nn.Momentum(params=net.trainable_params(), learning_rate=0.001, momentum=0.0009, weight_decay=0.001,
  80. loss_scale=0.0001)
  81. loss = nn.SoftmaxCrossEntropyWithLogits(sparse=False)
  82. train_network = amp.build_train_network(net, opt, loss, level="O3",
  83. loss_scale_manager=FixedLossScaleManager(drop_overflow_update=False))
  84. out = train_network(Tensor(input_data), Tensor(label_data))
  85. # pynative mode
  86. context.set_context(mode=context.PYNATIVE_MODE)
  87. net_pynative = Net(3, 10)
  88. opt_pynative = nn.Momentum(params=net_pynative.trainable_params(), learning_rate=0.001, momentum=0.0009,
  89. weight_decay=0.001,
  90. loss_scale=0.0001)
  91. loss_pynative = nn.SoftmaxCrossEntropyWithLogits(sparse=False)
  92. train_network_pynative = amp.build_train_network(net_pynative, opt_pynative, loss_pynative, level="O3",
  93. loss_scale_manager=FixedLossScaleManager(
  94. drop_overflow_update=False))
  95. out_pynative = train_network_pynative(Tensor(input_data), Tensor(label_data))
  96. assert np.allclose(out.asnumpy(), out_pynative.asnumpy(), 0.001, 0.001)
  97. @pytest.mark.level0
  98. @pytest.mark.platform_arm_ascend_training
  99. @pytest.mark.platform_x86_ascend_training
  100. @pytest.mark.env_onecard
  101. def test_sit_auto_mix_precision_model_o0():
  102. input_data = np.random.randn(32, 3, 224, 224).astype(np.float32)
  103. dataset1 = FakeData(size=32,
  104. batch_size=32,
  105. image_size=(3, 224, 224),
  106. num_classes=10,
  107. fakedata_mode=FakeDataInitMode.OnesInit)
  108. dataset1.set_label_data_type(np.float16)
  109. # graph mode
  110. context.set_context(mode=context.GRAPH_MODE)
  111. context.set_context(save_graphs=True, save_graphs_path='./test_amp_o0')
  112. net = Net(3, 10)
  113. net.to_float(dtype.float16)
  114. opt = nn.Momentum(params=net.trainable_params(), learning_rate=0.001, momentum=0.0009)
  115. loss = nn.SoftmaxCrossEntropyWithLogits(sparse=False)
  116. model = Model(net, loss, opt, amp_level="O0")
  117. model.train(1, dataset1, dataset_sink_mode=False)
  118. contend = read_validateir_file('./test_amp_o0')
  119. castnum = re.findall("Cast", contend)
  120. assert len(castnum) == 5
  121. clean_all_ir_files('./test_amp_o0')
  122. model.predict(Tensor(input_data))
  123. contend = read_validateir_file('./test_amp_o0')
  124. castnum = re.findall("Cast", contend)
  125. assert len(castnum) == 11
  126. clean_all_ir_files('./test_amp_o0')
  127. @pytest.mark.level0
  128. @pytest.mark.platform_arm_ascend_training
  129. @pytest.mark.platform_x86_ascend_training
  130. @pytest.mark.platform_x86_gpu_training
  131. @pytest.mark.env_onecard
  132. def test_sit_auto_mix_precision_model_o2():
  133. input_data = np.random.randn(32, 3, 224, 224).astype(np.float32)
  134. dataset1 = FakeData(size=32,
  135. batch_size=32,
  136. image_size=(3, 224, 224),
  137. num_classes=10,
  138. fakedata_mode=FakeDataInitMode.OnesInit)
  139. dataset2 = FakeData(size=32,
  140. batch_size=32,
  141. image_size=(3, 224, 224),
  142. num_classes=10,
  143. fakedata_mode=FakeDataInitMode.OnesInit)
  144. # graph mode
  145. context.set_context(mode=context.GRAPH_MODE)
  146. context.set_context(save_graphs=True, save_graphs_path='./test_amp_o2')
  147. net = Net(3, 10)
  148. opt = nn.Momentum(params=net.trainable_params(), learning_rate=0.001, momentum=0.0009)
  149. loss = nn.SoftmaxCrossEntropyWithLogits(sparse=False)
  150. model = Model(net, loss, opt, amp_level="O2")
  151. model.train(1, dataset1, dataset_sink_mode=False)
  152. contend = read_validateir_file('./test_amp_o2')
  153. castnum = re.findall("Cast", contend)
  154. assert len(castnum) == 14
  155. clean_all_ir_files('./test_amp_o2')
  156. out_graph = model.predict(Tensor(input_data))
  157. # pynative mode
  158. context.set_context(mode=context.PYNATIVE_MODE)
  159. net_pynative = Net(3, 10)
  160. opt_pynative = nn.Momentum(params=net_pynative.trainable_params(), learning_rate=0.001, momentum=0.0009)
  161. loss_pynative = nn.SoftmaxCrossEntropyWithLogits(sparse=False)
  162. model_pynative = Model(net_pynative, loss_pynative, opt_pynative, amp_level="O2")
  163. model_pynative.train(1, dataset2, dataset_sink_mode=False)
  164. out_pynative = model_pynative.predict(Tensor(input_data))
  165. allclose_nparray(out_graph.asnumpy(), out_pynative.asnumpy(), 0.001, 0.001)