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_debug_location.py 6.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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. import numpy as np
  16. import mindspore.nn as nn
  17. import pytest
  18. from mindspore import context
  19. from mindspore import Tensor, Parameter
  20. from mindspore.nn.wrap.cell_wrapper import WithLossCell
  21. from mindspore.train.loss_scale_manager import FixedLossScaleManager, DynamicLossScaleManager
  22. from mindspore.nn.wrap.loss_scale import TrainOneStepWithLossScaleCell
  23. from mindspore.ops import operations as P
  24. from mindspore.nn.optim import Momentum
  25. from mindspore.ops import functional as F
  26. from mindspore.common import dtype as mstype
  27. from mindspore.train import Model
  28. from ....dataset_mock import MindData
  29. from mindspore.nn.optim import Lamb
  30. from mindspore.ops._utils import _get_broadcast_shape
  31. from mindspore.ops.primitive import Primitive, PrimitiveWithInfer, prim_attr_register
  32. from mindspore.ops._grad.grad_base import bprop_getters
  33. from mindspore.ops._grad.grad_math_ops import binop_grad_common
  34. context.set_context(mode=context.GRAPH_MODE)
  35. class MockNeg(PrimitiveWithInfer):
  36. @prim_attr_register
  37. def __init__(self):
  38. """init MockNeg"""
  39. self.init_prim_io_names(inputs=['x'], outputs=['y'])
  40. def infer_shape(self, input_x):
  41. return input_x
  42. def infer_dtype(self, input_x):
  43. raise TypeError("InferError")
  44. return input_x
  45. class MockSub(PrimitiveWithInfer):
  46. @prim_attr_register
  47. def __init__(self):
  48. """init MockSub"""
  49. self.init_prim_io_names(inputs=['x', 'y'], outputs=['output'])
  50. def infer_shape(self, x_shape, y_shape):
  51. return _get_broadcast_shape(x_shape, y_shape)
  52. def infer_dtype(self, x_dtype, y_dtype):
  53. return x_dtype
  54. @bprop_getters.register(MockSub)
  55. def get_bprop_mock_sub(self):
  56. """Grad definition for `MockSub` operation."""
  57. neg_func = MockNeg()
  58. def bprop(x, y, out, dout):
  59. return binop_grad_common(x, y, dout, neg_func(dout))
  60. return bprop
  61. class Net(nn.Cell):
  62. def __init__(self, in_features, out_features):
  63. super(Net, self).__init__()
  64. self.weight = Parameter(Tensor(np.ones([out_features, in_features]).astype(np.float32)), name="weight")
  65. self.bias = Parameter(Tensor(np.ones([out_features]).astype(np.float32)), name="bias")
  66. self.matmul = P.MatMul()
  67. self.add = P.TensorAdd()
  68. def construct(self, input):
  69. output = self.add(self.matmul(input, self.weight), self.bias)
  70. return output
  71. class NetFP16(nn.Cell):
  72. def __init__(self, in_features, out_features):
  73. super(NetFP16, self).__init__()
  74. self.weight = Parameter(Tensor(np.ones([out_features, in_features]).astype(np.float32)), name="weight")
  75. self.bias = Parameter(Tensor(np.ones([out_features]).astype(np.float32)), name="bias")
  76. self.matmul = P.MatMul()
  77. self.add = P.TensorAdd()
  78. self.cast = P.Cast()
  79. def construct(self, input):
  80. output = self.cast(self.add(self.matmul(self.cast(input, mstype.float16), self.cast(self.weight, mstype.float16)),
  81. self.cast(self.bias, mstype.float16)), mstype.float32)
  82. return output
  83. def get_axis(x):
  84. shape = F.shape(x)
  85. length = F.tuple_len(shape)
  86. perm = F.make_range(0, length)
  87. return perm
  88. class MSELoss(nn.Cell):
  89. def __init__(self):
  90. super(MSELoss, self).__init__()
  91. self.reduce_sum = P.ReduceSum()
  92. self.square = P.Square()
  93. self.reduce_mean = P.ReduceMean()
  94. self.sub = MockSub()
  95. def construct(self, data, label):
  96. diff = self.sub(data, label)
  97. return self.reduce_mean(self.square(diff), get_axis(diff))
  98. class NegCell(nn.Cell):
  99. def __init__(self):
  100. super(NegCell, self).__init__()
  101. self.neg = MockNeg()
  102. def construct(self, x):
  103. return self.neg(x)
  104. class Net3(nn.Cell):
  105. def __init__(self):
  106. super().__init__()
  107. self.tuple = (NegCell(), nn.ReLU())
  108. def construct(self, x):
  109. for op in self.tuple:
  110. x = op(x)
  111. return x
  112. def test_op_forward_infererror():
  113. input_np = np.random.randn(2, 3, 4, 5).astype(np.float32)
  114. input_me = Tensor(input_np)
  115. net = Net3()
  116. with pytest.raises(TypeError) as e:
  117. net(input_me)
  118. class SequenceNet(nn.Cell):
  119. def __init__(self):
  120. super().__init__()
  121. self.seq = nn.SequentialCell([nn.AvgPool2d(3, 1), nn.ReLU(), nn.Flatten()])
  122. def construct(self, x):
  123. x = self.seq(x) + bbb
  124. return x
  125. def test_sequential_resolve_error():
  126. input_np = np.random.randn(2, 3, 4, 5).astype(np.float32)
  127. input_me = Tensor(input_np)
  128. net = SequenceNet()
  129. with pytest.raises(RuntimeError) as e:
  130. net(input_me)
  131. def test_compile_grad_error():
  132. inputs = Tensor(np.ones([16, 16]).astype(np.float32))
  133. label = Tensor(np.zeros([16, 16]).astype(np.float32))
  134. lr = Tensor(np.ones([1], np.float32) * 0.1)
  135. net = NetFP16(16, 16)
  136. loss = MSELoss()
  137. optimizer = Momentum(net.trainable_params(), learning_rate=lr, momentum=0.9)
  138. net_with_loss = WithLossCell(net, loss)
  139. scale_manager = DynamicLossScaleManager()
  140. update_cell = scale_manager.get_update_cell()
  141. train_network = TrainOneStepWithLossScaleCell(net_with_loss, optimizer, scale_update_cell = update_cell)
  142. train_network.set_train()
  143. with pytest.raises(TypeError) as e:
  144. train_network(inputs, label)
  145. print (e)