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 16import numpy as np 17import pytest 18 19import mindspore.context as context 20import mindspore.nn as nn 21from mindspore import Tensor 22from mindspore.ops import operations as P 23 24context.set_context(mode=context.GRAPH_MODE, device_target='CPU') 25 26 27class Net2Inputs(nn.Cell): 28 def __init__(self): 29 super(Net2Inputs, self).__init__() 30 self.addn = P.AddN() 31 32 def construct(self, x, y): 33 return self.addn((x, y)) 34 35 36@pytest.mark.level0 37@pytest.mark.platform_x86_cpu 38@pytest.mark.env_onecard 39def test_two_tensors_add(): 40 x = np.arange(2 * 3 * 2).reshape((2, 3, 2)) 41 y = np.arange(88, 2 * 3 * 2 + 88).reshape((2, 3, 2)) 42 addn_net = Net2Inputs() 43 dtypes = (np.int32, np.float32) 44 for dtype in dtypes: 45 output = addn_net(Tensor(x.astype(dtype)), Tensor(y.astype(dtype))) 46 expect_result = (x + y).astype(dtype) 47 assert output.asnumpy().dtype == expect_result.dtype 48 assert np.array_equal(output.asnumpy(), expect_result) 49 50 51class Net4Inputs(nn.Cell): 52 def __init__(self): 53 super(Net4Inputs, self).__init__() 54 self.addn = P.AddN() 55 56 def construct(self, x, y, m, n): 57 return self.addn((x, y, m, n)) 58 59 60@pytest.mark.level0 61@pytest.mark.platform_x86_cpu 62@pytest.mark.env_onecard 63def test_four_tensors_add(): 64 x = np.arange(2 * 3).reshape((2, 3)) 65 y = np.arange(1, 2 * 3 + 1).reshape((2, 3)) 66 m = np.arange(2, 2 * 3 + 2).reshape((2, 3)) 67 n = np.arange(3, 2 * 3 + 3).reshape((2, 3)) 68 addn_net = Net4Inputs() 69 dtypes = (np.int32, np.float32) 70 for dtype in dtypes: 71 output = addn_net(Tensor(x.astype(dtype)), Tensor(y.astype(dtype)), 72 Tensor(m.astype(dtype)), Tensor(n.astype(dtype))) 73 expect_result = (x + y + m + n).astype(dtype) 74 assert output.asnumpy().dtype == expect_result.dtype 75 assert np.array_equal(output.asnumpy(), expect_result) 76 77 78if __name__ == '__main__': 79 test_two_tensors_add() 80 test_four_tensors_add() 81