test_addmm_op.py 14.7 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
18
from eager_op_test import OpTest, convert_float_to_uint16
19 20

import paddle
21
from paddle import fluid
22
from paddle.fluid import Program, core, program_guard
23 24 25 26 27 28


class TestAddMMOp(OpTest):
    # test basic
    def setUp(self):
        self.op_type = "addmm"
H
hong 已提交
29
        self.python_api = paddle.addmm
30 31 32 33 34 35 36
        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 = {
37 38
            'Out': self.inputs['Input']
            + np.dot(self.inputs['X'], self.inputs['Y'])
39 40 41
        }

    def init_dtype_type(self):
42
        self.dtype = np.float64
43 44

    def test_check_output(self):
45
        self.check_output()
46 47

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

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

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

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


60 61 62 63 64 65 66 67 68 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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
class TestAddMMFP16Op(TestAddMMOp):
    def init_dtype_type(self):
        self.dtype = np.float16

    def test_check_output(self):
        self.check_output(atol=1e-2)


@unittest.skipIf(
    not core.is_compiled_with_cuda()
    or not core.is_bfloat16_supported(core.CUDAPlace(0)),
    "core is not compiled with CUDA or not support bfloat16",
)
class TestAddMMBF16Op(OpTest):
    def setUp(self):
        self.op_type = "addmm"
        self.python_api = paddle.addmm
        self.init_dtype_type()
        self.inputs = {
            'Input': np.random.random((100, 1)).astype(self.np_dtype),
            'X': np.random.random((100, 10)).astype(self.np_dtype),
            'Y': np.random.random((10, 20)).astype(self.np_dtype),
        }
        self.outputs = {
            'Out': self.inputs['Input']
            + np.dot(self.inputs['X'], self.inputs['Y'])
        }

        self.inputs['Input'] = convert_float_to_uint16(self.inputs['Input'])
        self.inputs['X'] = convert_float_to_uint16(self.inputs['X'])
        self.inputs['Y'] = convert_float_to_uint16(self.inputs['Y'])
        self.outputs['Out'] = convert_float_to_uint16(self.outputs['Out'])
        self.place = core.CUDAPlace(0)

    def init_dtype_type(self):
        self.dtype = np.uint16
        self.np_dtype = np.float32

    def test_check_output(self):
        self.check_output_with_place(self.place)

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

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

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

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


116 117 118 119 120
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 已提交
121

122 123 124 125 126 127 128 129 130
            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()
            )
131
            self.assertRaises(TypeError, paddle.addmm, input, x1, x2)
Y
yaoxuefeng 已提交
132

133
            # The input dtype of mul_op must be float32 or float64.
G
GGBond8488 已提交
134
            input = paddle.static.data(
135 136 137 138
                name='input',
                shape=[4, 4],
                dtype="int32",
            )
G
GGBond8488 已提交
139 140
            x3 = paddle.static.data(name='x3', shape=[4, 4], dtype="int32")
            x4 = paddle.static.data(name='x4', shape=[4, 4], dtype="int32")
141
            self.assertRaises(TypeError, paddle.addmm, input, x3, x4)
Y
yaoxuefeng 已提交
142
            # x and y dimension mismatch
G
GGBond8488 已提交
143
            x5 = paddle.static.data(
144 145 146 147
                name='x5',
                shape=[4, 5],
                dtype="float32",
            )
G
GGBond8488 已提交
148
            x6 = paddle.static.data(
149 150 151 152
                name='x6',
                shape=[4, 4],
                dtype="float32",
            )
Y
yaoxuefeng 已提交
153 154
            self.assertRaises(ValueError, paddle.addmm, input, x5, x6)
            # input and x are not broadcastable
G
GGBond8488 已提交
155
            x7 = paddle.static.data(
156 157 158 159
                name='x7',
                shape=[4, 4],
                dtype="float32",
            )
G
GGBond8488 已提交
160
            x8 = paddle.static.data(
161 162 163 164
                name='x8',
                shape=[4, 4],
                dtype="float32",
            )
G
GGBond8488 已提交
165
            input1 = paddle.static.data(
166 167 168 169
                name='input1',
                shape=[2, 4],
                dtype="float32",
            )
Y
yaoxuefeng 已提交
170 171
            self.assertRaises(ValueError, paddle.addmm, input1, x7, x8)
            # input and x are not broadcastable
G
GGBond8488 已提交
172
            x9 = paddle.static.data(
173 174 175 176
                name='x9',
                shape=[4, 4],
                dtype="float32",
            )
G
GGBond8488 已提交
177
            x10 = paddle.static.data(
178 179 180 181
                name='x10',
                shape=[4, 4],
                dtype="float32",
            )
G
GGBond8488 已提交
182
            input2 = paddle.static.data(
183 184 185 186
                name='input2',
                shape=[1, 2],
                dtype="float32",
            )
Y
yaoxuefeng 已提交
187
            self.assertRaises(ValueError, paddle.addmm, input2, x9, x10)
G
GGBond8488 已提交
188
            x11 = paddle.static.data(
189 190 191 192
                name='x11',
                shape=[4, 4],
                dtype="float32",
            )
G
GGBond8488 已提交
193 194
            x12 = paddle.static.data(name='x12', shape=[4, 4], dtype="float32")
            input3 = paddle.static.data(
195 196 197 198
                name='input3',
                shape=[4, 2],
                dtype="float32",
            )
Y
yaoxuefeng 已提交
199
            self.assertRaises(ValueError, paddle.addmm, input3, x11, x12)
G
GGBond8488 已提交
200
            x13 = paddle.static.data(
201 202 203 204
                name='x13',
                shape=[4, 4],
                dtype="float32",
            )
G
GGBond8488 已提交
205
            x14 = paddle.static.data(
206 207 208 209
                name='x14',
                shape=[4, 4],
                dtype="float32",
            )
G
GGBond8488 已提交
210
            input4 = paddle.static.data(
211 212 213 214
                name='input4',
                shape=[3, 1],
                dtype="float32",
            )
Y
yaoxuefeng 已提交
215
            self.assertRaises(ValueError, paddle.addmm, input4, x13, x14)
216 217 218 219 220 221


class TestAddMMOp2(TestAddMMOp):
    # test alpha and beta
    def setUp(self):
        self.op_type = "addmm"
H
hong 已提交
222
        self.python_api = paddle.addmm
223 224 225 226 227 228 229 230 231 232 233
        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,
        }
234 235 236 237
        self.outputs = {
            'Out': self.attrs['Beta'] * self.inputs['Input']
            + self.attrs['Alpha'] * np.dot(self.inputs['X'], self.inputs['Y'])
        }
238 239 240 241 242 243


class TestAddMMOp3(OpTest):
    # test broadcast
    def setUp(self):
        self.op_type = "addmm"
244
        self.python_api = paddle.addmm
245 246 247 248 249 250 251 252 253 254 255
        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,
        }
256 257 258 259
        self.outputs = {
            'Out': self.attrs['Beta'] * self.inputs['Input']
            + self.attrs['Alpha'] * np.dot(self.inputs['X'], self.inputs['Y'])
        }
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279

    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)


280 281 282 283
class TestAddMMOp4(OpTest):
    # test broadcast
    def setUp(self):
        self.op_type = "addmm"
284
        self.python_api = paddle.addmm
285 286 287
        self.dtype = np.float64
        self.init_dtype_type()
        self.inputs = {
288
            'Input': np.random.random(100).astype(self.dtype),
289 290 291 292 293 294 295
            '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,
        }
296 297 298 299
        self.outputs = {
            'Out': self.attrs['Beta'] * self.inputs['Input']
            + self.attrs['Alpha'] * np.dot(self.inputs['X'], self.inputs['Y'])
        }
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320

    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):
321 322 323 324 325 326 327 328 329 330 331 332 333
    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 已提交
334 335 336 337 338 339
class TestAddMMAPI(unittest.TestCase):
    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)

340
        paddle.disable_static()
Y
yaoxuefeng 已提交
341 342 343

        def test_error1():
            data_x_wrong = np.ones((2, 3)).astype(np.float32)
Z
Zhou Wei 已提交
344 345 346
            x = paddle.to_tensor(data_x_wrong)
            y = paddle.to_tensor(data_y)
            input = paddle.to_tensor(data_input)
347 348 349
            out = paddle.tensor.addmm(
                input=input, x=x, y=y, beta=0.5, alpha=5.0
            )
350

Y
yaoxuefeng 已提交
351
        self.assertRaises(ValueError, test_error1)
352 353

        def test_error2():
354
            data_x_wrong = np.ones(2).astype(np.float32)
355 356 357
            x = paddle.to_tensor(data_x_wrong)
            y = paddle.to_tensor(data_y)
            input = paddle.to_tensor(data_input)
358 359 360
            out = paddle.tensor.addmm(
                input=input, x=x, y=y, beta=0.5, alpha=5.0
            )
361 362 363 364 365 366 367 368

        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)
369 370 371
            out = paddle.tensor.addmm(
                input=input, x=x, y=y, beta=0.5, alpha=5.0
            )
372 373 374 375

        self.assertRaises(ValueError, test_error3)

        def test_error4():
376
            data_input_wrong = np.ones(5).astype(np.float32)
377 378 379
            x = paddle.to_tensor(data_x)
            y = paddle.to_tensor(data_y)
            input = paddle.to_tensor(data_input_wrong)
380 381 382
            out = paddle.tensor.addmm(
                input=input, x=x, y=y, beta=0.5, alpha=5.0
            )
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399

        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)
400 401 402
        paddle_output = paddle.tensor.addmm(
            input=input, x=x, y=y, beta=data_beta, alpha=data_alpha
        )
403
        numpy_output = data_beta * data_input + data_alpha * np.dot(
404 405
            data_x, data_y
        )
406

407 408 409
        np.testing.assert_allclose(
            numpy_output, paddle_output.numpy(), rtol=1e-05
        )
410 411 412 413 414 415

        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)
416
        data_input = np.ones(3).astype(np.float32)
417 418 419 420 421 422 423 424
        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)
425 426 427
        paddle_output = paddle.tensor.addmm(
            input=input, x=x, y=y, beta=data_beta, alpha=data_alpha
        )
428
        numpy_output = data_beta * data_input + data_alpha * np.dot(
429 430
            data_x, data_y
        )
431

432 433 434
        np.testing.assert_allclose(
            numpy_output, paddle_output.numpy(), rtol=1e-05
        )
435 436 437 438 439 440

        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)
441
        data_input = np.ones(1).astype(np.float32)
442 443 444 445 446 447 448 449
        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)
450 451 452
        paddle_output = paddle.tensor.addmm(
            input=input, x=x, y=y, beta=data_beta, alpha=data_alpha
        )
453
        numpy_output = data_beta * data_input + data_alpha * np.dot(
454 455
            data_x, data_y
        )
456

457 458 459
        np.testing.assert_allclose(
            numpy_output, paddle_output.numpy(), rtol=1e-05
        )
460 461 462

        paddle.enable_static()

Y
yaoxuefeng 已提交
463

464
if __name__ == "__main__":
H
hong 已提交
465
    paddle.enable_static()
466
    unittest.main()