test_layer_norm_op.py 9.0 KB
Newer Older
C
chengduoZH 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.
#
# 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.
import unittest
import numpy as np

C
chengduoZH 已提交
17
from operator import mul
C
chengduoZH 已提交
18
from op_test import OpTest
C
chengduoZH 已提交
19 20 21
import paddle.v2.fluid.core as core
from paddle.v2.fluid.op import Operator
from paddle.v2.fluid.framework import grad_var_name
C
chengduoZH 已提交
22

C
chengduoZH 已提交
23 24
np.random.random(123)

C
chengduoZH 已提交
25

C
chengduoZH 已提交
26
def _reference_layer_norm_naive(x, scale, beta, epsilon, begin_norm_axis=1):
C
chengduoZH 已提交
27 28 29
    x_shape = x.shape
    N = reduce(mul, x_shape[0:begin_norm_axis], 1)
    D = reduce(mul, x_shape[begin_norm_axis:len(x_shape)], 1)
C
chengduoZH 已提交
30
    x.shape = [N, D]
C
chengduoZH 已提交
31

C
chengduoZH 已提交
32 33
    mean = np.mean(x, axis=1)
    var = np.var(x, axis=1) + epsilon
C
chengduoZH 已提交
34 35 36
    output = scale.reshape([1, D]) * np.divide(
        (x - mean.reshape([N, 1])),
        (np.sqrt(var)).reshape([N, 1])) + beta.reshape([1, D])
C
chengduoZH 已提交
37 38

    x.shape, output.shape = x_shape, x_shape
C
chengduoZH 已提交
39 40 41
    return output, mean, var


C
chengduoZH 已提交
42
def _reference_layer_norm_grad(x, grad_y, scale, mean, var, begin_norm_axis=1):
C
chengduoZH 已提交
43
    x_shape = x.shape
C
chengduoZH 已提交
44
    scale_shape = scale.shape
C
chengduoZH 已提交
45 46
    N = reduce(mul, x_shape[0:begin_norm_axis], 1)
    D = reduce(mul, x_shape[begin_norm_axis:len(x_shape)], 1)
C
chengduoZH 已提交
47 48
    x.shape, grad_y.shape = [N, D], [N, D]
    var.shape, mean.shape = [N, 1], [N, 1]
C
chengduoZH 已提交
49
    scale.shape = [1, D]
C
chengduoZH 已提交
50

C
chengduoZH 已提交
51
    # d_bias
C
chengduoZH 已提交
52
    d_bias = np.sum(grad_y, axis=0).reshape([1, D])
C
chengduoZH 已提交
53
    # d_scale
C
chengduoZH 已提交
54 55
    d_scale = np.sum(((x - mean) * np.sqrt(1 / var)) * grad_y,
                     axis=0).reshape([1, D])
C
chengduoZH 已提交
56
    # dx
C
chengduoZH 已提交
57 58
    dx_end = scale * np.sqrt(1.0 / var) * grad_y
    d_mean_0 = np.sum(-np.sqrt(1.0 / var) * grad_y * scale, axis=1).reshape(
59
        [N, 1])  # the second part equals to zero.
C
chengduoZH 已提交
60 61
    d_mean = 1.0 / D * d_mean_0
    d_std = np.sum(
C
chengduoZH 已提交
62
        -(1.0 / var) * (x - mean) * grad_y * scale, axis=1).reshape([N, 1]) * (
C
chengduoZH 已提交
63
            1.0 / D * np.sqrt(1.0 / var).reshape([N, 1]) * (x - mean))
C
chengduoZH 已提交
64

C
chengduoZH 已提交
65
    grad_x = dx_end + d_mean + d_std
C
chengduoZH 已提交
66

C
chengduoZH 已提交
67
    grad_x.shape, x.shape, grad_y.shape = x_shape, x_shape, x_shape
C
chengduoZH 已提交
68
    scale.shape = scale_shape
C
chengduoZH 已提交
69
    var.shape, mean.shape = [N, ], [N, ]
C
chengduoZH 已提交
70
    return grad_x, d_scale, d_bias
C
chengduoZH 已提交
71 72


C
chengduoZH 已提交
73 74 75 76 77 78 79 80 81 82 83
def get_backward_op(scope, op, no_grad_set):
    backward_op = core.Operator.backward(op, no_grad_set)
    for input in backward_op.input_vars():
        var = scope.var(input)
        var.get_tensor()
    for output in backward_op.output_vars():
        var = scope.var(output)
        var.get_tensor()
    return backward_op


C
chengduoZH 已提交
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 111 112 113 114
def create_or_get_tensor(scope, var_name, var, place):
    tensor = scope.var(var_name).get_tensor()
    if var is not None:
        assert isinstance(var, np.ndarray)
        tensor.set_lod([[]])
        tensor.set_dims(var.shape)
        tensor.set(var, place)
    return tensor


def set_output_grad(scope, outputs, place, feed_dict=None):
    def __set_tensor__(name, data=None):
        out_tensor = scope.find_var(name).get_tensor()
        grad_tensor = scope.var(grad_var_name(name)).get_tensor()
        out_dtype = out_tensor.dtype()
        if data is None:
            if out_dtype == core.DataType.FP64:
                data = np.ones(out_tensor.shape(), dtype=np.float64)
            elif out_dtype == core.DataType.FP32:
                data = np.ones(out_tensor.shape(), dtype=np.float32)
            else:
                raise ValueError("Not supported data type " + str(out_dtype))
        grad_tensor.set(data, place)

    for output in outputs:
        data = None
        if output in feed_dict:
            data = feed_dict[output]
        __set_tensor__(output, data)


C
chengduoZH 已提交
115
class TestLayerNormdOp(OpTest):
C
chengduoZH 已提交
116
    def __assert_close(self, tensor, np_array, msg, atol=1e-4):
C
chengduoZH 已提交
117
        self.assertTrue(np.allclose(np.array(tensor), np_array, atol=atol), msg)
C
chengduoZH 已提交
118 119 120 121 122 123 124

    def __assert_grad_close(self,
                            tensor,
                            np_array,
                            name,
                            place,
                            max_relative_error=0.02):
C
chengduoZH 已提交
125
        a = np.array(tensor)
C
chengduoZH 已提交
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
        b = np_array
        abs_a = np.abs(a)
        abs_a[abs_a < 1e-5] = 1

        diff_mat = np.abs(a - b) / abs_a
        max_diff = np.max(diff_mat)

        def err_msg():
            offset = np.argmax(diff_mat > max_relative_error)
            return ("%s Variable %s max gradient diff %f over limit %f, "
                    "the first error element is %d, %f, %f") % (
                        "Gradient Check On %s" % str(place), name, max_diff,
                        max_relative_error, offset, a.flatten()[offset],
                        b.flatten()[offset])

        self.assertLessEqual(max_diff, max_relative_error, err_msg())

C
chengduoZH 已提交
143
    def check_forward_backward(self, shape, begin_norm_axis):
C
chengduoZH 已提交
144
        def test_with_place(place, shape, begin_norm_axis=1):
C
chengduoZH 已提交
145
            # setUp
C
chengduoZH 已提交
146 147
            assert begin_norm_axis > 0 and begin_norm_axis < len(
                shape), 'begin_norm_axis must be between 0 and len(shape)-1.'
C
chengduoZH 已提交
148 149 150
            # attr
            epsilon = 0.00001
            x_shape = shape
C
chengduoZH 已提交
151 152
            D = reduce(mul, x_shape[begin_norm_axis:len(x_shape)], 1)
            scale_shape = [D]
C
chengduoZH 已提交
153

C
chengduoZH 已提交
154 155 156
            x_val = np.random.random_sample(x_shape).astype(np.float32)
            scale_val = np.random.random_sample(scale_shape).astype(np.float32)
            bias_val = np.random.random_sample(scale_shape).astype(np.float32)
C
chengduoZH 已提交
157
            y_grad = np.random.random_sample(x_shape).astype(np.float32)
C
chengduoZH 已提交
158 159 160

            # run forward
            y_out, saved_mean, var_ref = _reference_layer_norm_naive(
C
chengduoZH 已提交
161
                x_val, scale_val, bias_val, epsilon, begin_norm_axis)
C
chengduoZH 已提交
162
            naive_fw = {"Y": y_out, "Mean": saved_mean, "Variance": var_ref}
C
chengduoZH 已提交
163

C
chengduoZH 已提交
164
            # get gradient
C
chengduoZH 已提交
165
            x_grad_ref, scale_grad_ref, bias_grad_ref = _reference_layer_norm_grad(
C
chengduoZH 已提交
166
                x_val, y_grad, scale_val, saved_mean, var_ref, begin_norm_axis)
C
chengduoZH 已提交
167 168 169 170 171
            naive_grad = {
                "X": x_grad_ref,
                "Scale": scale_grad_ref,
                "Bias": bias_grad_ref
            }
C
chengduoZH 已提交
172 173 174 175

            scope = core.Scope()

            # create input
C
chengduoZH 已提交
176 177 178
            input_map = {"X": x_val, "Scale": scale_val, "Bias": bias_val}
            for i_name in input_map:
                create_or_get_tensor(scope, i_name, input_map[i_name], place)
C
chengduoZH 已提交
179 180

            # create output
C
chengduoZH 已提交
181 182 183 184 185
            output_map = {"Y": None, "Mean": None, "Variance": None}
            output_tensor = {}
            for o_name in output_map:
                output_tensor[o_name] = create_or_get_tensor(
                    scope, o_name, output_map[o_name], place)
C
chengduoZH 已提交
186 187 188 189 190 191 192 193 194 195 196 197

            layer_norm_op = Operator(
                "layer_norm",
                # inputs
                X="X",
                Scale="Scale",
                Bias="Bias",
                # outputs
                Y="Y",
                Mean="Mean",
                Variance="Variance",
                # attrs
C
chengduoZH 已提交
198 199
                epsilon=epsilon,
                begin_norm_axis=begin_norm_axis)
C
chengduoZH 已提交
200 201 202 203

            layer_norm_op.run(scope, place)

            # check forward result
C
chengduoZH 已提交
204 205 206 207
            atol = 5e-2 if isinstance(place, core.CUDAPlace) else 1e-4
            for o_tensor in output_tensor:
                self.__assert_close(output_tensor[o_tensor], naive_fw[o_tensor],
                                    o_tensor, atol)
C
chengduoZH 已提交
208 209 210 211 212 213 214 215 216

            # run backward
            layer_norm_op_grad = get_backward_op(scope, layer_norm_op, set())
            set_output_grad(
                scope, ["Y", "Mean", "Variance"],
                place,
                feed_dict={"Y": y_grad})
            layer_norm_op_grad.run(scope, place)

C
chengduoZH 已提交
217 218 219 220 221
            # get output
            grad_tensor = {}
            for o_name in naive_grad:
                grad_tensor[o_name] = x_ = create_or_get_tensor(
                    scope, grad_var_name(o_name), None, place)
C
chengduoZH 已提交
222 223

            # check gradient output
C
chengduoZH 已提交
224 225 226 227
            for o_grad in naive_grad:
                self.__assert_grad_close(grad_tensor[o_grad],
                                         naive_grad[o_grad], o_grad + "@GRAD",
                                         place)
C
chengduoZH 已提交
228 229

        places = [core.CPUPlace()]
Y
Yang Yu 已提交
230
        if core.is_compiled_with_cuda() and core.op_support_gpu("layer_norm"):
C
chengduoZH 已提交
231 232 233
            places.append(core.CUDAPlace(0))

        for place in places:
C
chengduoZH 已提交
234 235
            test_with_place(place, shape, begin_norm_axis)

236
    def test_check_forward_backward_with_scale_and_bias(self):
C
chengduoZH 已提交
237 238
        self.check_forward_backward(shape=[2, 3, 4, 5], begin_norm_axis=1)
        self.check_forward_backward(shape=[2, 3, 4, 5], begin_norm_axis=3)
C
chengduoZH 已提交
239

240 241 242 243 244 245 246 247 248
    def test_check_forward_backward_with_scale(self):
        pass  # TODO(zcd)

    def test_check_forward_backward_with_bias(self):
        pass  # TODO(zcd)

    def test_check_forward_backward(self):
        pass  # TODO(zcd)

C
chengduoZH 已提交
249 250 251

if __name__ == '__main__':
    unittest.main()