test_insert_grad_of.py 4.2 KB
Newer Older
Z
zhunaipan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# 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_insert_grad_of """
import numpy as np
import mindspore.nn as nn
from mindspore.ops import composite as C
from mindspore.ops import operations as P
20
from mindspore.ops import functional as F
Z
zhunaipan 已提交
21 22 23 24 25 26
from mindspore.common.api import ms_function
from ....mindspore_test_framework.utils.bprop_util import bprop
from ....mindspore_test_framework.utils.debug_util import PrintShapeTypeCell, PrintGradShapeTypeCell
from mindspore import Tensor

from mindspore import context
27
import mindspore
Z
zhunaipan 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 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 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110

def setup_module(module):
    context.set_context(mode=context.PYNATIVE_MODE)


def stop_gradient(dx):
    """ stop_gradient """
    return C.zeros_like(dx)

stop = P.InsertGradientOf(stop_gradient)
def test_InsertGradientOf_1():
    """ test_InsertGradientOf_1 """
    def stop_test(x, y):
        x = stop(x)
        c = x * y
        return c

    def f(x, y):
        return C.grad_all(stop_test)(x, y)
    print("stop_gradient:", f(1, 2))

def clip_gradient(dx):
    """ clip_gradient """
    ret = dx
    if ret > 1.0:
        ret = 1.0

    if ret < 0.2:
        ret = 0.2

    return ret

clip = P.InsertGradientOf(clip_gradient)
def test_InsertGradientOf_2():
    """ test_InsertGradientOf_2 """
    def clip_test(x, y):
        x = clip(x)
        y = clip(y)
        c = x * y
        return c

    @ms_function
    def f(x, y):
        return clip_test(x, y)

    def fd(x, y):
        return C.grad_all(clip_test)(x, y)

    print("forward: ", f(1.1, 0.1))
    print("clip_gradient:", fd(1.1, 0.1))

summary = P.ScalarSummary()
def debug_gradient(dx):
    """ debug_gradient """
    dx = summary("dx: ", dx)
    return dx

debug = P.InsertGradientOf(debug_gradient)
def test_InsertGradientOf_3():
    """ test_InsertGradientOf_3 """
    def debug_test(x, y):
        x = debug(x)
        y = debug(y)
        c = x * y
        return c

    def f(x, y):
        return C.grad_all(debug_test)(x, y)
    print("debug_gradient:", f(1, 2))

def test_print_shape_type():
    class Mul(nn.Cell):
        def __init__(self):
            super(Mul, self).__init__()
            self.print_shape_type = PrintShapeTypeCell()
            self.print_shape_type_gradient = PrintGradShapeTypeCell("Gradients")
        def construct(self, x, y):
            z = x * y
            self.print_shape_type("Forward", z)
            self.print_shape_type_gradient(z)
            return z
    bprop(Mul(), Tensor(np.ones([2, 2]).astype(np.float32)),
          Tensor(np.ones([2, 2]).astype(np.float32)))
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

def test_cell_assign():
    context.set_context(mode=context.GRAPH_MODE, save_graphs=True)
    class GradNetWrap(nn.Cell):
        """ GradNetWrap definition """
        def __init__(self, net):
            super(GradNetWrap, self).__init__()
            self.net = net
            self.weights = mindspore.ParameterTuple(net.get_parameters())

        def construct(self, x, y):
            return C.grad_by_list(self.net, self.weights)(x, y)

    class Mul(nn.Cell):
        def __init__(self):
            super(Mul, self).__init__()
            self.get_g = P.InsertGradientOf(self.save_gradient)
            self.matrix_w = mindspore.Parameter(Tensor(np.ones([2, 2], np.float32)), name="matrix_w")
            self.matrix_g = mindspore.Parameter(Tensor(np.ones([2, 2], np.float32)), name="matrix_g")

        def save_gradient(self, dout):
            self.matrix_g = dout
            return dout

        def construct(self, x, y):
            z = x * self.matrix_w
            z = self.get_g(z)
            z = z * y
            return z

    input_x = Tensor(np.ones([2, 2], np.float32))
    input_y = Tensor(np.ones([2, 2], np.float32))
    GradNetWrap(Mul())(input_x, input_y)