test_matmul_op.py 5.3 KB
Newer Older
D
dzhwinter 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
#  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.
M
Markus Kliegl 已提交
14 15 16 17 18 19 20 21 22 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
import unittest
import numpy as np
from op_test import OpTest


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 已提交
63 64 65
            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 已提交
66 67 68 69
    if transpose_Y:
        if Y.ndim == 1:
            Y = Y.reshape((1, Y.size))
        else:
C
chengduoZH 已提交
70 71 72 73
            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 已提交
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
    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


class Generator(object):
    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,
            'transpose_Y': self.transpose_Y
        }
        self.outputs = {'Out': Out}

    def test_check_output(self):
98
        self.check_output(atol=1e-3)
M
Markus Kliegl 已提交
99 100

    def test_check_grad_normal(self):
101
        self.check_grad(['X', 'Y'], 'Out', max_relative_error=1e-3)
M
Markus Kliegl 已提交
102 103 104

    def test_check_grad_ignore_x(self):
        self.check_grad(
105
            ['Y'], 'Out', max_relative_error=1e-3, no_grad_set=set("X"))
M
Markus Kliegl 已提交
106 107 108

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


# Generate test cases for all possibilities
for dim_X in [1, 2, 3]:
    for dim_Y in [1, 2, 3]:
        for transpose_X in [False, True]:
            for transpose_Y in [False, True]:
                test_name = (
                    'TestMatMulOp_dimX_{}_dim_Y_{}_transX_{}_transY_{}'.format(
                        dim_X, dim_Y, transpose_X, transpose_Y))
                shape_X, shape_Y = generate_compatible_shapes(
                    dim_X, dim_Y, transpose_X, transpose_Y)
C
chengduoZH 已提交
122
                globals()[test_name] = type(test_name, (Generator, OpTest), {
M
Markus Kliegl 已提交
123 124 125 126 127
                    'shape_X': shape_X,
                    'shape_Y': shape_Y,
                    'transpose_X': transpose_X,
                    'transpose_Y': transpose_Y,
                })
C
chengduoZH 已提交
128 129


C
chengduoZH 已提交
130
# Test case n-dim
C
chengduoZH 已提交
131 132 133 134 135 136 137 138
def generate_compatible_shapes(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)]

    if transpose_X:
C
chengduoZH 已提交
139
        shape_X += [K, M]
C
chengduoZH 已提交
140
    else:
C
chengduoZH 已提交
141
        shape_X += [M, K]
C
chengduoZH 已提交
142 143

    if transpose_Y:
C
chengduoZH 已提交
144
        shape_Y += [N, K]
C
chengduoZH 已提交
145
    else:
C
chengduoZH 已提交
146
        shape_Y += [K, N]
C
chengduoZH 已提交
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165

    return shape_X, shape_Y


# Test case n-dim
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(
                    dim, dim, transpose_X, transpose_Y))
            shape_X, shape_Y = generate_compatible_shapes(dim, transpose_X,
                                                          transpose_Y)
            globals()[test_name] = type(test_name, (Generator, OpTest), {
                'shape_X': shape_X,
                'shape_Y': shape_Y,
                'transpose_X': transpose_X,
                'transpose_Y': transpose_Y,
            })
C
chengduoZH 已提交
166

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