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_tensoradd.py 2.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 pytest
  17. import mindspore.common.dtype as mstype
  18. import mindspore.nn as nn
  19. from mindspore import Tensor, context
  20. from mindspore.ops import operations as P
  21. context.set_context(mode=context.GRAPH_MODE, device_target='CPU')
  22. class TensorAdd(nn.Cell):
  23. def __init__(self):
  24. super(TensorAdd, self).__init__()
  25. self.add = P.TensorAdd()
  26. def construct(self, x, y):
  27. res = self.add(x, y)
  28. return res
  29. @pytest.mark.level0
  30. @pytest.mark.platform_x86_cpu
  31. @pytest.mark.env_onecard
  32. def test_tensor_add():
  33. x0 = Tensor(np.random.uniform(-2, 2, (2, 3, 4, 4)).astype(np.float32))
  34. y0 = Tensor(np.random.uniform(-2, 2, (1, 1, 1, 1)).astype(np.float32))
  35. x1 = Tensor(np.random.uniform(-2, 2, (1, 3, 1, 4)).astype(np.float32))
  36. y1 = Tensor(np.random.uniform(-2, 2, (2, 3, 4, 4)).astype(np.float32))
  37. x2 = Tensor(np.random.uniform(-2, 2, (2, 3, 4, 4)).astype(np.float32))
  38. y2 = Tensor(2, mstype.float32)
  39. add = TensorAdd()
  40. out = add(x0, y0).asnumpy()
  41. exp = x0.asnumpy() + y0.asnumpy()
  42. diff = np.abs(out - exp)
  43. err = np.ones(shape=exp.shape) * 1.0e-5
  44. assert np.all(diff < err)
  45. assert out.shape == exp.shape
  46. out = add(x1, y1).asnumpy()
  47. exp = x1.asnumpy() + y1.asnumpy()
  48. diff = np.abs(out - exp)
  49. err = np.ones(shape=exp.shape) * 1.0e-5
  50. assert np.all(diff < err)
  51. assert out.shape == exp.shape
  52. out = add(x2, y2).asnumpy()
  53. exp = x2.asnumpy() + y2.asnumpy()
  54. diff = np.abs(out - exp)
  55. err = np.ones(shape=exp.shape) * 1.0e-5
  56. assert np.all(diff < err)
  57. assert out.shape == exp.shape