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 6.2 kB

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