test_grad.py 6.2 KB
Newer Older
Z
zhunaipan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
""" test_grad """
import numpy as np
J
jinyaohui 已提交
17

Z
zhunaipan 已提交
18
import mindspore as ms
J
jinyaohui 已提交
19
import mindspore.ops.operations as P
20
from mindspore import Tensor, context
J
jinyaohui 已提交
21 22
from mindspore.common.api import ms_function
from mindspore.ops import composite as C
W
Wei Luning 已提交
23
from mindspore.ops import functional as F
Z
zhunaipan 已提交
24 25
from ...ut_filter import non_graph_engine

26 27 28
# pylint: disable=unused-argument
def setup_module(module):
    context.set_context(mode=context.PYNATIVE_MODE)
Z
zhunaipan 已提交
29

P
panyifeng 已提交
30

P
panyifeng 已提交
31 32
grad = C.GradOperation()
grad_all_with_sens = C.GradOperation(get_all=True, sens_param=True)
P
panyifeng 已提交
33 34


Z
zhunaipan 已提交
35 36 37 38 39 40
def mul(x, y):
    return x * y


@ms_function
def mainf(x, y):
P
panyifeng 已提交
41
    return grad(mul)(x, y)
Z
zhunaipan 已提交
42 43 44 45 46 47 48 49


@non_graph_engine
def test_grad():
    mainf(1, 2)


@non_graph_engine
B
buxue 已提交
50
def Xtest_expand_dims_grad():
Z
zhunaipan 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
    """ test_expand_dims_grad """
    input_tensor = Tensor(np.array([[2, 2], [2, 2]]))
    expand_dims = P.ExpandDims()

    def fn(x):
        output = expand_dims(x, 0)
        return output

    out = fn(input_tensor)
    gfn = grad_all_with_sens(fn)
    sens = Tensor(np.ones_like(out.asnumpy()))
    args = [input_tensor, sens]
    gout = gfn(*args)
    expect = np.ones([2, 2])
    assert np.all(gout[0].asnumpy() == expect)


def test_cast_grad():
    """ test_cast_grad """
    input_np = np.random.randn(2, 3).astype(np.float32)
    input_x = Tensor(input_np)

    td = ms.int32
    cast = P.Cast()

    def fn(x):
        output = cast(x, td)
        return output

    out = fn(input_x)
    gfn = grad_all_with_sens(fn)
    sens = Tensor(np.ones_like(out.asnumpy()))
    args = [input_x, sens]
    gout = gfn(*args)
    expect = np.ones((2, 3), dtype=np.float32)
    assert np.all(gout[0].asnumpy() == expect)


W
Wei Luning 已提交
89 90 91
def test_scalar_cast_grad():
    """ test_scalar_cast_grad """
    input_x = 255.5
92
    input_t = ms.int8
W
Wei Luning 已提交
93 94 95 96 97

    def fx_cast(x):
        output = F.scalar_cast(x, input_t)
        return output

K
kingfo 已提交
98 99
    @ms_function
    def grad_fx_cast(input_x):
P
panyifeng 已提交
100
        return grad(fx_cast)(input_x)
K
kingfo 已提交
101 102

    gfn = grad_fx_cast(input_x)
W
Wei Luning 已提交
103 104 105 106
    expect_dx = 1
    assert gfn == expect_dx


Z
zhunaipan 已提交
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
@non_graph_engine
def test_reshape_grad():
    """ test_reshape_grad """
    input_tensor = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]))
    shp = (3, 2)
    reshape = P.Reshape()

    def fn(x):
        output = reshape(x, shp)
        return output

    out = fn(input_tensor)
    gfn = grad_all_with_sens(fn)
    sens = Tensor(np.ones_like(out.asnumpy()))
    args = [input_tensor, sens]
    gout = gfn(*args)
    expect = np.ones([2, 3])
    assert np.all(gout[0].asnumpy() == expect)


def test_transpose_grad():
    """ test_transpose_grad """
    input_tensor = Tensor(np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]))
    perm = (0, 2, 1)
    transpose = P.Transpose()

    def fn(x):
        output = transpose(x, perm)
        return output

    out = fn(input_tensor)
    gfn = grad_all_with_sens(fn)
    sens = Tensor(np.ones_like(out.asnumpy()))
    args = [input_tensor, sens]
    gout = gfn(*args)
    expect = np.ones([2, 2, 3])
    assert np.all(gout[0].asnumpy() == expect)


def test_select_grad():
    """ test_select_grad """
    select = P.Select()
    cond = Tensor(np.array([[True, False, False], [False, True, True]]))
    x = Tensor(np.array([[1, 2, 3], [4, 5, 6]]).astype(np.float32))
    y = Tensor(np.array([[7, 8, 9], [10, 11, 12]]).astype(np.float32))

    def fn(cond, x, y):
        output = select(cond, x, y)
        return output

    out = fn(cond, x, y)
    gfn = grad_all_with_sens(fn)
    sens = Tensor(np.ones_like(out.asnumpy()).astype(np.float32))
    args = [cond, x, y, sens]
    gout = gfn(*args)
162
    expect_cond = np.zeros_like(cond.asnumpy())
Z
zhunaipan 已提交
163 164 165 166 167
    expect_x = np.array([[1, 0, 0], [0, 1, 1]])
    expect_y = np.array([[0, 1, 1], [1, 0, 0]])
    assert np.all(gout[0].asnumpy() == expect_cond)
    assert np.all(gout[1].asnumpy() == expect_x)
    assert np.all(gout[2].asnumpy() == expect_y)
P
panyifeng 已提交
168

Z
zhunaipan 已提交
169

K
kingfo 已提交
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
@non_graph_engine
def test_squeeze_grad():
    """ test_squeeze_grad """
    input_tensor = Tensor(np.ones(shape=[3, 2, 1]))
    squeeze = P.Squeeze(2)

    def fn(x):
        output = squeeze(x)
        return output

    out = fn(input_tensor)
    gfn = grad_all_with_sens(fn)
    sens = Tensor(np.ones_like(out.asnumpy()))
    args = [input_tensor, sens]
    gout = gfn(*args)
    expect = np.ones([3, 2, 1])
    assert np.all(gout[0].asnumpy() == expect)


Z
zhunaipan 已提交
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
def test_SubGrad():
    """ test_SubGrad """
    input_x = Tensor(np.array([[2, 2]]))
    input_y = Tensor(np.array([[2, 2], [2, 2]]))
    sub = P.Sub()

    def fn(x, y):
        output = sub(x, y)
        return output

    out = fn(input_x, input_y)
    gfn = grad_all_with_sens(fn)
    sens = Tensor(np.ones_like(out.asnumpy()))
    args = [input_x, input_y, sens]
    gout = gfn(*args)
    expect_dx = np.ones([1, 2]).astype(np.int32) * 2  # reduce sum dout to the shape of x
    expect_dy = np.ones([2, 2]).astype(np.int32) * (-1)
    assert np.array_equal(gout[0].asnumpy(), expect_dx)
    assert np.array_equal(gout[1].asnumpy(), expect_dy)


def test_MulGrad():
    """ test_MulGrad """
    input_x = Tensor(np.array([[2, 2], [2, 2]], np.float32))
    input_y = Tensor(np.array([[3, 3], [3, 3]], np.float32))
P
panyifeng 已提交
214
    mymul = P.Mul()
Z
zhunaipan 已提交
215 216

    def fn(x, y):
P
panyifeng 已提交
217
        output = mymul(x, y)
Z
zhunaipan 已提交
218 219 220 221 222 223 224 225 226 227 228 229 230
        return output

    out = fn(input_x, input_y)
    gfn = grad_all_with_sens(fn)
    sens = Tensor(np.ones_like(out.asnumpy()) * 3)
    args = [input_x, input_y, sens]
    gout = gfn(*args)
    expect_dx = np.ones([2, 2], np.float32) * 9
    expect_dy = np.ones([2, 2], np.float32) * 6
    assert np.all(gout[0].asnumpy().shape == expect_dx.shape)
    assert np.all(gout[0].asnumpy() == expect_dx)
    assert np.all(gout[1].asnumpy().shape == expect_dy.shape)
    assert np.all(gout[1].asnumpy() == expect_dy)