• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2019-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# ============================================================================
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 NetNeg(nn.Cell):
26    def __init__(self):
27        super(NetNeg, self).__init__()
28        self.neg = P.Neg()
29
30    def construct(self, x):
31        return self.neg(x)
32
33
34def neg(nptype):
35    x0_np = np.random.uniform(-2, 2, (2, 3, 4, 4)).astype(nptype)
36    x1_np = np.random.uniform(-2, 2, 1).astype(nptype)
37    x0 = Tensor(x0_np)
38    x1 = Tensor(x1_np)
39    expect0 = np.negative(x0_np)
40    expect1 = np.negative(x1_np)
41    error0 = np.ones(shape=expect0.shape) * 1.0e-5
42    error1 = np.ones(shape=expect1.shape) * 1.0e-5
43
44    context.set_context(mode=context.PYNATIVE_MODE, device_target="GPU")
45    neg_net = NetNeg()
46    output0 = neg_net(x0)
47    diff0 = output0.asnumpy() - expect0
48    assert np.all(diff0 < error0)
49    assert output0.shape == expect0.shape
50    output1 = neg_net(x1)
51    diff1 = output1.asnumpy() - expect1
52    assert np.all(diff1 < error1)
53    assert output1.shape == expect1.shape
54
55    context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
56    neg_net = NetNeg()
57    output0 = neg_net(x0)
58    diff0 = output0.asnumpy() - expect0
59    assert np.all(diff0 < error0)
60    assert output0.shape == expect0.shape
61    output1 = neg_net(x1)
62    diff1 = output1.asnumpy() - expect1
63    assert np.all(diff1 < error1)
64    assert output1.shape == expect1.shape
65
66@pytest.mark.level1
67@pytest.mark.platform_x86_gpu_training
68@pytest.mark.env_onecard
69def test_neg_float16():
70    neg(np.float16)
71
72@pytest.mark.level0
73@pytest.mark.platform_x86_gpu_training
74@pytest.mark.env_onecard
75def test_neg_float32():
76    neg(np.float32)
77
78@pytest.mark.level0
79@pytest.mark.platform_x86_gpu_training
80@pytest.mark.env_onecard
81def test_neg_float64():
82    neg(np.float64)
83