test_einsum_v2.py 19.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#   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 numpy as np
import unittest
import paddle
from paddle.fluid import core

import os
21

22 23 24 25
os.environ['FLAGS_new_einsum'] = "1"


def error_trans(func, *args, **kargs):
26 27
    """
    transport C++ exception into Python exception.
28 29 30 31 32 33
    because einsum_v2 raise different exception with einsum_v1.
    """
    try:
        out = func(*args, **kargs)
    except ValueError as e:
        if "Same label have different shapes" in str(e):
34 35 36 37
            raise AssertionError(
                "Invalid operands: label i "
                "corresponds to non-broadcastable dimensions."
            )
38 39 40 41 42 43 44 45 46


class TestErrors(unittest.TestCase):
    def setUp(self):
        pass

    def test_diagonalize_errors(self):
        a = np.arange(4 * 3 * 4 * 4).reshape(4, 3, 4, 4).astype('float')
        a = paddle.to_tensor(a)
47 48 49
        with self.assertRaisesRegex(
            AssertionError, ('Duplicate labels are not supported.')
        ):
50
            paddle.einsum('...ii->...i', a)
51 52 53
        with self.assertRaisesRegex(
            AssertionError, ('Duplicate labels are not supported.')
        ):
54
            paddle.einsum('i...i', a)
55 56 57
        with self.assertRaisesRegex(
            AssertionError, ('Duplicate labels are not supported.')
        ):
58 59 60 61 62 63
            paddle.einsum('i...i->i...', a)

    def test_param_errors(self):
        a = np.arange(4 * 3 * 4 * 4).reshape(4, 3, 4, 4).astype('float')
        a = paddle.to_tensor(a)
        with self.assertRaisesRegex(
64 65 66
            AssertionError,
            ("Required at least one operand in Einsum API, but received 0 "),
        ):
67
            paddle.einsum('ijk')
68
        with self.assertRaisesRegex(
69 70
            AssertionError, ('Invalid equation: multiple `->` were found.')
        ):
71
            paddle.einsum('i -> j -> k', a)
72
        with self.assertRaisesRegex(
73 74 75 76 77 78
            AssertionError,
            (
                "Invalid equation: the number of operands is 2, "
                "but found 3 segments in the label equation."
            ),
        ):
79
            paddle.einsum('i,j,k', a, a)
80
        with self.assertRaisesRegex(
81 82 83 84 85 86
            AssertionError,
            (
                "Invalid equation: the number of operands is 2, "
                "but found 1 segments in the label equation."
            ),
        ):
87
            paddle.einsum('ij -> k', a, a)
88
        with self.assertRaisesRegex(
89 90 91 92 93 94
            AssertionError,
            (
                "Invalid equation: the number of operands is 1, "
                "but found 2 segments in the label equation."
            ),
        ):
95
            paddle.einsum('i, -> k', a)
96
        with self.assertRaisesRegex(
97 98 99
            AssertionError,
            ("Invalid equation: the label string '' misses dimensions."),
        ):
100
            paddle.einsum('->', a)
101
        with self.assertRaisesRegex(
102 103 104
            AssertionError,
            ("Invalid equation: the label string 'i' misses dimensions."),
        ):
105
            paddle.einsum('i', a)
106
        with self.assertRaisesRegex(
107 108 109 110 111 112
            AssertionError,
            (
                "Invalid equation: _ is not a valid label, "
                "which should be letters."
            ),
        ):
113
            paddle.einsum('i_', a)
114
        with self.assertRaisesRegex(
115 116 117
            AssertionError,
            ("Invalid equation: `.` is found outside of an ellipsis."),
        ):
118
            paddle.einsum('i..j', a)
119
        with self.assertRaisesRegex(
120 121 122
            AssertionError,
            ("Invalid equation: `.` is found outside of an ellipsis."),
        ):
123
            paddle.einsum('...k...', a)
124
        with self.assertRaisesRegex(
125 126 127
            AssertionError,
            ("Invalid equation: missing ellipsis in output labels."),
        ):
128
            paddle.einsum('i...->i', a)
129
        with self.assertRaisesRegex(
130 131 132
            AssertionError,
            ("Invalid equation: duplicate output labels are found."),
        ):
133
            paddle.einsum('i...->i...i', a)
134
        with self.assertRaisesRegex(
135 136 137 138 139 140
            AssertionError,
            (
                "Invalid operands: label i "
                "corresponds to non-broadcastable dimensions."
            ),
        ):
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
            error_trans(paddle.einsum, 'ij...,ji...', a, a)


class TestEinsum(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        np.random.seed(12345)

        cls.TEST_SAMPLES = {
            "a": np.random.rand(1, 1),
            "b": np.random.rand(1),
            "x": np.random.rand(5),
            "y": np.random.rand(7),
            "A": np.random.rand(4, 5),
            "B": np.random.rand(2, 5),
            "C": np.random.rand(3, 7),
            "D": np.random.rand(3, 4, 5),
            "E": np.random.rand(3, 5, 2),
            "F": np.random.rand(2, 4, 5, 3),
            "G": np.random.rand(4, 2, 5),
            "H": np.random.rand(3, 2, 4),
            "I": np.random.rand(2, 2),
            "J": np.random.rand(1, 3, 5),
            "K": np.random.rand(1, 2, 3, 4),
        }

    def _get_place(self, force_to_use_cpu=False):
        if force_to_use_cpu:
            return core.CPUPlace()
        else:
            if core.is_compiled_with_cuda():
                return core.CUDAPlace(0)
            return core.CPUPlace()

175
    def check_output_equal(self, actual, expect, rtol=1.0e-5, atol=1.0e-8):
176
        error_msg = 'Output has diff at place:{}. \nExpect: {} \nBut Got: {} in class {}'
177 178 179 180 181 182 183 184 185
        np.testing.assert_allclose(
            actual,
            expect,
            rtol=rtol,
            atol=atol,
            err_msg=error_msg.format(
                paddle.get_device(), expect, actual, self.__class__.__name__
            ),
        )
186 187 188 189 190 191 192 193 194 195 196 197

    def setUp(self):
        self.sample = {"paradigm": "i->", "data": ["x"]}

    def test_forward(self):
        operands = [
            TestEinsum.TEST_SAMPLES[operand] for operand in self.sample["data"]
        ]
        expected_result = np.einsum(self.sample["paradigm"], *operands)
        equation = self.sample["paradigm"]

        with paddle.fluid.dygraph.guard(
198 199
            self._get_place(force_to_use_cpu=False)
        ):
200 201 202 203 204 205 206 207 208 209 210 211 212 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 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
            pd_operands = [paddle.to_tensor(operand) for operand in operands]
            result = paddle.einsum(equation, *pd_operands)
            self.check_output_equal(result.numpy(), expected_result)

        with paddle.fluid.dygraph.guard(self._get_place(force_to_use_cpu=True)):
            pd_operands = [paddle.to_tensor(operand) for operand in operands]
            result = paddle.einsum(equation, *pd_operands)
            self.check_output_equal(result.numpy(), expected_result)


class TestEinsumVectorDot(TestEinsum):
    def setUp(self):
        self.sample = {"paradigm": "i,i->", "data": ["x", "x"]}


class TestEinsumVectorMul(TestEinsum):
    def setUp(self):
        self.sample = {"paradigm": "i,i->i", "data": ["x", "x"]}


class TestEinsumVectorOuter(TestEinsum):
    def setUp(self):
        self.sample = {"paradigm": "i,j->ij", "data": ["x", "y"]}


class TestEinsumMatrixTranspose(TestEinsum):
    def setUp(self):
        self.sample = {"paradigm": "ij->ji", "data": ["A"]}


class TestEinsumMatrixRowSum(TestEinsum):
    def setUp(self):
        self.sample = {"paradigm": "ij->j", "data": ["A"]}


class TestEinsumMatrixColSum(TestEinsum):
    def setUp(self):
        self.sample = {"paradigm": "ij->i", "data": ["A"]}


class TestEinsumMatrixEleMul(TestEinsum):
    def setUp(self):
        self.sample = {"paradigm": "ij,ij->ij", "data": ["A", "A"]}


class TestEinsumDegenerateMatrixVecMul(TestEinsum):
    def setUp(self):
        self.sample = {"paradigm": "ij,j", "data": ["a", "b"]}


class TestEinsumMatrixVecMul(TestEinsum):
    def setUp(self):
        self.sample = {"paradigm": "ij,j->i", "data": ["A", "x"]}


class TestEinsumMatrixMul(TestEinsum):
    def setUp(self):
        self.sample = {"paradigm": "ij,kj->ik", "data": ["A", "B"]}


class TestEinsumMatrixOuter(TestEinsum):
    def setUp(self):
        self.sample = {"paradigm": "ij,kl->ijkl", "data": ["A", "C"]}


class TestEinsumTensorBMM(TestEinsum):
    def setUp(self):
        self.sample = {"paradigm": "bij,bjk->bik", "data": ["D", "E"]}


class TestEinsumTensorContract1(TestEinsum):
    def setUp(self):
        self.sample = {"paradigm": "ijk,jk->i", "data": ["D", "A"]}


class TestEinsumTensorContract2(TestEinsum):
    def setUp(self):
        self.sample = {"paradigm": "ijk,lk->ijl", "data": ["D", "B"]}


class TestEinsumTensorContract3(TestEinsum):
    def setUp(self):
        self.sample = {"paradigm": "abcd,dfg->abcfg", "data": ["F", "D"]}


class TestEinsumTensorContract4(TestEinsum):
    def setUp(self):
        self.sample = {"paradigm": "ijk,jk->ik", "data": ["D", "A"]}


class TestEinsumTensorContract5(TestEinsum):
    def setUp(self):
        self.sample = {"paradigm": "ijk,jk->ij", "data": ["D", "A"]}


class TestEinsumTensorContract6(TestEinsum):
    def setUp(self):
        self.sample = {"paradigm": "ik, ijk->j", "data": ["A", "G"]}


class TestEinsumTensorContract7(TestEinsum):
    def setUp(self):
        self.sample = {"paradigm": "ijk, ik->jk", "data": ["G", "A"]}


class TestEinsumEllipsis1(TestEinsum):
    def setUp(self):
        self.sample = {"paradigm": "i...->...", "data": ["G"]}


class TestEinsumEllipsis2(TestEinsum):
    def setUp(self):
        self.sample = {"paradigm": "ij,...i->j...", "data": ["A", "H"]}


class TestEinsumEllipsis3(TestEinsum):
    def setUp(self):
        self.sample = {"paradigm": "k...,jk", "data": ["F", "I"]}


class TestEinsumTestEinsumBilinear(TestEinsum):
    def setUp(self):
        self.sample = {"paradigm": "bn,anm,bm->ba", "data": ["B", "E", "I"]}


class TestEinsumTestEinsumOthers1(TestEinsum):
    def setUp(self):
        self.sample = {"paradigm": "ijkl, lmn->kmn", "data": ["F", "H"]}


class TestEinsumTestEinsumOthers2(TestEinsum):
    def setUp(self):
        self.sample = {"paradigm": "ijkl, lmn->ijn", "data": ["F", "H"]}


class TestEinsumBatch1(TestEinsum):
    def setUp(self):
        self.sample = {"paradigm": "blq,bhlk->bhlqk", "data": ["J", "K"]}


class TestNumpyTests(unittest.TestCase):
    def setUp(self):
        pass

    def _get_place(self, force_to_use_cpu=False):
        if force_to_use_cpu:
            return core.CPUPlace()
        else:
            if core.is_compiled_with_cuda():
                return core.CUDAPlace(0)
            return core.CPUPlace()

352
    def check_output_equal(self, actual, expect, rtol=1.0e-5, atol=1.0e-8):
353
        error_msg = 'Output has diff at place:{}. \nExpect: {} \nBut Got: {} in class {}'
354 355 356 357 358 359 360 361 362
        np.testing.assert_allclose(
            actual,
            expect,
            rtol=rtol,
            atol=atol,
            err_msg=error_msg.format(
                paddle.get_device(), expect, actual, self.__class__.__name__
            ),
        )
363 364 365 366

    def check_output(self, eqn, *ops):
        expect = np.einsum(eqn, *ops)
        with paddle.fluid.dygraph.guard(
367 368
            self._get_place(force_to_use_cpu=False)
        ):
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
            pd_operands = [paddle.to_tensor(op) for op in ops]
            actual = paddle.einsum(eqn, *pd_operands)
            self.check_output_equal(actual.numpy(), expect)

    def test_sums(self):
        for n in range(1, 17):
            a = np.arange(n).astype('float')
            self.check_output("i->", a)

        for n in range(1, 17):
            a = np.arange(2 * 3 * n).reshape(2, 3, n).astype('float')
            self.check_output("...i->...", a)

        for n in range(1, 17):
            a = np.arange(2 * n).reshape(2, n).astype('float')
            self.check_output("i...->...", a)

        for n in range(1, 17):
            a = np.arange(2 * 3 * n).reshape(2, 3, n).astype('float')
            self.check_output("i...->...", a)

        for n in range(1, 17):
            a = np.arange(3 * n).reshape(3, n).astype('float')
            b = np.arange(2 * 3 * n).reshape(2, 3, n).astype('float')
            self.check_output("..., ...", a, b)

        for n in range(1, 17):
            a = np.arange(2 * 3 * n).reshape(2, 3, n).astype('float')
            b = np.arange(n).astype('float')
            self.check_output("...i, ...i", a, b)

        for n in range(1, 11):
            a = np.arange(n * 3 * 2).reshape(n, 3, 2).astype('float')
            b = np.arange(n).astype('float')
            self.check_output("i..., i...", a, b)

        for n in range(1, 17):
            a = (np.arange(3) + 1).astype('float')
            b = (np.arange(n) + 1).astype('float')
            self.check_output("i,j", a, b)

        for n in range(1, 17):
            a = np.arange(4 * n).reshape(4, n).astype('float')
            b = np.arange(n).astype('float')
            self.check_output("ij, j", a, b)

        for n in range(1, 17):
            a = np.arange(4 * n).reshape(4, n).astype('float')
            b = np.arange(n).astype('float')
            self.check_output("ji,j", a.T, b.T)

        for n in range(1, 17):
            a = np.arange(4 * n).reshape(4, n).astype('float')
            b = np.arange(n * 6).reshape(n, 6).astype('float')
            self.check_output("ij,jk", a, b)

        a = np.arange(12).reshape(3, 4).astype('float')
        b = np.arange(20).reshape(4, 5).astype('float')
        c = np.arange(30).reshape(5, 6).astype('float')
        self.check_output("ij,jk,kl", a, b, c)

        a = np.arange(60).reshape(3, 4, 5).astype('float')
        b = np.arange(24).reshape(4, 3, 2).astype('float')
        self.check_output("ijk, jil -> kl", a, b)

        for n in range(1, 25):
            a = np.arange(n).astype('float')
            self.check_output("...,...", a, a)
            self.check_output("i,i", a, a)

        # TODO(@xiongkun): explict broadcast in EinsumOp is not supported, it's not recommend to use einsum like this.
440 441 442
        # p = np.ones((10, 2)).astype('float')
        # q = np.ones((1, 2)).astype('float')
        # self.check_output('ij,ij->j', p, q)
443 444

        # TODO(@xiongkun): explict-label-broadcast in EinsumOp is not supported, it's not recommend to use einsum like this.
445 446 447
        # x = np.array([2., 3.]).astype('float')
        # y = np.array([4.]).astype('float')
        # self.check_output("i, i", x, y)
448 449

        # TODO(@xiongkun): explict-label-broadcast in EinsumOp is not supported, it's not recommend to use einsum like this.
450 451 452 453
        # p = np.ones((1, 5)) / 2
        # q = np.ones((5, 5)) / 2
        # self.check_output("...ij,...jk->...ik", p, p)
        # self.check_output("...ij,...jk->...ik", p, q)
454 455 456 457 458 459 460 461 462 463

        x = np.eye(2).astype('float')
        y = np.ones(2).astype('float')
        self.check_output("ji,i->", x, y)
        self.check_output("i,ij->", y, x)
        self.check_output("ij,i->", x, y)

    def test_large_nops(self):
        pass
        # TODO(@xiongkun): explict broadcast in EinsumOp is not supported, it's not recommend to use einsum like this.
464 465 466 467 468
        # a = np.arange(4 * 3 * 1 * 4).reshape(4, 3, 1, 4).astype('float')
        # self.check_output('a...b,b...c,c...d', a, a, a)
        # self.check_output('a...b,b...c,c...a', a, a, a)
        # self.check_output('a...b,b...c,c...a', a, a, a)
        # self.check_output('...ab,...ba,...ab,...ab', a, a, a, a)
469 470 471 472 473 474 475 476 477 478 479

    def test_static_graph(self):
        paddle.enable_static()
        fluid = paddle.fluid
        if fluid.core.is_compiled_with_cuda():
            self.place = fluid.CUDAPlace(0)
        else:
            self.place = fluid.CPUPlace()
        main = fluid.Program()
        startup = fluid.Program()
        with fluid.program_guard(main, startup):
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
            a = paddle.static.data(
                name='a', shape=[3, None, None, None], dtype='float'
            )
            b = paddle.static.data(
                name='b', shape=[2, None, None, None], dtype='float'
            )
            c = paddle.static.data(
                name='c', shape=[None, None, 2, None], dtype='float'
            )
            d = paddle.static.data(
                name='d', shape=[None, None, 5], dtype='float'
            )
            e = paddle.static.data(
                name='e', shape=[None, 2, None], dtype='float'
            )
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520

            outs = []
            outs.append(paddle.einsum("ibnd,jbnd->bnij", a, b))
            outs.append(paddle.einsum('...ik, ...j', c, d))
            outs.append(paddle.einsum('...kj, ...ik', d, e))
            outs.append(paddle.einsum('ijk..., ikj', c, e))
            outs.append(paddle.einsum('ijk..., ikj->...ij', c, e))
        exe = fluid.Executor(self.place)
        exe.run(startup)
        a = np.arange(72).reshape(3, 2, 3, 4).astype('float')
        b = np.arange(48).reshape(2, 2, 3, 4).astype('float')
        c = np.arange(48).reshape(2, 3, 2, 4).astype('float')
        d = np.arange(30).reshape(2, 3, 5).astype('float')
        e = np.arange(12).reshape(2, 2, 3).astype('float')
        feeds = {'a': a, 'b': b, 'c': c, 'd': d, 'e': e}
        actual = exe.run(main, feed=feeds, fetch_list=[outs])
        expect = []
        expect.append(np.einsum("ibnd,jbnd->bnij", a, b))
        expect.append(np.einsum('...ik, ...j', c, d))
        expect.append(np.einsum('...kj, ...ik', d, e))
        expect.append(np.einsum('ijk..., ikj', c, e))
        expect.append(np.einsum('ijk..., ikj->...ij', c, e))
        for a, e in zip(actual, expect):
            self.check_output_equal(a, e)


521 522 523 524 525 526 527 528 529 530 531 532 533 534
class TestStaticGraphShape(unittest.TestCase):
    def setUp(self):
        paddle.enable_static()

    def tearDown(self):
        paddle.disable_static()

    def test_shape(self):
        A = paddle.static.data(name='x', shape=[-1])
        B = paddle.static.data(name='y', shape=[384])
        C = paddle.einsum('i,d->id', A, B)
        self.assertEqual(C.shape, (-1, 384))


535 536 537 538 539
@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 the bfloat16",
)
540 541 542 543 544 545
class TestBF16(unittest.TestCase):
    """
    EinsumOp support bfloat16 type, add unittest here for the correctness.
    """

    def test_shape(self):
L
Leo Chen 已提交
546 547
        cuda_major = paddle.version.cuda().split('.')[0].strip()
        if int(cuda_major) >= 11:
548
            """MatmulKernel support bfloat16 only if cuda_major > 11.0."""
549 550 551 552 553
            A = paddle.to_tensor(np.array([1.0, 2.0])).astype(paddle.bfloat16)
            A = A.cuda()
            B = paddle.to_tensor(np.array([2.0, 3.0])).astype(paddle.bfloat16)
            B = B.cuda()
            C = paddle.einsum('i,i->', A, B)
L
Leo Chen 已提交
554 555
            D = paddle.to_tensor(8.0).astype(paddle.bfloat16)
            self.assertEqual(C.item(), D.item())
556 557


X
xiongkun 已提交
558 559 560 561 562 563 564 565 566 567 568 569 570 571
class TestComplex(unittest.TestCase):
    """
    EinsumOp support Complex type
    """

    def test_shape(self):
        a = paddle.rand([4, 4])
        b = paddle.rand([4, 4])
        c = paddle.einsum('xy,yz->xz', a, b)
        a = paddle.cast(a, 'complex64')
        b = paddle.cast(b, 'complex64')
        c = paddle.einsum('xy,yz->xz', a, b)


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