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 composite as C 23from mindspore.ops import operations as P 24 25context.set_context(mode=context.GRAPH_MODE, device_target="CPU") 26 27 28class GeluNet(nn.Cell): 29 def __init__(self): 30 super(GeluNet, self).__init__() 31 self.gelu = P.GeLU() 32 33 def construct(self, x): 34 return self.gelu(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_cpu 50@pytest.mark.env_onecard 51def test_gelugrad(): 52 x_ms = Tensor(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_ms = Tensor(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 57 net = GeluNet() 58 grad = Grad(net) 59 60 output = grad(x_ms, dy_ms) 61 expect = [0.50963277, 0.9414753, 0.2667653, 0.21358444, 0.25243032, 0.0352667, 62 0.34266686, 0.57757664, 0.04707306, 0.51536125] 63 assert np.allclose(output[0].asnumpy(), expect) 64