• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2021 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# ============================================================================
15import numpy as np
16import pytest
17import mindspore.context as context
18import mindspore.nn as nn
19from mindspore import Tensor
20from mindspore.ops import operations as P
21
22class Net(nn.Cell):
23    def __init__(self, axis=-1):
24        super(Net, self).__init__()
25        self.Softmax = P.Softmax(axis)
26
27    def construct(self, x):
28        return self.Softmax(x)
29
30def get_output(x, enable_graph_kernel=False):
31    context.set_context(enable_graph_kernel=enable_graph_kernel)
32    opt = Net()
33    output = opt(Tensor(x))
34    return output
35
36def test_softmax(shape, dtype):
37    np.random.seed(0)
38    x = np.random.normal(0, 1, shape).astype(dtype)
39
40    expect = get_output(x, False)
41    output = get_output(x, True)
42
43    rtol = 1.e-4
44    atol = 1.e-4
45    if dtype == "float16":
46        rtol = 1.e-3
47        atol = 1.e-3
48
49    assert np.allclose(expect.asnumpy(), output.asnumpy(), rtol, atol, equal_nan=True)
50
51@pytest.mark.level0
52@pytest.mark.platform_x86_gpu_training
53@pytest.mark.env_onecard
54def test_softmax_gpu():
55    context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
56    test_softmax([4, 32, 48], np.float32)
57
58@pytest.mark.level1
59@pytest.mark.platform_arm_ascend_training
60@pytest.mark.platform_x86_ascend_training
61@pytest.mark.env_onecard
62def test_softmax_ascend():
63    context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
64    test_softmax([2, 32, 48, 64], np.float32)
65