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_if_by_if.py 2.1 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import numpy as np
  2. import pytest
  3. import mindspore.context as context
  4. from mindspore import Tensor
  5. from mindspore.common.parameter import Parameter
  6. from mindspore.nn import Cell
  7. import mindspore.ops.operations as P
  8. @pytest.mark.level0
  9. @pytest.mark.platform_arm_ascend_training
  10. @pytest.mark.platform_x86_ascend_training
  11. @pytest.mark.env_onecard
  12. def test_if_by_if_basic():
  13. class SubNet(Cell):
  14. def __init__(self):
  15. super().__init__()
  16. self.mul = P.Mul()
  17. self.add = P.Add()
  18. a = np.full((1,), 5, dtype=np.float32)
  19. self.a = Parameter(Tensor(a), name='a')
  20. b = np.full((1,), 4, dtype=np.float32)
  21. self.b = Parameter(Tensor(b), name='b')
  22. def construct(self, x):
  23. if self.a > self.b:
  24. x = self.mul(x, 1)
  25. while self.b < 6:
  26. x = self.add(x, x)
  27. self.b += 1
  28. return x
  29. class Net(Cell):
  30. def __init__(self):
  31. super().__init__()
  32. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  33. self.subnet = SubNet()
  34. self.relu = P.ReLU()
  35. self.add = P.Add()
  36. a = np.full((1,), 5, dtype=np.float32)
  37. self.a = Parameter(Tensor(a), name='a')
  38. b = np.full((1,), 4, dtype=np.float32)
  39. self.b = Parameter(Tensor(b), name='b')
  40. c = np.full((1,), 7, dtype=np.float32)
  41. self.c = Parameter(Tensor(c), name='c')
  42. def func(self, x):
  43. for _ in range(0, 2):
  44. x = self.add(x, 0)
  45. return x
  46. def construct(self, x):
  47. if self.a > self.b:
  48. x = self.subnet(x)
  49. else:
  50. x = self.relu(x)
  51. if self.a < self.c:
  52. x = self.func(x)
  53. else:
  54. x = self.add(x, 2)
  55. return x
  56. input_np = np.random.randn(2, 3, 4, 5).astype(np.float32)
  57. net = Net()
  58. out_ms = net(Tensor(input_np))
  59. out_np = input_np * 4
  60. assert np.allclose(out_ms.asnumpy(), out_np)