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 random 17from functools import reduce 18import numpy as np 19import pytest 20 21import mindspore.context as context 22import mindspore.nn as nn 23from mindspore import Tensor 24from mindspore.common import dtype as mstype 25import mindspore.ops as ops 26 27 28class NetArgmax(nn.Cell): 29 def __init__(self, axis=0): 30 super(NetArgmax, self).__init__() 31 self.argmax = ops.Argmax(axis, output_type=mstype.int32) 32 33 def construct(self, x): 34 return self.argmax(x) 35 36 37@pytest.mark.level0 38@pytest.mark.platform_x86_gpu_training 39@pytest.mark.env_onecard 40def test_argmax_1d(): 41 for mode in [context.PYNATIVE_MODE, context.GRAPH_MODE]: 42 context.set_context(mode=mode, device_target="GPU") 43 44 x = Tensor(np.array([1., 20., 5.]).astype(np.float32)) 45 Argmax = NetArgmax(axis=0) 46 output = Argmax(x) 47 expect = np.array([1]).astype(np.float32) 48 assert (output.asnumpy() == expect).all() 49 50 51@pytest.mark.level0 52@pytest.mark.platform_x86_gpu_training 53@pytest.mark.env_onecard 54def test_argmax_2d(): 55 for mode in [context.PYNATIVE_MODE, context.GRAPH_MODE]: 56 context.set_context(mode=mode, device_target="GPU") 57 58 x = Tensor(np.array([[1., 20., 5.], 59 [67., 8., 9.], 60 [130., 24., 15.], 61 [0.3, -0.4, -15.]]).astype(np.float32)) 62 Argmax_axis_0 = NetArgmax(axis=0) 63 output = Argmax_axis_0(x) 64 expect = np.array([2, 2, 2]).astype(np.int32) 65 assert (output.asnumpy() == expect).all() 66 67 Argmax_axis_1 = NetArgmax(axis=1) 68 output = Argmax_axis_1(x) 69 expect = np.array([1, 0, 0, 0]).astype(np.int32) 70 assert (output.asnumpy() == expect).all() 71 72 73@pytest.mark.level0 74@pytest.mark.platform_x86_gpu_training 75@pytest.mark.env_onecard 76def test_argmax_high_dims(): 77 for mode in [context.PYNATIVE_MODE, context.GRAPH_MODE]: 78 context.set_context(mode=mode, device_target="GPU") 79 for dim in range(3, 10): 80 shape = np.random.randint(1, 10, size=dim) 81 x = np.random.randn(reduce(lambda x, y: x * y, shape)).astype(np.float32) 82 x = x.reshape(shape) 83 84 rnd_axis = random.randint(-dim + 1, dim - 1) 85 Argmax = NetArgmax(axis=rnd_axis) 86 ms_output = Argmax(Tensor(x)) 87 np_output = np.argmax(x, axis=rnd_axis) 88 assert (ms_output.asnumpy() == np_output).all() 89