• 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 import operations as P
23from mindspore.ops.composite import GradOperation
24
25
26class Grad(nn.Cell):
27    def __init__(self, network):
28        super(Grad, self).__init__()
29        self.grad = GradOperation(get_all=True, sens_param=True)
30        self.network = network
31
32    def construct(self, input_x, dout):
33        return self.grad(self.network)(input_x, dout)
34
35
36class Net(nn.Cell):
37    def __init__(self):
38        super(Net, self).__init__()
39        self.hswish = P.HSwish()
40
41    def construct(self, x):
42        return self.hswish(x)
43
44
45def expect_hswish_forward_result(x):
46    return np.where(x <= -3, 0, np.where(x >= 3, x, x * (x + 3) / 6))
47
48
49def expect_hswish_backward_result(x, dout):
50    return np.where(x <= -3, 0, np.where(x >= 3, 1, x / 3 + 0.5)) * dout
51
52
53def judge_result_correct(result, expect):
54    assert result.dtype == expect.dtype
55    assert result.shape == expect.shape
56    assert np.allclose(result, expect)
57
58
59def generate_test_cases(np_type, mode):
60    context.set_context(mode=mode, device_target="GPU")
61    x = np.array([-1, -2, 0, 4, 5]).astype(np_type)
62    net = Net()
63    output = net(Tensor(x))
64    expect = expect_hswish_forward_result(x)
65    judge_result_correct(output.asnumpy(), expect)
66
67    sens = np.array([-1.45, 0.63, 0.34, 6.43, 34.6]).astype(np_type)
68    backward_net = Grad(Net())
69    output = backward_net(Tensor(x), Tensor(sens))
70    expect = expect_hswish_backward_result(x, sens)
71    judge_result_correct(output[0].asnumpy(), expect)
72
73
74@pytest.mark.level0
75@pytest.mark.platform_x86_gpu_training
76@pytest.mark.env_onecard
77def test_hswish_forward_and_backward():
78    modes = (context.GRAPH_MODE, context.PYNATIVE_MODE)
79    dtypes = (np.float32, np.float16)
80    for mode in modes:
81        for dtype in dtypes:
82            generate_test_cases(dtype, mode)
83