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 import operations as P 23from mindspore.ops.operations import _grad_ops as G 24 25context.set_context(mode=context.GRAPH_MODE, device_target="CPU") 26 27class NetReLU6(nn.Cell): 28 def __init__(self): 29 super(NetReLU6, self).__init__() 30 self.relu6 = P.ReLU6() 31 32 def construct(self, x): 33 return self.relu6(x) 34 35class NetReLU6Grad(nn.Cell): 36 def __init__(self): 37 super(NetReLU6Grad, self).__init__() 38 self.relu6_grad = G.ReLU6Grad() 39 40 def construct(self, x, dy): 41 return self.relu6_grad(dy, x) 42 43@pytest.mark.level0 44@pytest.mark.platform_x86_cpu 45@pytest.mark.env_onecard 46def test_relu6(): 47 x = Tensor(np.array([[[[-1, 1, 10], 48 [5.9, 6.1, 6], 49 [10, 1, -1]]]]).astype(np.float32)) 50 expect = np.array([[[[0, 1, 6,], 51 [5.9, 6, 6,], 52 [6, 1, 0.]]]]).astype(np.float32) 53 54 relu6 = NetReLU6() 55 output = relu6(x) 56 assert (output.asnumpy() == expect).all() 57 58@pytest.mark.level0 59@pytest.mark.platform_x86_cpu 60@pytest.mark.env_onecard 61def test_relu6_grad(): 62 x = Tensor(np.array([[[[-1, 1, 10], 63 [5.9, 6.1, 6], 64 [10, 1, -1]]]]).astype(np.float32)) 65 dy = Tensor(np.array([[[[1, 1, 1], 66 [1, 1, 1], 67 [1, 1, 1]]]]).astype(np.float32)) 68 expect = np.array([[[[0, 1, 0,], 69 [1, 0, 1,], 70 [0, 1, 0,]]]]).astype(np.float32) 71 error = np.ones(shape=[3, 3]) * 1.0e-6 72 73 relu6_grad = NetReLU6Grad() 74 output = relu6_grad(x, dy) 75 diff = np.abs(output.asnumpy() - expect) 76 assert np.all(np.abs(diff) < error) 77