test_fused_gemm_epilogue_op_xpu.py 9.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
# Copyright (c) 2022 NVIDIA Corporation. All rights reserved.
#
# 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.

from __future__ import print_function
import sys

sys.path.append("..")
import unittest
import numpy as np
import paddle
import paddle.fluid.core as core
C
Chen Weihang 已提交
24
from paddle import _legacy_C_ops
25 26 27 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 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 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 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 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
from op_test_xpu import XPUOpTest
from xpu.get_test_cover_info import create_test_class, get_xpu_op_support_types, XPUOpTestWrapper


def gelu(x):
    y_ref = 0.5 * x * (
        1.0 + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * np.power(x, 3))))
    return y_ref.astype(x.dtype)


def relu(x):
    mask = x > 0
    return x * mask


def get_output(X, Y, bias, act):
    out = np.dot(X, Y) + bias
    if act == 'relu':
        return relu(out)
    elif act == 'gelu':
        return gelu(out)
    else:
        return out


def matmul(x, y, bias, trans_x, trans_y):
    x = np.array(x)
    if trans_x:
        x = np.ascontiguousarray(np.transpose(x))
    if trans_y:
        y = np.ascontiguousarray(np.transpose(y))
    z = np.matmul(x, y)
    if bias is None:
        return z
    else:
        return z + bias


def matmul_grad(x, y, bias, dz, trans_x, trans_y):
    if trans_x:
        if trans_y:
            dx = matmul(y, dz, None, True, True)
            dy = matmul(dz, x, None, True, True)
        else:
            dx = matmul(y, dz, None, False, True)
            dy = matmul(x, dz, None, False, False)
    else:
        if trans_y:
            dx = matmul(dz, y, None, False, False)
            dy = matmul(dz, x, None, True, False)
        else:
            dx = matmul(dz, y, None, False, True)
            dy = matmul(x, dz, None, True, False)
    if bias is None:
        dbias = None
    else:
        dbias = np.sum(dz, axis=0, keepdims=False)
    return dx, dy, dbias


class XPUTestFuseGemmOp(XPUOpTestWrapper):

    def __init__(self):
        self.op_name = 'fused_gemm_epilogue'
        self.use_dynamic_create_class = False

    class TestFuseGemmBase(XPUOpTest):

        def setUp(self):
            self.__class__.no_need_check_grad = True
            self.op_type = "fused_gemm_epilogue"
            self.init_dtype_type()
            self.init_datas_shape_and_attrs()
            self.inputs = {
                'X': np.random.random(self.x_shape).astype(self.dtype) - 0.5,
                'Y': np.random.random(self.y_shape).astype(self.dtype) - 0.5,
                'Bias':
                np.random.random(self.bias_shape).astype(self.dtype) - 0.5
            }

            if self.trans_x == True:
                numpy_input_x = self.inputs['X'].reshape(
                    (self.x_shape[0], -1)).T
            else:
                numpy_input_x = self.inputs['X'].reshape((-1, self.x_shape[-1]))

            if self.trans_y == True:
                numpy_input_y = self.inputs['Y'].T
            else:
                numpy_input_y = self.inputs['Y']

            self.outputs = {
                'Out':
                get_output(numpy_input_x, numpy_input_y, self.inputs['Bias'],
                           self.activation).reshape(self.out_shape)
            }
            self.attrs = {
                "activation": self.activation,
                "trans_y": self.trans_y,
                "trans_x": self.trans_x
            }

        def init_dtype_type(self):
            self.dtype = self.in_type
            self.atol = 1e-4
            if self.dtype == np.float16:
                self.atol = 1e-3

        def init_datas_shape_and_attrs(self):
            self.x_shape = [8, 4]
            self.y_shape = [4, 128]
            self.bias_shape = [
                128,
            ]
            self.out_shape = [8, 128]
            self.activation = "relu"
            self.trans_y = False
            self.trans_x = False

        def test_check_output(self):
            self.check_output_with_place(core.XPUPlace(0), atol=self.atol)

    class TestFuseGemmEpilogueOp1(TestFuseGemmBase):

        def init_datas_shape_and_attrs(self):
            self.x_shape = [4, 8]
            self.y_shape = [4, 128]
            self.bias_shape = [
                128,
            ]
            self.out_shape = [8, 128]
            self.activation = "relu"
            self.trans_y = False
            self.trans_x = True

    class TestFuseGemmEpilogueOp2(TestFuseGemmBase):

        def init_datas_shape_and_attrs(self):
            self.x_shape = [8, 4]
            self.y_shape = [128, 4]
            self.bias_shape = [
                128,
            ]
            self.out_shape = [8, 128]
            self.activation = "relu"
            self.trans_y = True
            self.trans_x = False

    class TestFuseGemmEpilogueOp3(TestFuseGemmBase):

        def init_datas_shape_and_attrs(self):
            self.x_shape = [4, 8]
            self.y_shape = [128, 4]
            self.bias_shape = [
                128,
            ]
            self.out_shape = [8, 128]
            self.activation = "relu"
            self.trans_y = True
            self.trans_x = True

    class TestFuseGemmEpilogueOp4(TestFuseGemmBase):

        def init_datas_shape_and_attrs(self):
            self.x_shape = [2, 2, 8, 4]
            self.y_shape = [4, 128]
            self.bias_shape = [
                128,
            ]
            self.out_shape = [2, 2, 8, 128]
            self.activation = "relu"
            self.trans_y = False
            self.trans_x = False

    class TestFuseGemmEpilogueOp5(TestFuseGemmBase):

        def init_datas_shape_and_attrs(self):
            self.x_shape = [4, 2, 2, 8]
            self.y_shape = [4, 128]
            self.bias_shape = [
                128,
            ]
            self.out_shape = [2, 2, 8, 128]
            self.activation = "relu"
            self.trans_y = False
            self.trans_x = True

    class TestFuseGemmEpilogueOp6(TestFuseGemmBase):

        def init_datas_shape_and_attrs(self):
            self.x_shape = [8, 4]
            self.y_shape = [4, 128]
            self.bias_shape = [
                128,
            ]
            self.out_shape = [8, 128]
            self.activation = "gelu"
            self.trans_y = False
            self.trans_x = False

    class TestFuseGemmEpilogueOp7(TestFuseGemmBase):

        def init_datas_shape_and_attrs(self):
            self.x_shape = [8, 4]
            self.y_shape = [4, 128]
            self.bias_shape = [
                128,
            ]
            self.out_shape = [8, 128]
            self.activation = "none"
            self.trans_y = False
            self.trans_x = False


class TestEagerFusedGemmEpilogue(unittest.TestCase):

    def setUp(self):
        paddle.set_device('xpu')

    def test_case_act(self):
        paddle.disable_static()
        x_np = np.random.random((8, 4)).astype(np.float32) - 0.5
        y_np = np.random.random((4, 128)).astype(np.float32) - 0.5
        bias_np = np.random.random((128, )).astype(np.float32) - 0.5
        x = paddle.to_tensor(x_np)
        y = paddle.to_tensor(y_np)
        bias = paddle.to_tensor(bias_np)
        x.stop_gradient = False
        y.stop_gradient = False

C
Chen Weihang 已提交
255 256 257 258 259 260 261 262 263
        out1 = _legacy_C_ops.fused_gemm_epilogue(x, y, bias, 'trans_x', False,
                                                 'trans_y', False, 'activation',
                                                 'none')
        out2 = _legacy_C_ops.fused_gemm_epilogue(x, y, bias, 'trans_x', False,
                                                 'trans_y', False, 'activation',
                                                 'relu')
        out3 = _legacy_C_ops.fused_gemm_epilogue(x, y, bias, 'trans_x', False,
                                                 'trans_y', False, 'activation',
                                                 'gelu')
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294

        out_np1 = get_output(x_np, y_np, bias_np, 'none')
        out_np2 = get_output(x_np, y_np, bias_np, 'relu')
        out_np3 = get_output(x_np, y_np, bias_np, 'gelu')

        np.testing.assert_allclose(out1, out_np1, atol=1e-04)
        np.testing.assert_allclose(out2, out_np2, atol=1e-04)
        np.testing.assert_allclose(out3, out_np3, atol=1e-03)

        out_grad_np1 = np.random.randint(low=-20, high=20,
                                         size=out_np1.shape).astype(np.float32)
        paddle.autograd.backward(out1,
                                 grad_tensors=[paddle.to_tensor(out_grad_np1)])

        x_grad_np, y_grad_np, bias_grad_np = matmul_grad(
            x_np, y_np, bias_np, out_grad_np1, False, False)
        np.testing.assert_allclose(x.grad.numpy(), x_grad_np, atol=1e-02)
        self.assertEqual(y_grad_np.shape, y_np.shape)
        np.testing.assert_allclose(y.grad.numpy(), y_grad_np, atol=1e-03)

        paddle.enable_static()


support_types = get_xpu_op_support_types('fused_gemm_epilogue')
for stype in support_types:
    create_test_class(globals(), XPUTestFuseGemmOp, stype)

if __name__ == "__main__":
    paddle.enable_static()
    np.random.seed(0)
    unittest.main()