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_loss_scale.py 7.3 kB

5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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. import numpy as np
  15. import mindspore as ms
  16. from mindspore import Tensor
  17. from mindspore import context
  18. from mindspore.common.parameter import Parameter
  19. from mindspore.common import dtype as mstype
  20. from mindspore.ops import composite as C
  21. from mindspore.ops import operations as P
  22. from mindspore.ops import functional as F
  23. from mindspore.nn.optim.momentum import Momentum
  24. from mindspore.nn.wrap.loss_scale import DynamicLossScaleUpdateCell
  25. import mindspore.nn as nn
  26. from mindspore.train import Model
  27. from mindspore.context import ParallelMode
  28. from tests.dataset_mock import MindData
  29. GRADIENT_CLIP_TYPE = 1
  30. GRADIENT_CLIP_VALUE = 1.0
  31. clip_grad = C.MultitypeFuncGraph("clip_grad")
  32. grad_scale = C.MultitypeFuncGraph("grad_scale")
  33. reciprocal = P.Reciprocal()
  34. @grad_scale.register("Tensor", "Tensor")
  35. def tensor_grad_scale(scale, grad):
  36. return grad * reciprocal(scale)
  37. update_cell = DynamicLossScaleUpdateCell(loss_scale_value=65536, scale_factor=2, scale_window=1000)
  38. @clip_grad.register("Number", "Number", "Tensor")
  39. def _clip_grad(clip_type, clip_value, grad):
  40. dt = F.dtype(grad)
  41. if clip_type == 0:
  42. new_grad = C.clip_by_value(grad, F.cast(F.tuple_to_array((-clip_value,)), dt),
  43. F.cast(F.tuple_to_array((clip_value,)), dt))
  44. else:
  45. new_grad = nn.ClipByNorm()(grad, F.cast(F.tuple_to_array((clip_value,)), dt))
  46. return new_grad
  47. class TrainOneStepWithLossScaleCell(nn.Cell):
  48. def __init__(self, network, optimizer, scale_update_cell=None):
  49. super(TrainOneStepWithLossScaleCell, self).__init__(auto_prefix=False)
  50. self.network = network
  51. self.weights = optimizer.parameters
  52. self.optimizer = optimizer
  53. self.grad = C.GradOperation(get_by_list=True,
  54. sens_param=True)
  55. self.reducer_flag = False
  56. self.grad_reducer = F.identity
  57. self.cast = P.Cast()
  58. self.alloc_status = P.NPUAllocFloatStatus()
  59. self.get_status = P.NPUGetFloatStatus()
  60. self.clear_status = P.NPUClearFloatStatus()
  61. self.reduce_sum = P.ReduceSum(keep_dims=False)
  62. self.base = Tensor(1, mstype.float32)
  63. self.less_equal = P.LessEqual()
  64. self.hyper_map = C.HyperMap()
  65. self.loss_scale = None
  66. self.loss_scaling_manager = scale_update_cell
  67. if scale_update_cell:
  68. self.loss_scale = Parameter(Tensor(scale_update_cell.get_loss_scale(), dtype=mstype.float32),
  69. name="loss_scale")
  70. def construct(self, x, sens=None):
  71. """Defines the computation performed."""
  72. weights = self.weights
  73. loss = self.network(x)
  74. if sens is None:
  75. scaling_sens = self.loss_scale
  76. else:
  77. scaling_sens = sens
  78. # alloc status and clear should be right before gradoperation
  79. init = self.alloc_status()
  80. init = F.depend(init, loss)
  81. clear_status = self.clear_status(init)
  82. scaling_sens = F.depend(scaling_sens, clear_status)
  83. grads = self.grad(self.network, weights)(x, self.cast(scaling_sens, mstype.float32))
  84. # apply grad reducer on grads
  85. grads = self.grad_reducer(grads)
  86. grads = self.hyper_map(F.partial(clip_grad, GRADIENT_CLIP_TYPE, GRADIENT_CLIP_VALUE), grads)
  87. init = F.depend(init, grads)
  88. get_status = self.get_status(init)
  89. init = F.depend(init, get_status)
  90. flag_sum = self.reduce_sum(init, (0,))
  91. cond = self.less_equal(self.base, flag_sum)
  92. overflow = cond
  93. if sens is None:
  94. overflow = self.loss_scaling_manager(self.loss_scale, cond)
  95. if overflow:
  96. succ = False
  97. else:
  98. succ = self.optimizer(grads)
  99. ret = (loss, cond, scaling_sens)
  100. return F.depend(ret, succ)
  101. class DatasetLenet(MindData):
  102. def __init__(self, predict, label, length=3):
  103. super(DatasetLenet, self).__init__(size=length)
  104. self.predict = predict
  105. self.label = label
  106. self.index = 0
  107. self.length = length
  108. def __iter__(self):
  109. return self
  110. def __next__(self):
  111. if self.index >= self.length:
  112. raise StopIteration
  113. self.index += 1
  114. return self.predict, self.label
  115. def reset(self):
  116. self.index = 0
  117. class LoopLayer(nn.Cell):
  118. def __init__(self):
  119. super(LoopLayer, self).__init__()
  120. self.matmul = P.MatMul()
  121. self.relu = P.ReLU()
  122. self.matmul_weight = Parameter(Tensor(np.ones([64, 64]), dtype=ms.float32), name="weight")
  123. def construct(self, x):
  124. out = self.matmul(x, self.matmul_weight)
  125. out = self.relu(out)
  126. return out
  127. class Net(nn.Cell):
  128. def __init__(self):
  129. super(Net, self).__init__()
  130. self.exp = P.Exp()
  131. self.mean = P.ReduceMean()
  132. layers = []
  133. for _ in range(3):
  134. layer = LoopLayer()
  135. layers.append(layer)
  136. self.layers = nn.CellList(layers)
  137. def construct(self, x):
  138. out = self.exp(x)
  139. for layer in self.layers:
  140. layer_out = layer(out)
  141. out = layer_out
  142. out = self.mean(out, -1)
  143. return out
  144. class Net2(nn.Cell):
  145. def __init__(self):
  146. super(Net2, self).__init__()
  147. self.matmul = P.MatMul()
  148. self.relu = P.ReLU()
  149. self.matmul_weight = Parameter(Tensor(np.ones([64, 64]), dtype=ms.float32), name="weight")
  150. def construct(self, x, b):
  151. out = self.matmul(x, self.matmul_weight)
  152. out = self.relu(out)
  153. return out
  154. def test_loss_scale():
  155. context.set_context(mode=context.GRAPH_MODE)
  156. context.set_auto_parallel_context(parallel_mode=ParallelMode.SEMI_AUTO_PARALLEL, device_num=8)
  157. predict = Tensor(np.ones([64, 64]), dtype=ms.float32)
  158. label = Tensor(np.ones([64,]), dtype=ms.int32)
  159. dataset = DatasetLenet(predict, label)
  160. net = Net()
  161. opt = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), 0.01, 0.9)
  162. net = TrainOneStepWithLossScaleCell(net, opt, update_cell)
  163. model = Model(network=net)
  164. model.train(2, dataset, dataset_sink_mode=False)
  165. def test_loss_scale2():
  166. context.set_context(mode=context.GRAPH_MODE, save_graphs=False)
  167. context.set_auto_parallel_context(parallel_mode=ParallelMode.SEMI_AUTO_PARALLEL, device_num=8)
  168. predict = Tensor(np.ones([64, 64]), dtype=ms.float32)
  169. label = Tensor(np.ones([64,]), dtype=ms.int32)
  170. dataset = DatasetLenet(predict, label)
  171. net = Net2()
  172. opt = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), 0.01, 0.9)
  173. net = nn.TrainOneStepWithLossScaleCell(net, opt, update_cell)
  174. model = Model(network=net)
  175. model.train(2, dataset, dataset_sink_mode=False)