test_addmm_op.py 15.2 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 24 25 26 27 28 29
#   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.

from __future__ import print_function

import unittest
import numpy as np
import paddle
import paddle.fluid.core as core
from op_test import OpTest
import paddle.fluid as fluid
from paddle.fluid import Program, program_guard


class TestAddMMOp(OpTest):
    # test basic
    def setUp(self):
        self.op_type = "addmm"
H
hong 已提交
30
        self.python_api = paddle.addmm
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
        self.dtype = np.float64
        self.init_dtype_type()
        self.inputs = {
            'Input': np.random.random((100, 1)).astype(self.dtype),
            'X': np.random.random((100, 10)).astype(self.dtype),
            'Y': np.random.random((10, 20)).astype(self.dtype),
        }
        self.outputs = {
            'Out':
            self.inputs['Input'] + np.dot(self.inputs['X'], self.inputs['Y'])
        }

    def init_dtype_type(self):
        pass

    def test_check_output(self):
H
hong 已提交
47
        self.check_output(check_eager=False)
48 49

    def test_check_grad_normal(self):
H
hong 已提交
50
        self.check_grad(['Input', 'X', 'Y'], 'Out', check_eager=False)
51 52

    def test_check_grad_x(self):
H
hong 已提交
53
        self.check_grad(['X'], 'Out', no_grad_set=None, check_eager=False)
54 55

    def test_check_grad_y(self):
H
hong 已提交
56
        self.check_grad(['Y'], 'Out', no_grad_set=None, check_eager=False)
57 58

    def test_check_grad_input(self):
H
hong 已提交
59
        self.check_grad(['Input'], 'Out', no_grad_set=None, check_eager=False)
60 61 62 63 64 65 66


class TestAddMMOpError(unittest.TestCase):
    # test error
    def test_errors(self):
        with program_guard(Program(), Program()):
            # The input type of addmm_op must be Variable.
Y
yaoxuefeng 已提交
67

68 69 70 71 72 73
            input = fluid.create_lod_tensor(np.array([[-1, -1], [-1, -1]]),
                                            [[2]], fluid.CPUPlace())
            x1 = fluid.create_lod_tensor(np.array([[-1, -1], [-1, -1]]), [[2]],
                                         fluid.CPUPlace())
            x2 = fluid.create_lod_tensor(np.array([[-1, -1], [-1, -1]]), [[2]],
                                         fluid.CPUPlace())
74
            self.assertRaises(TypeError, paddle.addmm, input, x1, x2)
Y
yaoxuefeng 已提交
75

76
            # The input dtype of mul_op must be float32 or float64.
77 78 79 80 81 82 83 84 85 86 87 88
            input = fluid.layers.data(name='input',
                                      shape=[4, 4],
                                      dtype="int32",
                                      append_batch_size=False)
            x3 = fluid.layers.data(name='x3',
                                   shape=[4, 4],
                                   dtype="int32",
                                   append_batch_size=False)
            x4 = fluid.layers.data(name='x4',
                                   shape=[4, 4],
                                   dtype="int32",
                                   append_batch_size=False)
89
            self.assertRaises(TypeError, paddle.addmm, input, x3, x4)
Y
yaoxuefeng 已提交
90
            # x and y dimension mismatch
91 92 93 94 95 96 97 98
            x5 = fluid.layers.data(name='x5',
                                   shape=[4, 5],
                                   dtype="float32",
                                   append_batch_size=False)
            x6 = fluid.layers.data(name='x6',
                                   shape=[4, 4],
                                   dtype="float32",
                                   append_batch_size=False)
Y
yaoxuefeng 已提交
99 100
            self.assertRaises(ValueError, paddle.addmm, input, x5, x6)
            # input and x are not broadcastable
101 102 103 104 105 106 107 108 109 110 111 112
            x7 = fluid.layers.data(name='x7',
                                   shape=[4, 4],
                                   dtype="float32",
                                   append_batch_size=False)
            x8 = fluid.layers.data(name='x8',
                                   shape=[4, 4],
                                   dtype="float32",
                                   append_batch_size=False)
            input1 = fluid.layers.data(name='input1',
                                       shape=[2, 4],
                                       dtype="float32",
                                       append_batch_size=False)
Y
yaoxuefeng 已提交
113 114
            self.assertRaises(ValueError, paddle.addmm, input1, x7, x8)
            # input and x are not broadcastable
115 116 117 118 119 120 121 122 123 124 125 126
            x9 = fluid.layers.data(name='x9',
                                   shape=[4, 4],
                                   dtype="float32",
                                   append_batch_size=False)
            x10 = fluid.layers.data(name='x10',
                                    shape=[4, 4],
                                    dtype="float32",
                                    append_batch_size=False)
            input2 = fluid.layers.data(name='input2',
                                       shape=[1, 2],
                                       dtype="float32",
                                       append_batch_size=False)
Y
yaoxuefeng 已提交
127
            self.assertRaises(ValueError, paddle.addmm, input2, x9, x10)
128 129 130 131 132 133 134 135 136 137 138 139
            x11 = fluid.layers.data(name='x11',
                                    shape=[4, 4],
                                    dtype="float32",
                                    append_batch_size=False)
            x12 = fluid.layers.data(name='x12',
                                    shape=[4, 4],
                                    dtype="float32",
                                    append_batch_size=False)
            input3 = fluid.layers.data(name='input3',
                                       shape=[4, 2],
                                       dtype="float32",
                                       append_batch_size=False)
Y
yaoxuefeng 已提交
140
            self.assertRaises(ValueError, paddle.addmm, input3, x11, x12)
141 142 143 144 145 146 147 148 149 150 151 152
            x13 = fluid.layers.data(name='x13',
                                    shape=[4, 4],
                                    dtype="float32",
                                    append_batch_size=False)
            x14 = fluid.layers.data(name='x14',
                                    shape=[4, 4],
                                    dtype="float32",
                                    append_batch_size=False)
            input4 = fluid.layers.data(name='input4',
                                       shape=[3, 1],
                                       dtype="float32",
                                       append_batch_size=False)
Y
yaoxuefeng 已提交
153
            self.assertRaises(ValueError, paddle.addmm, input4, x13, x14)
154 155 156 157 158 159


class TestAddMMOp2(TestAddMMOp):
    # test alpha and beta
    def setUp(self):
        self.op_type = "addmm"
H
hong 已提交
160
        self.python_api = paddle.addmm
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
        self.dtype = np.float64
        self.init_dtype_type()
        self.inputs = {
            'Input': np.random.random((20, 30)).astype(self.dtype),
            'X': np.random.random((20, 6)).astype(self.dtype),
            'Y': np.random.random((6, 30)).astype(self.dtype),
        }
        self.attrs = {
            'Alpha': 0.1,
            'Beta': 1.0,
        }
        self.outputs = {'Out': self.attrs['Beta'] * self.inputs['Input'] + \
                        self.attrs['Alpha'] * np.dot(self.inputs['X'], self.inputs['Y'])}


class TestAddMMOp3(OpTest):
    # test broadcast
    def setUp(self):
        self.op_type = "addmm"
        self.dtype = np.float64
        self.init_dtype_type()
        self.inputs = {
            'Input': np.random.random((1, 100)).astype(self.dtype),
            'X': np.random.random((20, 10)).astype(self.dtype),
            'Y': np.random.random((10, 100)).astype(self.dtype),
        }
        self.attrs = {
            'Alpha': 0.5,
            'Beta': 2.0,
        }
        self.outputs = {'Out': self.attrs['Beta'] * self.inputs['Input'] + \
                        self.attrs['Alpha'] * np.dot(self.inputs['X'], self.inputs['Y'])}

    def init_dtype_type(self):
        pass

    def test_check_output(self):
        self.check_output()

    def test_check_grad_normal(self):
        self.check_grad(['Input', 'X', 'Y'], 'Out')

    def test_check_grad_x(self):
        self.check_grad(['X'], 'Out', no_grad_set=None)

    def test_check_grad_y(self):
        self.check_grad(['Y'], 'Out', no_grad_set=None)

    def test_check_grad_input(self):
        self.check_grad(['Input'], 'Out', no_grad_set=None)


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
class TestAddMMOp4(OpTest):
    # test broadcast
    def setUp(self):
        self.op_type = "addmm"
        self.dtype = np.float64
        self.init_dtype_type()
        self.inputs = {
            'Input': np.random.random((100)).astype(self.dtype),
            'X': np.random.random((20, 10)).astype(self.dtype),
            'Y': np.random.random((10, 100)).astype(self.dtype),
        }
        self.attrs = {
            'Alpha': 0.5,
            'Beta': 2.0,
        }
        self.outputs = {'Out': self.attrs['Beta'] * self.inputs['Input'] + \
                        self.attrs['Alpha'] * np.dot(self.inputs['X'], self.inputs['Y'])}

    def init_dtype_type(self):
        pass

    def test_check_output(self):
        self.check_output()

    def test_check_grad_normal(self):
        self.check_grad(['Input', 'X', 'Y'], 'Out')

    def test_check_grad_x(self):
        self.check_grad(['X'], 'Out', no_grad_set=None)

    def test_check_grad_y(self):
        self.check_grad(['Y'], 'Out', no_grad_set=None)

    def test_check_grad_input(self):
        self.check_grad(['Input'], 'Out', no_grad_set=None)


class TestAddMMOp5(unittest.TestCase):
251

252 253 254 255 256 257 258 259 260 261 262 263 264
    def test_api_with_dygraph(self):
        np_input = np.random.random((20, 30)).astype(np.float32)
        np_x = np.random.random((20, 6)).astype(np.float32)
        np_y = np.random.random((6, 30)).astype(np.float32)

        with fluid.dygraph.guard():
            input = fluid.dygraph.to_variable(np_input)
            x = fluid.dygraph.to_variable(np_x)
            y = fluid.dygraph.to_variable(np_y)
            out = paddle.tensor.addmm(input, x, y)
            assert np.allclose(np_input + np.dot(np_x, np_y), out.numpy())


Y
yaoxuefeng 已提交
265
class TestAddMMAPI(unittest.TestCase):
266

Y
yaoxuefeng 已提交
267 268 269 270 271
    def test_api_error(self):
        data_x = np.ones((2, 2)).astype(np.float32)
        data_y = np.ones((2, 2)).astype(np.float32)
        data_input = np.ones((2, 2)).astype(np.float32)

272
        paddle.disable_static()
Y
yaoxuefeng 已提交
273 274 275

        def test_error1():
            data_x_wrong = np.ones((2, 3)).astype(np.float32)
Z
Zhou Wei 已提交
276 277 278
            x = paddle.to_tensor(data_x_wrong)
            y = paddle.to_tensor(data_y)
            input = paddle.to_tensor(data_input)
279 280 281 282 283
            out = paddle.tensor.addmm(input=input,
                                      x=x,
                                      y=y,
                                      beta=0.5,
                                      alpha=5.0)
284

Y
yaoxuefeng 已提交
285
        self.assertRaises(ValueError, test_error1)
286 287 288 289 290 291

        def test_error2():
            data_x_wrong = np.ones((2)).astype(np.float32)
            x = paddle.to_tensor(data_x_wrong)
            y = paddle.to_tensor(data_y)
            input = paddle.to_tensor(data_input)
292 293 294 295 296
            out = paddle.tensor.addmm(input=input,
                                      x=x,
                                      y=y,
                                      beta=0.5,
                                      alpha=5.0)
297 298 299 300 301 302 303 304

        self.assertRaises(ValueError, test_error2)

        def test_error3():
            data_input_wrong = np.ones((2, 2, 2)).astype(np.float32)
            x = paddle.to_tensor(data_x)
            y = paddle.to_tensor(data_y)
            input = paddle.to_tensor(data_input_wrong)
305 306 307 308 309
            out = paddle.tensor.addmm(input=input,
                                      x=x,
                                      y=y,
                                      beta=0.5,
                                      alpha=5.0)
310 311 312 313 314 315 316 317

        self.assertRaises(ValueError, test_error3)

        def test_error4():
            data_input_wrong = np.ones((5)).astype(np.float32)
            x = paddle.to_tensor(data_x)
            y = paddle.to_tensor(data_y)
            input = paddle.to_tensor(data_input_wrong)
318 319 320 321 322
            out = paddle.tensor.addmm(input=input,
                                      x=x,
                                      y=y,
                                      beta=0.5,
                                      alpha=5.0)
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339

        self.assertRaises(ValueError, test_error4)

        paddle.enable_static()

    def test_api_normal_1(self):
        data_x = np.ones((2, 2)).astype(np.float32)
        data_y = np.ones((2, 2)).astype(np.float32)
        data_input = np.ones((2, 2)).astype(np.float32)
        data_alpha = 0.1
        data_beta = 1.0

        paddle.disable_static()

        x = paddle.to_tensor(data_x)
        y = paddle.to_tensor(data_y)
        input = paddle.to_tensor(data_input)
340 341 342 343 344 345 346
        paddle_output = paddle.tensor.addmm(input=input,
                                            x=x,
                                            y=y,
                                            beta=data_beta,
                                            alpha=data_alpha)
        numpy_output = data_beta * data_input + data_alpha * np.dot(
            data_x, data_y)
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363

        self.assertEqual(np.allclose(numpy_output, paddle_output.numpy()), True)

        paddle.enable_static()

    def test_api_normal_2(self):
        data_x = np.ones((3, 10)).astype(np.float32)
        data_y = np.ones((10, 3)).astype(np.float32)
        data_input = np.ones((3)).astype(np.float32)
        data_alpha = 0.1
        data_beta = 1.0

        paddle.disable_static()

        x = paddle.to_tensor(data_x)
        y = paddle.to_tensor(data_y)
        input = paddle.to_tensor(data_input)
364 365 366 367 368 369 370
        paddle_output = paddle.tensor.addmm(input=input,
                                            x=x,
                                            y=y,
                                            beta=data_beta,
                                            alpha=data_alpha)
        numpy_output = data_beta * data_input + data_alpha * np.dot(
            data_x, data_y)
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387

        self.assertEqual(np.allclose(numpy_output, paddle_output.numpy()), True)

        paddle.enable_static()

    def test_api_normal_3(self):
        data_x = np.ones((3, 10)).astype(np.float32)
        data_y = np.ones((10, 3)).astype(np.float32)
        data_input = np.ones((1)).astype(np.float32)
        data_alpha = 0.1
        data_beta = 1.0

        paddle.disable_static()

        x = paddle.to_tensor(data_x)
        y = paddle.to_tensor(data_y)
        input = paddle.to_tensor(data_input)
388 389 390 391 392 393 394
        paddle_output = paddle.tensor.addmm(input=input,
                                            x=x,
                                            y=y,
                                            beta=data_beta,
                                            alpha=data_alpha)
        numpy_output = data_beta * data_input + data_alpha * np.dot(
            data_x, data_y)
395 396 397 398 399

        self.assertEqual(np.allclose(numpy_output, paddle_output.numpy()), True)

        paddle.enable_static()

Y
yaoxuefeng 已提交
400

401
if __name__ == "__main__":
H
hong 已提交
402
    paddle.enable_static()
403
    unittest.main()