• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.operations import _grad_ops as G
23
24
25class NetSigmoidGrad(nn.Cell):
26    def __init__(self):
27        super(NetSigmoidGrad, self).__init__()
28        self.sigmoid_grad = G.SigmoidGrad()
29
30    def construct(self, y, dy):
31        return self.sigmoid_grad(y, dy)
32
33
34@pytest.mark.level0
35@pytest.mark.platform_x86_gpu_training
36@pytest.mark.env_onecard
37def test_sigmoid_grad():
38    y = Tensor(np.array([[[[-1, 1, 2],
39                           [1, -1, 1],
40                           [2, 1, -1]]]]).astype(np.float32))
41    dy = Tensor(np.array([[[[-11, 2, 4],
42                            [-1, 1, -1],
43                            [-4, 4, -4]]]]).astype(np.float32))
44
45    expect = np.array([[[[22, 0, -8],
46                         [0, -2, 0],
47                         [8, 0, 8]]]]).astype(np.float32)
48
49    error = np.ones(shape=[1, 1, 3, 3]) * 1.0e-6
50
51    context.set_context(mode=context.PYNATIVE_MODE, device_target="GPU")
52    sigmoid_grad = NetSigmoidGrad()
53    output = sigmoid_grad(y, dy)
54    diff = output.asnumpy() - expect
55    assert np.all(abs(diff) < error)
56
57    context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
58    sigmoid_grad = NetSigmoidGrad()
59    output = sigmoid_grad(y, dy)
60    diff = output.asnumpy() - expect
61    assert np.all(abs(diff) < error)
62