test_matmul_op.py 12.7 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2
#
D
dzhwinter 已提交
3 4 5
# 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
D
dzhwinter 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
D
dzhwinter 已提交
9 10 11 12 13 14
# 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.

M
Markus Kliegl 已提交
15
import unittest
16

M
Markus Kliegl 已提交
17
import numpy as np
18
from op_test import OpTest
19

20
import paddle
21 22
import paddle.fluid as fluid
from paddle.fluid import Program, program_guard
M
Markus Kliegl 已提交
23 24 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


def generate_compatible_shapes(dim_X, dim_Y, transpose_X, transpose_Y):
    BATCH_SIZE = 2
    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
    return shape_X, shape_Y


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:
C
chengduoZH 已提交
69 70 71
            dim = [i for i in range(len(X.shape))]
            dim[-1], dim[len(X.shape) - 2] = dim[len(X.shape) - 2], dim[-1]
            X = np.transpose(X, tuple(dim))
M
Markus Kliegl 已提交
72 73 74 75
    if transpose_Y:
        if Y.ndim == 1:
            Y = Y.reshape((1, Y.size))
        else:
C
chengduoZH 已提交
76 77 78 79
            dim = [i for i in range(len(Y.shape))]
            dim[-1], dim[len(Y.shape) - 2] = dim[len(Y.shape) - 2], dim[-1]
            Y = np.transpose(Y, tuple(dim))

M
Markus Kliegl 已提交
80 81 82 83 84 85 86 87 88 89
    Out = np.matmul(X, Y)
    if not Out.shape:
        # We do not support 0-dimensional Tensors (scalars). So where
        # np.matmul outputs a scalar, we must convert to a Tensor of
        # shape (1, ) instead.
        # Everywhere else, we are compatible with np.matmul.
        Out = np.array([Out], dtype="float32")
    return Out


90
class Generator:
M
Markus Kliegl 已提交
91 92 93 94 95 96 97 98
    def setUp(self):
        self.op_type = "matmul"
        X = np.random.random(self.shape_X).astype("float32")
        Y = np.random.random(self.shape_Y).astype("float32")
        Out = reference_matmul(X, Y, self.transpose_X, self.transpose_Y)
        self.inputs = {'X': X, 'Y': Y}
        self.attrs = {
            'transpose_X': self.transpose_X,
99
            'transpose_Y': self.transpose_Y,
M
Markus Kliegl 已提交
100 101 102 103
        }
        self.outputs = {'Out': Out}

    def test_check_output(self):
104
        self.check_output()
M
Markus Kliegl 已提交
105 106

    def test_check_grad_normal(self):
107
        self.check_grad(['X', 'Y'], 'Out', max_relative_error=1e-3)
M
Markus Kliegl 已提交
108 109

    def test_check_grad_ignore_x(self):
110 111 112
        self.check_grad(
            ['Y'], 'Out', max_relative_error=1e-3, no_grad_set=set("X")
        )
M
Markus Kliegl 已提交
113 114

    def test_check_grad_ignore_y(self):
115 116 117
        self.check_grad(
            ['X'], 'Out', max_relative_error=1e-3, no_grad_set=set('Y')
        )
M
Markus Kliegl 已提交
118 119


120
class TestMatmulOpError(unittest.TestCase):
121 122 123 124 125 126
    def test_errors(self):
        with program_guard(Program(), Program()):
            # The inputs type of matmul_op must be Variable.
            input1 = 12
            self.assertRaises(TypeError, fluid.layers.matmul, input1, input1)
            # The inputs dtype of matmul_op must be float32, float64.
127 128 129
            input2 = fluid.layers.data(
                name='input2', shape=[10, 10], dtype="int32"
            )
130
            self.assertRaises(TypeError, fluid.layers.matmul, input2, input2)
131 132 133
            input3 = fluid.layers.data(
                name='input3', shape=[2, 2], dtype="float16"
            )
134 135 136
            fluid.layers.matmul(input3, input3)


137 138 139
# Negative dimension generation
def generate_negative_dims(in_shape):
    from itertools import combinations
140

141 142 143 144 145 146 147
    size = len(in_shape)
    indexs = list()
    shapes = list()
    for i in range(size):
        indexs.extend(list(combinations([j for j in range(size)], i + 1)))
    for idx in indexs:
        shapes.append(
148 149
            [in_shape[i] if i not in idx else -1 for i in range(size)]
        )
150 151 152 153 154 155 156 157 158 159 160 161 162
    return shapes


# Build program with inputs sizes that contain negative numbers
def test_negative_dims_program(obj):
    for shape_x in generate_negative_dims(obj.shape_X):
        for shape_y in generate_negative_dims(obj.shape_Y):
            X = np.random.random(obj.shape_X).astype("float32")
            Y = np.random.random(obj.shape_Y).astype("float32")
            Ref = reference_matmul(X, Y, obj.transpose_X, obj.transpose_Y)
            with program_guard(Program(), Program()):
                x = fluid.data(name='x', shape=shape_x, dtype='float32')
                y = fluid.data(name='y', shape=shape_y, dtype='float32')
163 164 165
                output = fluid.layers.matmul(
                    x, y, obj.transpose_X, obj.transpose_Y
                )
166 167 168 169 170
                obj.assertEqual(len(Ref.shape), len(output.shape))
                for idx in range(len(Ref.shape)):
                    if output.shape[idx] != -1:
                        obj.assertEqual(Ref.shape[idx], output.shape[idx])
                exe = fluid.Executor(fluid.CPUPlace())
171 172 173 174 175
                (res,) = exe.run(
                    fluid.default_main_program(),
                    feed={'x': X, 'y': Y},
                    fetch_list=[output],
                )
176 177 178 179 180
                np.allclose(res, Ref, atol=1e-5)


# Generate program api cases for all negative possibilities
def api_test(dim_x, dim_y, trans_x, trans_y):
181 182 183 184 185 186
    test_name = 'TestMatMulAPI_dimX_{}_dim_Y_{}_transX_{}_transY_{}'.format(
        dim_x, dim_y, trans_x, trans_y
    )
    shape_x, shape_y = generate_compatible_shapes(
        dim_x, dim_y, trans_x, trans_y
    )
187
    globals()[test_name] = type(
188 189 190
        test_name,
        (unittest.TestCase,),
        {
191 192 193 194 195
            'shape_X': shape_x,
            'shape_Y': shape_y,
            'transpose_X': trans_x,
            'transpose_Y': trans_y,
            'test_propram': test_negative_dims_program,
196 197
        },
    )
198 199 200


# Generate operators cases for all possibilities
Y
Yu Yang 已提交
201
def inject_test(dim_x, dim_y, trans_x, trans_y):
202 203 204 205 206 207
    test_name = 'TestMatMulOp_dimX_{}_dim_Y_{}_transX_{}_transY_{}'.format(
        dim_x, dim_y, trans_x, trans_y
    )
    shape_x, shape_y = generate_compatible_shapes(
        dim_x, dim_y, trans_x, trans_y
    )
208
    globals()[test_name] = type(
209 210 211
        test_name,
        (Generator, OpTest),
        {
212 213 214 215
            'shape_X': shape_x,
            'shape_Y': shape_y,
            'transpose_X': trans_x,
            'transpose_Y': trans_y,
216 217
        },
    )
Y
Yu Yang 已提交
218 219 220 221 222 223 224


for dim_X in (1, 2, 3):
    for dim_Y in (1, 2, 3):
        for transose_x in (False, True):
            for transose_y in (False, True):
                inject_test(dim_X, dim_Y, transose_x, transose_y)
225
                api_test(dim_X, dim_Y, transose_x, transose_y)
C
chengduoZH 已提交
226 227


228
# Test case more batch_size and N, M, K
229 230 231
def generate_compatible_shapes_batch(
    dim_X, dim_Y, transpose_X, transpose_Y, batch_size
):
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
    BATCH_SIZE = 2
    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
    return shape_X, shape_Y


C
chengduoZH 已提交
265
# Test case n-dim
266
def generate_compatible_shapes_ndim(dim, transpose_X, transpose_Y):
C
chengduoZH 已提交
267 268 269 270 271 272 273
    M = 2
    N = 4
    K = 3
    shape_X = [2 for _ in range(dim - 2)]
    shape_Y = [2 for _ in range(dim - 2)]

    if transpose_X:
C
chengduoZH 已提交
274
        shape_X += [K, M]
C
chengduoZH 已提交
275
    else:
C
chengduoZH 已提交
276
        shape_X += [M, K]
C
chengduoZH 已提交
277 278

    if transpose_Y:
C
chengduoZH 已提交
279
        shape_Y += [N, K]
C
chengduoZH 已提交
280
    else:
C
chengduoZH 已提交
281
        shape_Y += [K, N]
C
chengduoZH 已提交
282 283 284 285

    return shape_X, shape_Y


Y
Yu Yang 已提交
286
# # Test case n-dim
C
chengduoZH 已提交
287 288 289 290 291
for dim in [4]:
    for transpose_X in [False, True]:
        for transpose_Y in [False, True]:
            test_name = (
                'TestMatMulOp_dimX_{}_dim_Y_{}_transX_{}_transY_{}'.format(
292 293 294
                    dim, dim, transpose_X, transpose_Y
                )
            )
295
            shape_X, shape_Y = generate_compatible_shapes_ndim(
296 297
                dim, transpose_X, transpose_Y
            )
298
            globals()[test_name] = type(
299 300 301
                test_name,
                (Generator, OpTest),
                {
302 303 304 305
                    'shape_X': shape_X,
                    'shape_Y': shape_Y,
                    'transpose_X': transpose_X,
                    'transpose_Y': transpose_Y,
306 307
                },
            )
C
chengduoZH 已提交
308

309 310 311 312

class API_TestMm(unittest.TestCase):
    def test_out(self):
        with fluid.program_guard(fluid.Program()):
313 314 315
            x = fluid.data(name="x", shape=[2], dtype="float64")
            y = fluid.data(name='y', shape=[2], dtype='float64')
            res = fluid.data(name="output", shape=[1], dtype="float64")
316 317
            result = paddle.mm(x, y)
            exe = fluid.Executor(fluid.CPUPlace())
318 319
            data1 = np.random.rand(2)
            data2 = np.random.rand(2)
320
            np_res = exe.run(feed={'x': data1, 'y': data2}, fetch_list=[result])
321 322 323
            expected_result = np.matmul(
                data1.reshape(1, 2), data2.reshape(2, 1)
            )
324

325 326 327 328 329 330
        np.testing.assert_allclose(
            np_res,
            expected_result,
            rtol=1e-05,
            atol=1e-05,
            err_msg='two value is            {}\n{}, check diff!'.format(
331 332 333
                np_res, expected_result
            ),
        )
334

335 336 337 338 339 340 341 342 343
    def test_dygraph_without_out(self):
        device = fluid.CPUPlace()
        with fluid.dygraph.guard(device):
            input_array1 = np.random.rand(3, 4).astype("float64")
            input_array2 = np.random.rand(4, 3).astype("float64")
            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)
344
        np.testing.assert_allclose(expected_result, out.numpy(), rtol=1e-05)
345 346 347 348 349 350 351 352 353 354 355 356


class Test_API_Matmul(unittest.TestCase):
    def test_dygraph_without_out(self):
        device = fluid.CPUPlace()
        with fluid.dygraph.guard(device):
            input_array1 = np.random.rand(3, 4).astype("float64")
            input_array2 = np.random.rand(4, 3).astype("float64")
            data1 = fluid.dygraph.to_variable(input_array1)
            data2 = fluid.dygraph.to_variable(input_array2)
            out = paddle.matmul(data1, data2)
            expected_result = np.matmul(input_array1, input_array2)
357
        np.testing.assert_allclose(expected_result, out.numpy(), rtol=1e-05)
358

359 360 361 362 363 364 365 366 367 368 369 370 371

class API_TestMmError(unittest.TestCase):
    def test_errors(self):
        def test_error1():
            with fluid.program_guard(fluid.Program(), fluid.Program()):
                data1 = fluid.data(name="data1", shape=[10, 2], dtype="float32")
                data2 = fluid.data(name="data2", shape=[3, 10], dtype="float32")
                paddle.mm(data1, data2)

        self.assertRaises(ValueError, test_error1)

        def test_error2():
            with fluid.program_guard(fluid.Program(), fluid.Program()):
372 373 374 375 376 377
                data1 = fluid.data(
                    name="data1", shape=[-1, 10, 2], dtype="float32"
                )
                data2 = fluid.data(
                    name="data2", shape=[-1, 2, 10], dtype="float32"
                )
378 379 380 381 382 383
                paddle.mm(data1, data2)

        test_error2()

        def test_error3():
            with fluid.program_guard(fluid.Program(), fluid.Program()):
384 385 386 387 388 389
                data1 = fluid.data(
                    name="data1", shape=[10, 10, 2], dtype="float32"
                )
                data2 = fluid.data(
                    name="data2", shape=[3, 2, 10], dtype="float32"
                )
390 391 392 393 394
                paddle.mm(data1, data2)

        self.assertRaises(ValueError, test_error3)


M
Markus Kliegl 已提交
395 396
if __name__ == "__main__":
    unittest.main()