• 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# ============================================================================
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
24context.set_context(mode=context.GRAPH_MODE, device_target='CPU')
25
26
27class NetEluGrad(nn.Cell):
28    def __init__(self):
29        super(NetEluGrad, self).__init__()
30        self.elu_grad = G.EluGrad()
31
32    def construct(self, dy, y):
33        return self.elu_grad(dy, y)
34
35
36@pytest.mark.level0
37@pytest.mark.platform_x86_cpu
38@pytest.mark.env_onecard
39def test_elu_grad_fp32():
40    y = Tensor(np.array([[[[-0.3, 1, 2],
41                           [1, -0.6, 1],
42                           [2, 1, -2]]]]).astype(np.float32))
43    dy = Tensor(np.array([[[[-11, 2, 4],
44                            [-1, 1, -1],
45                            [-4, 4, -4]]]]).astype(np.float32))
46
47    expect = np.array([[[[-7.7, 2, 4],
48                         [-1, 0.4, -1],
49                         [-4, 4, 4]]]]).astype(np.float32)
50
51    error = np.ones(shape=[1, 1, 3, 3]) * 1.0e-6
52
53    elu_grad = NetEluGrad()
54    output = elu_grad(dy, y)
55    print(output)
56    diff = np.abs(output.asnumpy() - expect)
57    double_check = diff / expect
58    assert np.all(double_check < error)
59
60
61@pytest.mark.level0
62@pytest.mark.platform_x86_cpu
63@pytest.mark.env_onecard
64def test_elu_grad_fp16():
65    y = Tensor(np.array([[0.5, 2, 5.5], [4.5, -2, 0]]).astype(np.float16))
66    dy = Tensor(np.array([[2, 1, 1.5], [-0.5, -1, -3]]).astype(np.float16))
67    expect = np.array([[2, 1, 1.5], [-0.5, 1, -3]]).astype(np.float16)
68    error = np.ones(shape=[2, 3]) * 1.0e-3
69
70    elu_grad = NetEluGrad()
71    output = elu_grad(dy, y)
72    print(output)
73    diff = np.abs(output.asnumpy() - expect)
74    double_check = diff / expect
75    assert np.all(double_check < error)
76