test_grad.py 6.3 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
from mindspore.common.api import ms_function
W
Wei Luning 已提交
22
from mindspore.common.dtype import get_py_obj_dtype
J
jinyaohui 已提交
23
from mindspore.ops import composite as C
W
Wei Luning 已提交
24
from mindspore.ops import functional as F
Z
zhunaipan 已提交
25 26
from ...ut_filter import non_graph_engine

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

P
panyifeng 已提交
31

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


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


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


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


@non_graph_engine
B
buxue 已提交
51
def Xtest_expand_dims_grad():
Z
zhunaipan 已提交
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 89
    """ 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 已提交
90 91 92 93 94 95 96 97 98
def test_scalar_cast_grad():
    """ test_scalar_cast_grad """
    input_x = 255.5
    input_t = get_py_obj_dtype(ms.int8)

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

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

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


Z
zhunaipan 已提交
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 162
@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)
163
    expect_cond = np.zeros_like(cond.asnumpy())
Z
zhunaipan 已提交
164 165 166 167 168
    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 已提交
169

Z
zhunaipan 已提交
170

K
kingfo 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
@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 已提交
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
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 已提交
215
    mymul = P.Mul()
Z
zhunaipan 已提交
216 217

    def fn(x, y):
P
panyifeng 已提交
218
        output = mymul(x, y)
Z
zhunaipan 已提交
219 220 221 222 223 224 225 226 227 228 229 230 231
        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)