test_matmul_op_xpu.py 12.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#   Copyright (c) 2018 PaddlePaddle Authors. 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.

import unittest
16

17
import numpy as np
R
RedContritio 已提交
18
from get_test_cover_info import (
19
    XPUOpTestWrapper,
20 21 22
    create_test_class,
    get_xpu_op_support_types,
)
R
RedContritio 已提交
23
from op_test_xpu import XPUOpTest
24

25
import paddle
26
from paddle import fluid
27

28 29 30 31 32 33 34 35 36 37 38

def reference_matmul(X, Y, transpose_X=False, transpose_Y=False):
    """Reference forward implementation using np.matmul."""
    # np.matmul does not support the transpose flags, so we manually
    # transpose X and Y appropriately.
    if transpose_X:
        if X.ndim == 1:
            X = X.reshape((X.size, 1))
        elif X.ndim == 2:
            X = X.T
        else:
39
            dim = list(range(len(X.shape)))
40 41 42 43 44 45 46 47
            dim[-1], dim[len(X.shape) - 2] = dim[len(X.shape) - 2], dim[-1]
            X = np.transpose(X, tuple(dim))
    if transpose_Y:
        if Y.ndim == 1:
            Y = Y.reshape((1, Y.size))
        elif Y.ndim == 2:
            Y = Y.T
        else:
48
            dim = list(range(len(Y.shape)))
49 50 51 52 53 54 55 56 57 58 59
            dim[-1], dim[len(Y.shape) - 2] = dim[len(Y.shape) - 2], dim[-1]
            Y = np.transpose(Y, tuple(dim))

    if X.ndim == 3 and Y.ndim == 2:
        x_dims = X.shape
        X = X.reshape((x_dims[0] * x_dims[1], x_dims[2]))
    if Y.ndim == 3 and X.ndim == 2:
        y_dims = Y.shape
        Y = Y.reshape((y_dims[0] * y_dims[1], y_dims[2]))
    Out = np.matmul(X, Y)
    return Out
60

61

62 63 64
def generate_compatible_shapes(
    dim_X, dim_Y, transpose_X, transpose_Y, batch_size
):
65
    BATCH_SIZE = 2
66
    if batch_size is not None:
67 68
        BATCH_SIZE = batch_size

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
    M = 3
    N = 4
    K = 5
    if (dim_X == 1 and transpose_X) or (dim_Y == 1 and transpose_Y):
        K = 1
    if dim_X == 1:
        if transpose_X:
            shape_X = [M]
        else:
            shape_X = [K]
    if dim_Y == 1:
        if transpose_Y:
            shape_Y = [N]
        else:
            shape_Y = [K]
    if dim_X >= 2:
        if transpose_X:
            shape_X = [K, M]
        else:
            shape_X = [M, K]
    if dim_X == 3:
        shape_X = [BATCH_SIZE] + shape_X
    if dim_Y >= 2:
        if transpose_Y:
            shape_Y = [N, K]
        else:
            shape_Y = [K, N]
    if dim_Y == 3:
        shape_Y = [BATCH_SIZE] + shape_Y
98 99

    if dim_Y == 3 and dim_X == 2:
100
        if not transpose_X:
101 102 103 104
            shape_X[1] = shape_X[1] * BATCH_SIZE
        else:
            shape_X[0] = shape_X[0] * BATCH_SIZE

105 106 107
    return shape_X, shape_Y


108 109 110 111 112 113
def generate_compatible_shapes_2(dim, transpose_X, transpose_Y):
    M = 2
    N = 4
    K = 3
    shape_X = [2 for _ in range(dim - 2)]
    shape_Y = [2 for _ in range(dim - 2)]
114

115 116 117 118
    if transpose_X:
        shape_X += [K, M]
    else:
        shape_X += [M, K]
119

120 121 122 123
    if transpose_Y:
        shape_Y += [N, K]
    else:
        shape_Y += [K, N]
124

125
    return shape_X, shape_Y
126 127


128 129 130 131
class XPUTestMatmulOpErr(XPUOpTestWrapper):
    def __init__(self):
        self.op_name = "matmul"
        self.use_dynamic_create_class = False
132

133 134 135
    class API_TestMm(unittest.TestCase):
        def test_out(self):
            with fluid.program_guard(fluid.Program()):
136 137
                x = paddle.static.data(name="x", shape=[2], dtype=self.in_type)
                y = paddle.static.data(name='y', shape=[2], dtype=self.in_type)
138 139 140 141
                result = paddle.mm(x, y)
                exe = fluid.Executor(fluid.XPUPlace(0))
                data1 = np.random.rand(2).astype(self.in_type)
                data2 = np.random.rand(2).astype(self.in_type)
142 143 144
                np_res = exe.run(
                    feed={'x': data1, 'y': data2}, fetch_list=[result]
                )
145
                expected_result = np.matmul(data1, data2)
146

147
                np.testing.assert_allclose(np_res, expected_result, atol=1e-3)
148 149 150 151 152 153 154 155 156 157

        def test_dygraph_without_out(self):
            device = fluid.XPUPlace(0)
            with fluid.dygraph.guard(device):
                input_array1 = np.random.rand(3, 4).astype(self.in_type)
                input_array2 = np.random.rand(4, 3).astype(self.in_type)
                data1 = fluid.dygraph.to_variable(input_array1)
                data2 = fluid.dygraph.to_variable(input_array2)
                out = paddle.mm(data1, data2)
                expected_result = np.matmul(input_array1, input_array2)
158 159 160
                np.testing.assert_allclose(
                    expected_result, out.numpy(), atol=1e-3
                )
161 162 163 164 165 166 167 168

    class Test_API_Matmul(unittest.TestCase):
        def test_dygraph_without_out(self):
            device = fluid.XPUPlace(0)
            with fluid.dygraph.guard(device):
                input_array1 = np.random.rand(3, 4).astype(self.in_type)
                input_array2 = np.random.rand(4, 3).astype(self.in_type)
                data1 = fluid.dygraph.to_variable(input_array1).astype(
169 170
                    self.in_type
                )
171
                data2 = fluid.dygraph.to_variable(input_array2).astype(
172 173
                    self.in_type
                )
174 175
                out = paddle.matmul(data1, data2)
                expected_result = np.matmul(input_array1, input_array2)
176 177 178
                np.testing.assert_allclose(
                    expected_result, out.numpy(), atol=1e-3
                )
179 180 181 182 183

    class API_TestMmError(unittest.TestCase):
        def test_errors(self):
            def test_error1():
                with fluid.program_guard(fluid.Program(), fluid.Program()):
184
                    data1 = paddle.static.data(
185 186
                        name="data1", shape=[10, 2], dtype="float32"
                    )
187
                    data2 = paddle.static.data(
188 189
                        name="data2", shape=[3, 10], dtype="float32"
                    )
190 191 192 193 194 195
                    paddle.mm(data1, data2)

            self.assertRaises(ValueError, test_error1)

            def test_error2():
                with fluid.program_guard(fluid.Program(), fluid.Program()):
196
                    data1 = paddle.static.data(
197 198
                        name="data1", shape=[-1, 10, 2], dtype="float32"
                    )
199
                    data2 = paddle.static.data(
200 201
                        name="data2", shape=[-1, 2, 10], dtype="float32"
                    )
202 203 204 205 206 207
                    paddle.mm(data1, data2)

            test_error2()

            def test_error3():
                with fluid.program_guard(fluid.Program(), fluid.Program()):
208
                    data1 = paddle.static.data(
209 210
                        name="data1", shape=[10, 10, 2], dtype="float32"
                    )
211
                    data2 = paddle.static.data(
212 213
                        name="data2", shape=[3, 2, 10], dtype="float32"
                    )
214 215 216 217 218 219 220 221
                    paddle.mm(data1, data2)

            self.assertRaises(ValueError, test_error3)


class TestMatmulBaseGenerator(XPUOpTest):
    def setUp(self):
        self.op_type = "matmul"
222 223 224
        self.dtype = (
            np.float32 if not hasattr(self, 'in_type') else self.in_type
        )
225

226 227 228 229 230
        self.__class__.no_need_check_grad = (
            False
            if not hasattr(self, 'no_need_check_grad')
            else self.no_need_check_grad
        )
231

232 233
        shape_X = [4, 5] if not hasattr(self, 'shape_X') else self.shape_X
        shape_Y = [5, 6] if not hasattr(self, 'shape_Y') else self.shape_Y
234 235 236 237 238 239
        transpose_X = (
            False if not hasattr(self, 'transpose_X') else self.transpose_X
        )
        transpose_Y = (
            False if not hasattr(self, 'transpose_Y') else self.transpose_Y
        )
240 241 242

        X = np.random.random(shape_X).astype(self.dtype)
        Y = np.random.random(shape_Y).astype(self.dtype)
243 244 245
        Out = reference_matmul(X, Y, transpose_X, transpose_Y).astype(
            self.dtype
        )
246 247 248 249 250 251 252 253 254
        self.inputs = {'X': X, 'Y': Y}
        self.attrs = {'transpose_X': transpose_X, 'transpose_Y': transpose_Y}
        self.outputs = {'Out': Out}

    def test_check_output(self):
        place = paddle.XPUPlace(0)
        self.check_output_with_place(place, atol=1e-3)

    def test_check_grad_normal(self):
255 256
        if (
            hasattr(self.__class__, "no_need_check_grad")
257
            and self.__class__.no_need_check_grad
258
        ):
259 260
            return

261
        place = paddle.XPUPlace(0)
262 263 264
        self.check_grad_with_place(
            place, ['X', 'Y'], 'Out', max_relative_error=5e-2
        )
265

266
    def test_check_grad_ignore_x(self):
267 268
        if (
            hasattr(self.__class__, "no_need_check_grad")
269
            and self.__class__.no_need_check_grad
270
        ):
271 272
            return

273
        place = paddle.XPUPlace(0)
274 275 276
        self.check_grad_with_place(
            place, ['Y'], 'Out', max_relative_error=5e-2, no_grad_set=set("X")
        )
277 278

    def test_check_grad_ignore_y(self):
279 280
        if (
            hasattr(self.__class__, "no_need_check_grad")
281
            and self.__class__.no_need_check_grad
282
        ):
283 284
            return

285
        place = paddle.XPUPlace(0)
286 287 288
        self.check_grad_with_place(
            place, ['X'], 'Out', max_relative_error=5e-2, no_grad_set=set('Y')
        )
289 290


291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
class XPUTestMatmulOp1(XPUOpTestWrapper):
    def __init__(self):
        self.op_name = "matmul"
        self.use_dynamic_create_class = True

    def dynamic_create_class(self):
        base_class = TestMatmulBaseGenerator
        classes = []
        xpu_support_dims_list = [[1, 1], [2, 2], [3, 3]]
        batch_size = [2, 4, 5, 10, 50, 100, 300]
        for dims in xpu_support_dims_list:
            dim_X = dims[0]
            dim_Y = dims[1]
            for transose_x in [True, False]:
                for transose_y in [True, False]:
                    for batch in batch_size:
307 308 309
                        no_need_check_grad = False
                        if batch >= 5:
                            no_need_check_grad = True
310 311 312
                        class_name = 'TestMatMulOp_dimX_{}_dim_Y_{}_transX_{}_transY_{}_batch_{}'.format(
                            dim_X, dim_Y, transose_x, transose_y, batch
                        )
313
                        shape_x, shape_y = generate_compatible_shapes(
314 315
                            dim_X, dim_Y, transose_x, transose_y, batch
                        )
316 317 318 319 320
                        attr_dict = {
                            'shape_X': shape_x,
                            'shape_Y': shape_y,
                            'transpose_X': transose_x,
                            'transpose_Y': transose_y,
321
                            'no_need_check_grad': no_need_check_grad,
322
                            'op_type': "matmul",
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
                        }
                        classes.append([class_name, attr_dict])

        return base_class, classes


class XPUTestMatmulOp3(XPUOpTestWrapper):
    def __init__(self):
        self.op_name = "matmul"
        self.use_dynamic_create_class = True

    def dynamic_create_class(self):
        base_class = TestMatmulBaseGenerator
        classes = []
        for dim in [4]:
            for transpose_X in [False, True]:
                for transpose_Y in [False, True]:
340 341 342
                    class_name = 'TestMatMulOp2_dimX_{}_dim_Y_{}_transX_{}_transY_{}'.format(
                        dim, dim, transpose_X, transpose_Y
                    )
343
                    shape_X, shape_Y = generate_compatible_shapes_2(
344 345
                        dim, transpose_X, transpose_Y
                    )
346 347 348 349 350
                    attr_dict = {
                        'shape_X': shape_X,
                        'shape_Y': shape_Y,
                        'transpose_X': transpose_X,
                        'transpose_Y': transpose_Y,
351
                        'op_type': "matmul",
352 353 354 355 356 357 358 359 360 361
                    }
                    classes.append([class_name, attr_dict])
        return base_class, classes


support_types = get_xpu_op_support_types('matmul')
for stype in support_types:
    create_test_class(globals(), XPUTestMatmulOpErr, stype)
    create_test_class(globals(), XPUTestMatmulOp1, stype)
    create_test_class(globals(), XPUTestMatmulOp3, stype)
362 363

if __name__ == "__main__":
364
    paddle.enable_static()
365
    unittest.main()