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 composite as C 23from mindspore.ops import operations as P 24 25context.set_context(mode=context.GRAPH_MODE, device_target="GPU") 26 27 28class SoftplusNet(nn.Cell): 29 def __init__(self): 30 super(SoftplusNet, self).__init__() 31 self.softplus = P.Softplus() 32 33 def construct(self, x): 34 return self.softplus(x) 35 36 37class Grad(nn.Cell): 38 def __init__(self, network): 39 super(Grad, self).__init__() 40 self.grad = C.GradOperation(get_all=True, sens_param=True) 41 self.network = network 42 43 def construct(self, input_data, sens): 44 gout = self.grad(self.network)(input_data, sens) 45 return gout 46 47 48@pytest.mark.level0 49@pytest.mark.platform_x86_gpu_training 50@pytest.mark.env_onecard 51def test_softplusgrad(): 52 x = np.array([0.58401114, 0.68800163, 0.9760397, 0.14702141, 0.46563736, 0.9607501, 53 0.14567593, 0.12261796, 0.37054458, 0.46421242]).astype(np.float32) 54 dy = np.array([0.5559598, 0.96994054, 0.24770357, 0.34646875, 0.2984393, 0.03287048, 55 0.55681044, 0.966908, 0.06015943, 0.6099489]).astype(np.float32) 56 x_ms = Tensor(x) 57 dy_ms = Tensor(dy) 58 59 net = SoftplusNet() 60 grad = Grad(net) 61 62 output = grad(x_ms, dy_ms) 63 expect = dy * np.exp(x) / (1 + np.exp(x)) 64 assert np.allclose(output[0].asnumpy(), expect, rtol=1e-3) 65 66@pytest.mark.level0 67@pytest.mark.platform_x86_gpu_training 68@pytest.mark.env_onecard 69def test_softplusgrad_fp16(): 70 np.random.seed(42) 71 x_np = np.random.randn(5, 3, 6).astype(np.float16) 72 dy_np = np.random.randn(5, 3, 6).astype(np.float16) 73 net = SoftplusNet() 74 grad = Grad(net) 75 output = grad(Tensor(x_np), Tensor(dy_np)) 76 expect = dy_np * np.exp(x_np) / (1 + np.exp(x_np)) 77 assert np.allclose(output[0].asnumpy(), expect, rtol=1e-2) 78