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 24 25class Net(nn.Cell): 26 def __init__(self): 27 super(Net, self).__init__() 28 self.select = P.Select() 29 30 def construct(self, cond_op, input_x, input_y): 31 return self.select(cond_op, input_x, input_y) 32 33 34context.set_context(mode=context.GRAPH_MODE, device_target="CPU") 35 36 37@pytest.mark.level0 38@pytest.mark.platform_x86_cpu 39@pytest.mark.env_onecard 40def test_select_float32(): 41 cond = np.array([[True, False], [True, False]]).astype(np.bool) 42 x = np.array([[1.2, 1], [1, 0]]).astype(np.float32) 43 y = np.array([[1, 2], [3, 4.0]]).astype(np.float32) 44 select = Net() 45 output = select(Tensor(cond), Tensor(x), Tensor(y)) 46 print(output.asnumpy()) 47 expect = [[1.2, 2], [1, 4.0]] 48 error = np.ones(shape=[2, 2]) * 1.0e-6 49 diff = output.asnumpy() - expect 50 assert np.all(diff < error) 51 assert np.all(-diff < error) 52 53 54@pytest.mark.level0 55@pytest.mark.platform_x86_cpu 56@pytest.mark.env_onecard 57def test_select_float16(): 58 cond = np.array([[True, False], [True, False]]).astype(np.bool) 59 x = np.array([[1.2, 1], [1, 0]]).astype(np.float16) 60 y = np.array([[1, 2], [3, 4.0]]).astype(np.float16) 61 select = Net() 62 output = select(Tensor(cond), Tensor(x), Tensor(y)) 63 print(output.asnumpy()) 64 expect = [[1.2, 2], [1, 4.0]] 65 error = np.ones(shape=[2, 2]) * 1.0e-3 66 diff = output.asnumpy() - expect 67 assert np.all(diff < error) 68 assert np.all(-diff < error) 69 70 71@pytest.mark.level0 72@pytest.mark.platform_x86_cpu 73@pytest.mark.env_onecard 74def test_select_int32(): 75 cond = np.array([[True, False], [True, False]]).astype(np.bool) 76 x = np.array([[12, 1], [1, 0]]).astype(np.int32) 77 y = np.array([[1, 2], [3, 4]]).astype(np.int32) 78 select = Net() 79 output = select(Tensor(cond), Tensor(x), Tensor(y)) 80 print(output.asnumpy()) 81 expect = [[12, 2], [1, 4]] 82 error = np.ones(shape=[2, 2]) * 1.0e-6 83 diff = output.asnumpy() - expect 84 assert np.all(diff < error) 85 assert np.all(-diff < error) 86