test_tensordot.py 10.7 KB
Newer Older
F
From00 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#   Copyright (c) 2021 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 itertools as it
R
Ruibiao Chen 已提交
16 17
import numpy as np
import unittest
F
From00 已提交
18

R
Ruibiao Chen 已提交
19 20
import paddle
import paddle.fluid.core as core
F
From00 已提交
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 63 64 65 66 67 68


def tensordot_np(x, y, axes):
    if isinstance(axes, paddle.fluid.framework.Variable):
        axes = axes.tolist()

    # np.tensordot does not support empty axes
    if not axes:
        axes = 0
    if (isinstance(axes, (tuple, list))):
        if all(np.issubdtype(type(i), np.integer) for i in axes):
            axes = [axes, axes]
        else:
            axes_x = axes[0]
            if len(axes) > 1:
                axes_y = axes[1]
            else:
                axes_y = axes_x
            len_axes_x, len_axes_y = len(axes_x), len(axes_y)
            if len_axes_x < len_axes_y:
                axes_x = axes_x + axes_y[len_axes_x:]
            elif len_axes_y < len_axes_x:
                axes_y = axes_y + axes_x[len_axes_y:]
            axes = [axes_x, axes_y]

    # np.tensordot does not support broadcast
    if (isinstance(axes, (tuple, list))):
        axes_x, axes_y = axes
    else:
        axes_x = list(range(x.ndim - axes, x.ndim))
        axes_y = list(range(axes))
    shape_x, shape_y = list(np.shape(x)), list(np.shape(y))
    for i in range(len(axes_x)):
        dim_x, dim_y = axes_x[i], axes_y[i]
        sx, sy = shape_x[dim_x], shape_y[dim_y]
        if sx == 1:
            shape_y[dim_y] = 1
            y = np.sum(y, dim_y)
            y = np.reshape(y, shape_y)
        elif sy == 1:
            shape_x[dim_x] = 1
            x = np.sum(x, dim_x)
            x = np.reshape(x, shape_x)

    return np.tensordot(x, y, axes)


class TestTensordotAPI(unittest.TestCase):
69

F
From00 已提交
70
    def setUp(self):
R
Ruibiao Chen 已提交
71
        self.set_place()
F
From00 已提交
72 73 74
        self.set_dtype()
        self.set_input_shape()
        self.set_input_data()
R
Ruibiao Chen 已提交
75 76 77 78 79 80
        self.set_test_axes()

    def set_place(self):
        self.places = [core.CPUPlace()]
        if core.is_compiled_with_cuda():
            self.places.append(core.CUDAPlace(0))
F
From00 已提交
81 82 83 84 85 86 87 88 89 90 91 92

    def set_dtype(self):
        self.dtype = np.float32

    def set_input_shape(self):
        self.x_shape = [5, 5, 5, 5]
        self.y_shape = [5, 5, 5, 5]

    def set_input_data(self):
        self.x = np.random.random(self.x_shape).astype(self.dtype)
        self.y = np.random.random(self.y_shape).astype(self.dtype)

R
Ruibiao Chen 已提交
93
    def set_test_axes(self):
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
        self.all_axes = [[[3, 2], [3]], [[2, 1, 0], [2, 1]],
                         [[1, 2, 0], [1, 3, 2]], [3, 0], [[], [0, 3, 1]],
                         [[2, 1, 0, 3], [2, 0, 1, 3]], [[3, 1, 2], [1, 3, 2,
                                                                    0]],
                         [[2, 1], [0, 2]], [[2, 0, 1, 3], [2]],
                         [[1, 2, 0, 3], [0, 2, 1]], [[2, 1, 3, 0], [1, 2, 3]],
                         [[2, 0, 1, 3], [3, 1, 0, 2]], [[0, 3], [0, 3, 2, 1]],
                         [[1, 3, 2, 0], [2, 1, 0, 3]],
                         [[1, 3, 2, 0], [1, 3, 2, 0]], [[1, 0, 2], [0, 1]],
                         [[2, 3, 0], [3, 1]], [[1, 3, 2, 0], [3, 0, 1, 2]],
                         [[3, 2, 1], [2, 0, 1]], [[0], []],
                         [[2, 3, 0], [1, 2, 0]], [[3, 0, 2, 1], [2, 1, 0, 3]],
                         [[3, 1, 2], [2, 3, 1]], [[1, 0, 2, 3], []],
                         [[1, 2], [1, 2, 3]], [[2, 0, 1, 3], [2, 0, 1]],
                         [[3, 1, 2], [1, 3, 2]], [[3, 1, 2, 0], [1, 2, 3, 0]],
                         [[0, 2, 3], [0, 1, 2]], [[3, 2, 0], [2, 0, 3, 1]],
                         [[2, 1, 0, 3], [3, 1, 2, 0]],
                         [[1, 2, 3, 0], [1, 3, 0, 2]], [[3, 0], [2, 1]],
                         [[0, 1, 3, 2], [0, 2, 1, 3]], [[1, 0], [2, 1, 3]],
                         [[1, 0, 3, 2], [2, 3, 0, 1]], [[1, 2], [3]],
                         [[1, 2, 3, 0], [3, 2, 1, 0]],
                         [[0, 3, 2, 1], [2, 1, 3, 0]], [0],
                         [[0, 2, 3], [3, 2, 0, 1]], [[1, 2, 3, 0], [3, 2, 1,
                                                                    0]],
                         [[3, 1], [3]], [[3, 2, 0, 1], [3, 2, 0]],
                         [[2, 3, 0, 1], [0, 3, 2]], [[1], [1, 3]],
                         [[1, 2], [2, 1, 0]], [[3, 1, 2], [3, 1, 0]],
                         [[1, 3], [3, 1, 2]], [[2, 0, 1, 3], [3, 1, 0, 2]],
                         [[1, 3, 0], [1, 3]], [[2, 3, 1], [1, 0, 2]],
                         [[1, 2, 0, 3], [0, 2, 1, 3]], [[2], [0, 1, 3]],
                         [[1], [1, 2]], [[1, 0, 2, 3], [3, 0, 1, 2]],
                         [[0, 1, 3, 2], [1, 3, 0, 2]], [[3, 0, 2, 1], [0, 2,
                                                                       3]],
                         [[1, 2, 0], [1, 2, 3]], [[1, 0, 3], [2, 3, 0]],
                         [[2, 3, 0], [3, 1, 0]], [[1, 3], [1, 0]],
                         [[2, 1, 0, 3], [2, 0, 3, 1]], [[3, 2, 0], [2, 1, 0]],
                         [[0, 1, 3], [0, 3, 1]], [[3, 1, 0], [3, 2, 1]],
                         [[3, 2], [3, 1]], [[3], [2, 1, 0]], [[1, 2, 3, 0], []],
                         [[1, 3, 2, 0], [3, 1, 2]], [[1], [0, 2]],
                         [[3, 2, 0], [3, 2, 0]], [[3], []], [[1, 0, 3], [2, 1]],
                         [[3, 1, 0, 2], [2, 3, 1, 0]], [[0, 1], [0, 3, 2]],
                         [[0, 2, 3], [0, 2, 1]], [[1, 3, 0], [3, 0, 2]],
                         [[3, 1, 2], [1, 2, 3]], [[3, 1, 2], [3, 1, 0]],
                         [[0, 3, 1, 2], [3, 2, 1, 0]], [[0, 3], [3, 2, 1]],
                         [[2, 3], [1, 3, 0]], [[0, 3, 2], [2, 0, 3, 1]],
                         [[2, 3], [1, 3]], [[3, 1, 2, 0], [2, 3, 1, 0]],
                         [[1, 0, 3, 2], [3, 0, 1, 2]],
                         [[3, 2, 1, 0], [0, 1, 3, 2]], [[3, 1, 2], [3]],
                         [[0, 1, 3, 2], [2, 3, 0, 1]],
                         [[1, 2, 3, 0], [1, 3, 0, 2]], [3, 1, 2],
                         [[3, 1, 2], [0, 3, 2]], [[2, 3, 0], [1, 2, 0]],
                         [[2, 0, 3], [2, 0]], [[3, 1, 0, 2], [3, 1, 0, 2]],
                         [[0, 1, 2], [2, 0, 1]], [[1, 0, 3], [2, 3, 0]],
                         [[2, 0, 1], [0, 1, 3]], [[2, 1], [0, 1, 3]]]
R
Ruibiao Chen 已提交
148

149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
    def test_dygraph(self):
        paddle.disable_static()
        for axes in self.all_axes:
            for place in self.places:
                x = paddle.to_tensor(self.x, place=place)
                y = paddle.to_tensor(self.y, place=place)
                paddle_res = paddle.tensordot(x, y, axes)
                np_res = tensordot_np(self.x, self.y, axes)
                np.testing.assert_allclose(paddle_res, np_res, rtol=1e-6)

    def test_static(self):
        paddle.enable_static()
        for axes in self.all_axes:
            for place in self.places:
                with paddle.static.program_guard(paddle.static.Program(),
                                                 paddle.static.Program()):
165 166 167 168 169 170
                    x = paddle.static.data(name='x',
                                           shape=self.x_shape,
                                           dtype=self.dtype)
                    y = paddle.static.data(name='y',
                                           shape=self.y_shape,
                                           dtype=self.dtype)
171 172
                    z = paddle.tensordot(x, y, axes)
                    exe = paddle.static.Executor(place)
173 174 175 176
                    paddle_res = exe.run(feed={
                        'x': self.x,
                        'y': self.y
                    },
177 178 179 180 181 182
                                         fetch_list=[z])
                    np_res = tensordot_np(self.x, self.y, axes)
                    np.testing.assert_allclose(paddle_res[0], np_res, rtol=1e-6)


class TestTensordotAPIFloat64(TestTensordotAPI):
183

F
From00 已提交
184 185 186 187
    def set_dtype(self):
        self.dtype = np.float64


R
Ruibiao Chen 已提交
188
class TestTensordotAPIBroadcastCase1(TestTensordotAPIFloat64):
189

R
Ruibiao Chen 已提交
190 191 192 193 194
    def set_input_shape(self):
        self.x_shape = [1, 1, 1, 5]
        self.y_shape = [1, 5, 1, 1]


R
Ruibiao Chen 已提交
195
class TestTensordotAPIBroadcastCase2(TestTensordotAPIFloat64):
196

R
Ruibiao Chen 已提交
197 198 199 200 201
    def set_input_shape(self):
        self.x_shape = [1, 5, 5, 5]
        self.y_shape = [1, 1, 1, 5]


R
Ruibiao Chen 已提交
202
class TestTensordotAPIBroadcastCase3(TestTensordotAPIFloat64):
203

R
Ruibiao Chen 已提交
204 205 206 207 208
    def set_input_shape(self):
        self.x_shape = [5, 5, 5, 1]
        self.y_shape = [5, 5, 1, 5]


R
Ruibiao Chen 已提交
209
class TestTensordotAPIBroadcastCase4(TestTensordotAPIFloat64):
210

R
Ruibiao Chen 已提交
211 212 213 214 215
    def set_input_shape(self):
        self.x_shape = [5, 5, 5, 1]
        self.y_shape = [1, 1, 1, 1]


R
Ruibiao Chen 已提交
216
class TestTensordotAPIBroadcastCase5(TestTensordotAPIFloat64):
217

R
Ruibiao Chen 已提交
218 219 220 221 222
    def set_input_shape(self):
        self.x_shape = [1, 1, 5, 5]
        self.y_shape = [5, 5, 1, 5]


F
From00 已提交
223
class TestTensordotAPIAxesType(TestTensordotAPI):
224

F
From00 已提交
225 226 227 228
    def set_input_shape(self):
        self.x_shape = [3, 4, 4]
        self.y_shape = [4, 4, 5]

R
Ruibiao Chen 已提交
229
    def set_test_axes(self):
F
From00 已提交
230
        self.all_axes = [
231 232
            0, 1, 2, (1, ), [1], ((1, ), ), ([1], ), ((2, 1), (0, )),
            ((1, 2), (0, 1)), ([1, 2], [0, 1]), ([1, 2], [0, 1]),
F
From00 已提交
233 234 235
            [[1, 2], [0, 1]]
        ]

R
Ruibiao Chen 已提交
236
    def test_tensor_axes(self):
F
From00 已提交
237 238
        # The 'axes' with type 'Tensor' in tensordot is not available in static mode
        paddle.disable_static()
R
Ruibiao Chen 已提交
239 240 241
        tensor_axes = [
            paddle.to_tensor([1]), (paddle.to_tensor([1])),
            (paddle.to_tensor([1, 2]), paddle.to_tensor([0, 1])),
242 243
            [paddle.to_tensor([1, 2]),
             paddle.to_tensor([0, 1])],
R
Ruibiao Chen 已提交
244 245 246 247 248 249 250 251 252 253
            paddle.to_tensor([[1, 2], [0, 1]])
        ]

        for place in self.places:
            for axes in tensor_axes:
                x = paddle.to_tensor(self.x, place=place)
                y = paddle.to_tensor(self.y, place=place)
                paddle_res = paddle.tensordot(x, y, axes)
                np_res = tensordot_np(self.x, self.y, axes)
                np.testing.assert_allclose(paddle_res, np_res, rtol=1e-6)
F
From00 已提交
254 255 256 257 258 259 260 261 262 263 264 265 266

    def test_error(self):
        self.all_axes = [[[[0], [1]]], 0.1, -1, 100, [[1, 2], [0, 0]],
                         [[1, 2], [0, -1]], [0, 1, 2, 3]]
        paddle.disable_static()
        x = paddle.to_tensor(self.x)
        y = paddle.to_tensor(self.y)
        for axes in self.all_axes:
            with self.assertRaises(BaseException):
                paddle.tensordot(x, y, axes)


class TestTensordotAPIAxesTypeFloat64(TestTensordotAPIAxesType):
267

F
From00 已提交
268 269 270 271 272 273
    def set_dtype(self):
        self.dtype = np.float64


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