test_imperative_triple_grad.py 39.0 KB
Newer Older
W
Weilong Wu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# 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 unittest
from unittest import TestCase
17

W
Weilong Wu 已提交
18
import numpy as np
19 20 21 22

import paddle
import paddle.fluid as fluid
from paddle.fluid.wrapped_decorator import wrap_decorator
W
Weilong Wu 已提交
23 24 25 26


def _dygraph_guard_(func):
    def __impl__(*args, **kwargs):
J
Jiabin Yang 已提交
27
        if fluid._non_static_mode():
W
Weilong Wu 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
            return func(*args, **kwargs)
        else:
            with fluid.dygraph.guard():
                return func(*args, **kwargs)

    return __impl__


dygraph_guard = wrap_decorator(_dygraph_guard_)


def random_var(size, low=-1, high=1, dtype='float32'):
    np.random.seed(2021)
    x_np = np.random.uniform(low=low, high=high, size=size).astype(dtype)
    return fluid.dygraph.to_variable(x_np)


45 46 47
class TestDygraphTripleGradMatmul(TestCase):
    def test_matmul_triple_grad(self):
        input_numpy = np.ones([3, 3]) * 2
48 49 50
        x = paddle.to_tensor(input_numpy, stop_gradient=False, dtype='float32')
        y = paddle.to_tensor(input_numpy, stop_gradient=False, dtype='float32')
        out = paddle.matmul(x, y, False, False)
51

52 53 54 55 56 57
        new_out_g = paddle.to_tensor(
            np.ones([3, 3]), stop_gradient=False, dtype='float32'
        )
        new_x_g, new_y_g = paddle.grad(
            [out], [x, y], [new_out_g], retain_graph=True, create_graph=True
        )
58

59 60 61 62 63 64 65 66 67 68 69 70 71
        new_x_g_g = paddle.to_tensor(
            np.ones([3, 3]), stop_gradient=False, dtype='float32'
        )
        new_y_g_g = paddle.to_tensor(
            np.ones([3, 3]), stop_gradient=False, dtype='float32'
        )
        new_a, new_b, new_c = paddle.grad(
            [new_x_g, new_y_g],
            [x, y, new_out_g],
            [new_x_g_g, new_y_g_g],
            retain_graph=True,
            create_graph=True,
        )
72

73
        new_a.backward()
74

75 76
        out_ref = np.ones([3, 3]) * 12.0
        np.testing.assert_array_equal(out.numpy(), out_ref)
77

78 79 80 81
        new_x_g_ref = np.ones([3, 3]) * 6.0
        new_y_g_ref = np.ones([3, 3]) * 6.0
        np.testing.assert_array_equal(new_x_g.numpy(), new_x_g_ref)
        np.testing.assert_array_equal(new_y_g.numpy(), new_y_g_ref)
82

83 84 85
        new_a_ref = np.ones([3, 3]) * 3.0
        new_b_ref = np.ones([3, 3]) * 3.0
        new_c_ref = np.ones([3, 3]) * 12.0
86

87 88 89
        np.testing.assert_array_equal(new_a.numpy(), new_a_ref)
        np.testing.assert_array_equal(new_b.numpy(), new_b_ref)
        np.testing.assert_array_equal(new_c.numpy(), new_c_ref)
90

91
        x_grad_ref = np.ones([3, 3]) * 0.0
92
        assert x.grad is None
93

94
        y_grad_ref = np.ones([3, 3]) * 0.0
95
        assert y.grad is None
96

97 98
        new_out_g_ref = np.ones([3, 3]) * 3.0
        np.testing.assert_array_equal(new_out_g.grad.numpy(), new_out_g_ref)
99

100 101
        new_x_g_g_ref = np.ones([3, 3]) * 0.0
        new_y_g_g_ref = np.ones([3, 3]) * 3.0
102
        assert new_x_g_g.grad is None
103
        np.testing.assert_array_equal(new_y_g_g.grad.numpy(), new_y_g_g_ref)
104 105


W
Weilong Wu 已提交
106 107 108 109 110
class TestDygraphTripleGrad(TestCase):
    def setUp(self):
        self.sort_sum_gradient = False
        self.shape = [5, 5]

111 112 113 114 115 116 117 118 119 120
    def grad(
        self,
        outputs,
        inputs,
        grad_outputs=None,
        no_grad_vars=None,
        retain_graph=None,
        create_graph=False,
        allow_unused=False,
    ):
W
Weilong Wu 已提交
121
        fluid.set_flags({'FLAGS_sort_sum_gradient': self.sort_sum_gradient})
122 123 124 125 126 127 128 129 130
        return fluid.dygraph.grad(
            outputs=outputs,
            inputs=inputs,
            grad_outputs=grad_outputs,
            no_grad_vars=no_grad_vars,
            retain_graph=retain_graph,
            create_graph=create_graph,
            allow_unused=allow_unused,
        )
W
Weilong Wu 已提交
131 132

    @dygraph_guard
133
    def func_exception(self):
W
Weilong Wu 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
        with self.assertRaises(AssertionError):
            self.grad(None, None)

        shape = self.shape

        with self.assertRaises(AssertionError):
            self.grad(1, random_var(shape))

        with self.assertRaises(AssertionError):
            self.grad(random_var(shape), 1)

        with self.assertRaises(AssertionError):
            self.grad([1], [random_var(shape)])

        with self.assertRaises(AssertionError):
            self.grad([random_var(shape)], [1])

        with self.assertRaises(AssertionError):
152 153 154 155 156
            self.grad(
                [random_var(shape), random_var(shape)],
                [random_var(shape)],
                [random_var(shape)],
            )
W
Weilong Wu 已提交
157 158

        with self.assertRaises(AssertionError):
159 160 161
            self.grad(
                [random_var(shape)], [random_var(shape)], no_grad_vars=[1]
            )
W
Weilong Wu 已提交
162 163 164 165 166

        with self.assertRaises(AssertionError):
            self.grad([random_var(shape)], [random_var(shape)], no_grad_vars=1)

    @dygraph_guard
167
    def func_example_with_gradient_and_create_graph(self):
W
Weilong Wu 已提交
168
        x = random_var(self.shape)
姜永久 已提交
169
        x.retain_grads()
W
Weilong Wu 已提交
170 171 172 173 174 175 176 177 178 179 180 181
        x_np = x.numpy()
        x.stop_gradient = False

        y = random_var(self.shape)
        y_np = y.numpy()
        y.stop_gradient = False

        z = random_var(self.shape)
        z_np = z.numpy()
        numel = z_np.size
        z.stop_gradient = False

182
        out = paddle.nn.functional.sigmoid(paddle.matmul(x, y) + z)
W
Weilong Wu 已提交
183 184
        out_np = out.numpy()

185
        (dx_actual,) = self.grad([out], [x], create_graph=True)
W
Weilong Wu 已提交
186 187
        # Theoritical result based on math calculation
        dout = np.ones(self.shape).astype('float32')
188 189 190
        dx_expected = np.matmul(
            dout * out_np * (1 - out_np), np.transpose(y_np)
        )
191
        np.testing.assert_allclose(dx_actual.numpy(), dx_expected, rtol=1e-05)
W
Weilong Wu 已提交
192

193
        (ddx_actual,) = self.grad([dx_actual], [x], create_graph=True)
W
Weilong Wu 已提交
194 195 196
        # Theoritical result based on math calculation
        DDY = np.zeros(self.shape).astype('float32')
        DDX = np.ones(self.shape).astype('float32')
197 198 199
        double_grad_tmp1 = np.matmul(
            dout * out_np * (1 - out_np), np.transpose(DDY)
        )
W
Weilong Wu 已提交
200 201
        double_grad_tmp2 = np.matmul(DDX, y_np) + np.matmul(x_np, DDY)
        double_grad_tmp3 = (
202 203 204 205 206
            (1 - 2 * out_np) * dout * double_grad_tmp2 * out_np * (1 - out_np)
        )
        ddx_expected = double_grad_tmp1 + np.matmul(
            double_grad_tmp3, np.transpose(y_np)
        )
207
        np.testing.assert_allclose(ddx_actual.numpy(), ddx_expected, rtol=1e-05)
W
Weilong Wu 已提交
208 209 210 211 212

        # Theoritical result based on math calculation
        d_ddout = np.zeros(self.shape).astype('float32')
        tmp0 = np.matmul(DDX, y_np) + np.matmul(x_np, DDY)
        tmp1 = (1 - 2 * out_np) * ((1 - 2 * out_np) * dout * tmp0 * tmp0)
213 214 215 216 217 218 219
        tmp2 = (
            tmp0 * (1 - 2 * out_np) * d_ddout
            - 2 * dout * (1 - out_np) * out_np * tmp0 * tmp0
        )
        dddx_expected = np.matmul(
            ((tmp1 + tmp2) * out_np * (1 - out_np)), np.transpose(y_np)
        )
W
Weilong Wu 已提交
220 221 222

        ddx_actual.backward()
        dddx_grad_actual = x.gradient()
223
        np.testing.assert_allclose(dddx_grad_actual, dddx_expected, rtol=1e-05)
W
Weilong Wu 已提交
224

225
    def test_all_cases(self):
226 227
        self.func_exception()
        self.func_example_with_gradient_and_create_graph()
228

W
Weilong Wu 已提交
229

230 231 232 233 234 235 236
class TestDygraphTripleGradBradcastCase(TestCase):
    def setUp(self):
        self.sort_sum_gradient = False
        self.x_shape = [3, 2, 2]
        self.y_shape = [1, 2, 2]
        self.z_shape = [2, 2]

237 238 239 240 241 242 243 244 245 246
    def grad(
        self,
        outputs,
        inputs,
        grad_outputs=None,
        no_grad_vars=None,
        retain_graph=None,
        create_graph=False,
        allow_unused=False,
    ):
247
        fluid.set_flags({'FLAGS_sort_sum_gradient': self.sort_sum_gradient})
248 249 250 251 252 253 254 255 256
        return fluid.dygraph.grad(
            outputs=outputs,
            inputs=inputs,
            grad_outputs=grad_outputs,
            no_grad_vars=no_grad_vars,
            retain_graph=retain_graph,
            create_graph=create_graph,
            allow_unused=allow_unused,
        )
257 258

    @dygraph_guard
259
    def func_example_with_gradient_and_create_graph(self):
260
        x = random_var(self.x_shape)
姜永久 已提交
261
        x.retain_grads()
262 263 264 265 266 267 268 269 270 271 272 273
        x_np = x.numpy()
        x.stop_gradient = False

        y = random_var(self.y_shape)
        y_np = y.numpy()
        y.stop_gradient = False

        z = random_var(self.z_shape)
        z_np = z.numpy()
        numel = z_np.size
        z.stop_gradient = False

274
        out = paddle.nn.functional.sigmoid(paddle.matmul(x, y) + z)
275 276
        out_np = out.numpy()

277
        (dx_actual,) = self.grad([out], [x], create_graph=True)
278 279
        # Theoritical result based on math calculation
        dout = np.ones(self.x_shape).astype('float32')
280 281 282
        dx_expected = np.matmul(
            dout * out_np * (1 - out_np), np.transpose(y_np, axes=(0, 2, 1))
        )
283
        np.testing.assert_allclose(dx_actual.numpy(), dx_expected, rtol=1e-05)
284

285
        (ddx_actual,) = self.grad([dx_actual], [x], create_graph=True)
286 287 288
        # Theoritical result based on math calculation
        DDY = np.zeros(self.y_shape).astype('float32')
        DDX = np.ones(self.x_shape).astype('float32')
289 290 291
        double_grad_tmp1 = np.matmul(
            dout * out_np * (1 - out_np), np.transpose(DDY, axes=(0, 2, 1))
        )
292 293
        double_grad_tmp2 = np.matmul(DDX, y_np) + np.matmul(x_np, DDY)
        double_grad_tmp3 = (
294 295
            (1 - 2 * out_np) * dout * double_grad_tmp2 * out_np * (1 - out_np)
        )
296
        ddx_expected = double_grad_tmp1 + np.matmul(
297 298
            double_grad_tmp3, np.transpose(y_np, axes=(0, 2, 1))
        )
299
        np.testing.assert_allclose(ddx_actual.numpy(), ddx_expected, rtol=1e-05)
300 301 302 303 304

        # Theoritical result based on math calculation
        d_ddout = np.zeros(self.x_shape).astype('float32')
        tmp0 = np.matmul(DDX, y_np) + np.matmul(x_np, DDY)
        tmp1 = (1 - 2 * out_np) * ((1 - 2 * out_np) * dout * tmp0 * tmp0)
305 306 307 308 309 310 311 312
        tmp2 = (
            tmp0 * (1 - 2 * out_np) * d_ddout
            - 2 * dout * (1 - out_np) * out_np * tmp0 * tmp0
        )
        dddx_expected = np.matmul(
            ((tmp1 + tmp2) * out_np * (1 - out_np)),
            np.transpose(y_np, axes=(0, 2, 1)),
        )
313 314 315

        ddx_actual.backward()
        dddx_grad_actual = x.gradient()
316
        np.testing.assert_allclose(dddx_grad_actual, dddx_expected, rtol=1e-05)
317

318
    def test_all_cases(self):
319
        self.func_example_with_gradient_and_create_graph()
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 352 353 354 355 356 357 358 359 360 361
# d_ddout is none, dtype is float32
class TestDygraphTripleGradMatmulcase1(TestCase):
    def setUp(self):
        self.input_numpy_x = None
        self.input_numpy_y = None
        self.input_numpy_dout = None
        self.input_numpy_ddx = None
        self.input_numpy_ddy = None
        self.places = ["cpu"]
        if paddle.is_compiled_with_cuda():
            self.places.append("gpu")

    def actual(self):
        x = paddle.to_tensor(
            self.input_numpy_x, stop_gradient=False, dtype='float32'
        )
        y = paddle.to_tensor(
            self.input_numpy_y, stop_gradient=False, dtype='float32'
        )
        out = paddle.matmul(x, y, False, False)

        dout = paddle.to_tensor(
            self.input_numpy_dout, stop_gradient=False, dtype='float32'
        )
        (dx, dy) = paddle.grad(
            [out], [x, y], [dout], retain_graph=True, create_graph=True
        )
        ddx = paddle.to_tensor(
            self.input_numpy_ddx, stop_gradient=False, dtype='float32'
        )
        ddy = paddle.to_tensor(
            self.input_numpy_ddy, stop_gradient=False, dtype='float32'
        )
        dx_double_grad, dy_double_grad = paddle.grad(
            [dx, dy],
            [x, y],
            [ddx, ddy],
            retain_graph=True,
            create_graph=True,
        )
362 363
        # d_x, d_y should be none because ddd_out = None
        d_dout, d_ddx, d_ddy = paddle.grad(
364
            [dx_double_grad, dy_double_grad],
365
            [dout, ddx, ddy],
366 367 368
            retain_graph=False,
            create_graph=False,
        )
369
        return d_dout, d_ddx, d_ddy
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 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488

    # case1: d_ddout is none, dims != 1
    def test_matmul_triple_grad_case1(self):
        def init_data():
            self.input_numpy_x = np.random.random([3, 3]).astype('float32')
            self.input_numpy_y = np.random.random([3, 3]).astype('float32')
            self.input_numpy_dout = np.ones([3, 3], dtype="float32")
            self.input_numpy_ddx = np.ones([3, 3], dtype="float32")
            self.input_numpy_ddy = np.ones([3, 3], dtype="float32")

        init_data()
        d_dout_expected = np.ones([3, 3], dtype="float32") * 6
        d_ddx_expected = np.ones([3, 3], dtype="float32") * 3
        d_ddy_expected = np.ones([3, 3], dtype="float32") * 3
        expected_results = (
            d_dout_expected,
            d_ddx_expected,
            d_ddy_expected,
        )

        for place in self.places:
            paddle.device.set_device(place)
            actual_results = self.actual()
            for expected_result, actual_result in zip(
                expected_results, actual_results
            ):
                np.testing.assert_allclose(
                    expected_result, actual_result, rtol=1e-6
                )

    # case2: d_ddout is none, dims = 1
    def test_matmul_triple_grad_case2(self):
        def init_data():
            self.input_numpy_x = np.random.random(
                [
                    3,
                ]
            ).astype('float32')
            self.input_numpy_y = np.random.random(
                [
                    3,
                ]
            ).astype('float32')
            self.input_numpy_dout = np.ones([1], dtype="float32")
            self.input_numpy_ddx = np.ones([3], dtype="float32")
            self.input_numpy_ddy = np.ones([3], dtype="float32")

        init_data()
        d_dout_expected = np.ones([1], dtype="float32") * 6
        d_ddx_expected = np.ones(
            [
                3,
            ],
            dtype="float32",
        )
        d_ddy_expected = np.ones(
            [
                3,
            ],
            dtype="float32",
        )
        expected_results = (
            d_dout_expected,
            d_ddx_expected,
            d_ddy_expected,
        )

        for place in self.places:
            paddle.device.set_device(place)
            actual_results = self.actual()
            for expected_result, actual_result in zip(
                expected_results, actual_results
            ):
                np.testing.assert_allclose(
                    expected_result, actual_result, rtol=1e-6
                )

    # case3: d_ddout is none , with broadcast
    def test_matmul_triple_grad_case3(self):
        def init_data():
            self.input_numpy_x = np.random.random([3, 1]).astype('float32')
            self.input_numpy_y = np.random.random(
                [
                    1,
                ]
            ).astype('float32')
            self.input_numpy_dout = np.ones([3], dtype="float32")
            self.input_numpy_ddx = np.ones([3, 1], dtype="float32")
            self.input_numpy_ddy = np.ones([1], dtype="float32")

        init_data()
        d_dout_expected = (
            np.ones(
                [
                    3,
                ],
                dtype="float32",
            )
            * 2
        )
        d_ddx_expected = np.ones([3, 1], dtype="float32")
        d_ddy_expected = np.ones([1], dtype="float32") * 3
        expected_results = (
            d_dout_expected,
            d_ddx_expected,
            d_ddy_expected,
        )

        for place in self.places:
            paddle.device.set_device(place)
            actual_results = self.actual()
            for expected_result, actual_result in zip(
                expected_results, actual_results
            ):
                np.testing.assert_allclose(
                    expected_result, actual_result, rtol=1e-6
                )


489
'''
490 491 492 493 494 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 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
# d_ddout is none, dtype is complex64
class TestDygraphTripleGradMatmulcase2(TestCase):
    def setUp(self):
        self.input_numpy_x = None
        self.input_numpy_y = None
        self.input_numpy_dout = None
        self.input_numpy_ddx = None
        self.input_numpy_ddy = None
        self.input_numpy_ddx_conj = None
        self.input_numpy_ddy_conj = None
        self.input_numpy_dout_conj = None
        self.places = ["cpu"]
        if paddle.is_compiled_with_cuda():
            self.places.append("gpu")

    def actual(self):
        x = paddle.to_tensor(
            self.input_numpy_x, stop_gradient=False, dtype='complex64'
        )
        y = paddle.to_tensor(
            self.input_numpy_y, stop_gradient=False, dtype='complex64'
        )
        out = paddle.matmul(x, y, False, False)

        dout = paddle.to_tensor(
            self.input_numpy_dout, stop_gradient=False, dtype='complex64'
        )
        (dx, dy) = paddle.grad(
            [out], [x, y], [dout], retain_graph=True, create_graph=True
        )
        ddx = paddle.to_tensor(
            self.input_numpy_ddx, stop_gradient=False, dtype='complex64'
        )
        ddy = paddle.to_tensor(
            self.input_numpy_ddy, stop_gradient=False, dtype='complex64'
        )
        dx_double_grad, dy_double_grad = paddle.grad(
            [dx, dy],
            [x, y],
            [ddx, ddy],
            retain_graph=True,
            create_graph=True,
        )
        d_x, d_y, d_dout, d_ddx, d_ddy = paddle.grad(
            [dx_double_grad, dy_double_grad],
            [x, y, dout, ddx, ddy],
            retain_graph=False,
            create_graph=False,
        )
        return d_x, d_y, d_dout, d_ddx, d_ddy

    # case1: no d_ddout, dims = 1, dtype is complex64
    def test_matmul_triple_grad_case1(self):
        def init_data():
            self.input_numpy_x = np.random.random([3]).astype(
                'float32'
            ) + 1j * np.random.random(
                [
                    3,
                ]
            ).astype(
                'float32'
            )
            self.input_numpy_y = np.random.random([3]).astype(
                'float32'
            ) + 1j * np.random.random(
                [
                    3,
                ]
            ).astype(
                'float32'
            )
            self.input_numpy_dout = np.ones(
                [
                    1,
                ],
                dtype="float32",
            )
            self.input_numpy_ddx = np.ones(
                [
                    3,
                ],
                dtype="float32",
            )
            self.input_numpy_ddy = np.ones(
                [
                    3,
                ],
                dtype="float32",
            )
            self.input_numpy_ddx_conj = np.conjugate(self.input_numpy_ddx)
            self.input_numpy_ddy_conj = np.conjugate(self.input_numpy_ddy)
            self.input_numpy_dout_conj = np.conjugate(self.input_numpy_dout)

        init_data()
        d_x_expected = np.zeros(
            [
                3,
            ],
            dtype="float32",
        )
        d_y_expected = np.zeros(
            [
                3,
            ],
            dtype="float32",
        )
        d_dout_expected = np.matmul(
            self.input_numpy_ddy_conj,
            np.ones(
                [
                    3,
                ],
                dtype="float32",
            ),
        ) + np.matmul(
            self.input_numpy_ddx_conj,
            np.ones(
                [
                    3,
                ],
                dtype="float32",
            ),
        )
        d_ddx_expected = (
            np.ones(
                [
                    3,
                ],
                dtype="float32",
            )
            * self.input_numpy_dout_conj[0]
        )
        d_ddy_expected = (
            np.ones(
                [
                    3,
                ],
                dtype="float32",
            )
            * self.input_numpy_dout_conj[0]
        )
        expected_results = (
            d_x_expected,
            d_y_expected,
            d_dout_expected,
            d_ddx_expected,
            d_ddy_expected,
        )

        for place in self.places:
            paddle.device.set_device(place)
            actual_results = self.actual()
            for expected_result, actual_result in zip(
                expected_results, actual_results
            ):
                np.testing.assert_allclose(
                    expected_result, actual_result, rtol=1e-6
                )
649
'''
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691


# d_ddout is none, d_dx is none, dtype is float32
class TestDygraphTripleGradMatmulcase3(TestCase):
    def setUp(self):
        self.input_numpy_x = None
        self.input_numpy_y = None
        self.input_numpy_dout = None
        self.input_numpy_ddx = None
        self.input_numpy_ddy = None
        self.places = ["cpu"]
        if paddle.is_compiled_with_cuda():
            self.places.append("gpu")

    def actual(self):
        x = paddle.to_tensor(
            self.input_numpy_x, stop_gradient=False, dtype='float32'
        )
        y = paddle.to_tensor(
            self.input_numpy_y, stop_gradient=False, dtype='float32'
        )
        out = paddle.matmul(x, y, False, False)

        dout = paddle.to_tensor(
            self.input_numpy_dout, stop_gradient=False, dtype='float32'
        )
        (dx, dy) = paddle.grad(
            [out], [x, y], [dout], retain_graph=True, create_graph=True
        )
        ddx = paddle.to_tensor(
            self.input_numpy_ddx, stop_gradient=False, dtype='float32'
        )
        ddy = paddle.to_tensor(
            self.input_numpy_ddy, stop_gradient=False, dtype='float32'
        )
        (dy_double_grad,) = paddle.grad(
            [dx, dy],
            [y],
            [ddx, ddy],
            retain_graph=True,
            create_graph=True,
        )
692 693 694
        # d_x d_y is None because (double grad out_put ddout grad tensor)d_ddout is None
        # d_ddy is None because (double grad out_put dx grad tensor) d_dx and d_ddout is None
        d_dout, d_ddx = paddle.grad(
695
            [dy_double_grad],
696
            [dout, ddx],
697 698 699
            retain_graph=False,
            create_graph=False,
        )
700
        return d_dout, d_ddx
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805

    # case1: d_ddout is none, d_dx is none, dims != 1
    def test_matmul_triple_grad_case1(self):
        def init_data():
            self.input_numpy_x = np.random.random([3, 3]).astype('float32')
            self.input_numpy_y = np.random.random([3, 3]).astype('float32')
            self.input_numpy_dout = np.ones([3, 3], dtype="float32")
            self.input_numpy_ddx = np.ones([3, 3], dtype="float32")
            self.input_numpy_ddy = np.ones([3, 3], dtype="float32")

        init_data()
        d_dout_expected = np.ones([3, 3], dtype="float32") * 3
        d_ddx_expected = np.ones([3, 3], dtype="float32") * 3
        expected_results = (
            d_dout_expected,
            d_ddx_expected,
        )

        for place in self.places:
            paddle.device.set_device(place)
            actual_results = self.actual()
            for expected_result, actual_result in zip(
                expected_results, actual_results
            ):
                np.testing.assert_allclose(
                    expected_result, actual_result, rtol=1e-6
                )

    # #case2: d_ddout is none, d_dx is none, dims = 1
    def test_matmul_triple_grad_case2(self):
        def init_data():
            self.input_numpy_x = np.random.random(
                [
                    3,
                ]
            ).astype('float32')
            self.input_numpy_y = np.random.random(
                [
                    3,
                ]
            ).astype('float32')
            self.input_numpy_dout = np.ones([1], dtype="float32")
            self.input_numpy_ddx = np.ones([3], dtype="float32")
            self.input_numpy_ddy = np.ones([3], dtype="float32")

        init_data()
        d_dout_expected = np.ones([1], dtype="float32") * 3
        d_ddx_expected = np.ones(
            [
                3,
            ],
            dtype="float32",
        )
        expected_results = (
            d_dout_expected,
            d_ddx_expected,
        )

        for place in self.places:
            paddle.device.set_device(place)
            actual_results = self.actual()
            for expected_result, actual_result in zip(
                expected_results, actual_results
            ):
                np.testing.assert_allclose(
                    expected_result, actual_result, rtol=1e-6
                )

    # #case3: d_ddout is none, d_dx is none , with broadcast
    def test_matmul_triple_grad_case3(self):
        def init_data():
            self.input_numpy_x = np.random.random([3, 1]).astype('float32')
            self.input_numpy_y = np.random.random(
                [
                    1,
                ]
            ).astype('float32')
            self.input_numpy_dout = np.ones([3], dtype="float32")
            self.input_numpy_ddx = np.ones([3, 1], dtype="float32")
            self.input_numpy_ddy = np.ones([1], dtype="float32")

        init_data()
        d_dout_expected = np.ones(
            [
                3,
            ],
            dtype="float32",
        )
        d_ddx_expected = np.ones([3, 1], dtype="float32")
        expected_results = (
            d_dout_expected,
            d_ddx_expected,
        )

        for place in self.places:
            paddle.device.set_device(place)
            actual_results = self.actual()
            for expected_result, actual_result in zip(
                expected_results, actual_results
            ):
                np.testing.assert_allclose(
                    expected_result, actual_result, rtol=1e-6
                )


806
'''
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
# d_ddout is none, d_dx is none, dtype is complex64
class TestDygraphTripleGradMatmulcase4(TestCase):
    def setUp(self):
        self.input_numpy_x = None
        self.input_numpy_y = None
        self.input_numpy_dout = None
        self.input_numpy_ddx = None
        self.input_numpy_ddy = None
        self.input_numpy_ddx_conj = None
        self.input_numpy_dout_conj = None
        self.places = ["cpu"]
        if paddle.is_compiled_with_cuda():
            self.places.append("gpu")

    def actual(self):
        x = paddle.to_tensor(
            self.input_numpy_x, stop_gradient=False, dtype='complex64'
        )
        y = paddle.to_tensor(
            self.input_numpy_y, stop_gradient=False, dtype='complex64'
        )
        out = paddle.matmul(x, y, False, False)

        dout = paddle.to_tensor(
            self.input_numpy_dout, stop_gradient=False, dtype='complex64'
        )
        (dx, dy) = paddle.grad(
            [out], [x, y], [dout], retain_graph=True, create_graph=True
        )
        ddx = paddle.to_tensor(
            self.input_numpy_ddx, stop_gradient=False, dtype='complex64'
        )
        ddy = paddle.to_tensor(
            self.input_numpy_ddy, stop_gradient=False, dtype='complex64'
        )
        (dy_double_grad,) = paddle.grad(
            [dx, dy],
            [y],
            [ddx, ddy],
            retain_graph=True,
            create_graph=True,
        )
        d_x, d_y, d_dout, d_ddx, d_ddy = paddle.grad(
            [dy_double_grad],
            [x, y, dout, ddx, ddy],
            retain_graph=False,
            create_graph=False,
        )
        return d_x, d_y, d_dout, d_ddx, d_ddy

    # case1: no d_ddout,no d_dx, dims = 1
    def test_matmul_triple_grad_case1(self):
        def init_data():
            self.input_numpy_x = np.random.random([3]).astype(
                'float32'
            ) + 1j * np.random.random(
                [
                    3,
                ]
            ).astype(
                'float32'
            )
            self.input_numpy_y = np.random.random([3]).astype(
                'float32'
            ) + 1j * np.random.random(
                [
                    3,
                ]
            ).astype(
                'float32'
            )
            self.input_numpy_dout = np.ones(
                [
                    1,
                ],
                dtype="float32",
            )
            self.input_numpy_ddx = np.ones(
                [
                    3,
                ],
                dtype="float32",
            )
            self.input_numpy_ddy = np.ones(
                [
                    3,
                ],
                dtype="float32",
            )
            self.input_numpy_ddx_conj = np.conjugate(self.input_numpy_ddx)
            self.input_numpy_dout_conj = np.conjugate(self.input_numpy_dout)

        init_data()
        d_x_expected = np.zeros(
            [
                3,
            ],
            dtype="float32",
        )
        d_y_expected = np.zeros(
            [
                3,
            ],
            dtype="float32",
        )
        d_dout_expected = np.matmul(
            self.input_numpy_ddx_conj,
            np.ones(
                [
                    3,
                ],
                dtype="float32",
            ),
        )
        d_ddx_expected = (
            np.ones(
                [
                    3,
                ],
                dtype="float32",
            )
            * self.input_numpy_dout_conj[0]
        )
        d_ddy_expected = np.zeros(
            [
                3,
            ],
            dtype="float32",
        )
        expected_results = (
            d_x_expected,
            d_y_expected,
            d_dout_expected,
            d_ddx_expected,
            d_ddy_expected,
        )

        for place in self.places:
            paddle.device.set_device(place)
            actual_results = self.actual()
            for expected_result, actual_result in zip(
                expected_results, actual_results
            ):
                np.testing.assert_allclose(
                    expected_result, actual_result, rtol=1e-6
                )
953
'''
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995


# d_ddout is none, d_dy is none, dtype is float32
class TestDygraphTripleGradMatmulcase5(TestCase):
    def setUp(self):
        self.input_numpy_x = None
        self.input_numpy_y = None
        self.input_numpy_dout = None
        self.input_numpy_ddx = None
        self.input_numpy_ddy = None
        self.places = ["cpu"]
        if paddle.is_compiled_with_cuda():
            self.places.append("gpu")

    def actual(self):
        x = paddle.to_tensor(
            self.input_numpy_x, stop_gradient=False, dtype='float32'
        )
        y = paddle.to_tensor(
            self.input_numpy_y, stop_gradient=False, dtype='float32'
        )
        out = paddle.matmul(x, y, False, False)

        dout = paddle.to_tensor(
            self.input_numpy_dout, stop_gradient=False, dtype='float32'
        )
        (dx, dy) = paddle.grad(
            [out], [x, y], [dout], retain_graph=True, create_graph=True
        )
        ddx = paddle.to_tensor(
            self.input_numpy_ddx, stop_gradient=False, dtype='float32'
        )
        ddy = paddle.to_tensor(
            self.input_numpy_ddy, stop_gradient=False, dtype='float32'
        )
        (dx_double_grad,) = paddle.grad(
            [dx, dy],
            [x],
            [ddx, ddy],
            retain_graph=True,
            create_graph=True,
        )
996
        d_dout, d_ddy = paddle.grad(
997
            [dx_double_grad],
998
            [dout, ddy],
999 1000 1001
            retain_graph=False,
            create_graph=False,
        )
1002
        return d_dout, d_ddy
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107

    # case1: d_ddout is none, d_dy is none, dims != 1
    def test_matmul_triple_grad_case1(self):
        def init_data():
            self.input_numpy_x = np.random.random([3, 3]).astype('float32')
            self.input_numpy_y = np.random.random([3, 3]).astype('float32')
            self.input_numpy_dout = np.ones([3, 3], dtype="float32")
            self.input_numpy_ddx = np.ones([3, 3], dtype="float32")
            self.input_numpy_ddy = np.ones([3, 3], dtype="float32")

        init_data()
        d_dout_expected = np.ones([3, 3], dtype="float32") * 3
        d_ddy_expected = np.ones([3, 3], dtype="float32") * 3
        expected_results = (
            d_dout_expected,
            d_ddy_expected,
        )

        for place in self.places:
            paddle.device.set_device(place)
            actual_results = self.actual()
            for expected_result, actual_result in zip(
                expected_results, actual_results
            ):
                np.testing.assert_allclose(
                    expected_result, actual_result, rtol=1e-6
                )

    # #case2: d_ddout is none, d_dy is none, dims = 1
    def test_matmul_triple_grad_case2(self):
        def init_data():
            self.input_numpy_x = np.random.random(
                [
                    3,
                ]
            ).astype('float32')
            self.input_numpy_y = np.random.random(
                [
                    3,
                ]
            ).astype('float32')
            self.input_numpy_dout = np.ones([1], dtype="float32")
            self.input_numpy_ddx = np.ones([3], dtype="float32")
            self.input_numpy_ddy = np.ones([3], dtype="float32")

        init_data()
        d_dout_expected = np.ones([1], dtype="float32") * 3
        d_ddy_expected = np.ones(
            [
                3,
            ],
            dtype="float32",
        )
        expected_results = (
            d_dout_expected,
            d_ddy_expected,
        )

        for place in self.places:
            paddle.device.set_device(place)
            actual_results = self.actual()
            for expected_result, actual_result in zip(
                expected_results, actual_results
            ):
                np.testing.assert_allclose(
                    expected_result, actual_result, rtol=1e-6
                )

    # #case3: d_ddout is none, d_dy is none , with broadcast
    def test_matmul_triple_grad_case3(self):
        def init_data():
            self.input_numpy_x = np.random.random([3, 1]).astype('float32')
            self.input_numpy_y = np.random.random(
                [
                    1,
                ]
            ).astype('float32')
            self.input_numpy_dout = np.ones([3], dtype="float32")
            self.input_numpy_ddx = np.ones([3, 1], dtype="float32")
            self.input_numpy_ddy = np.ones([1], dtype="float32")

        init_data()
        d_dout_expected = np.ones(
            [
                3,
            ],
            dtype="float32",
        )
        d_ddy_expected = np.ones([1], dtype="float32") * 3
        expected_results = (
            d_dout_expected,
            d_ddy_expected,
        )

        for place in self.places:
            paddle.device.set_device(place)
            actual_results = self.actual()
            for expected_result, actual_result in zip(
                expected_results, actual_results
            ):
                np.testing.assert_allclose(
                    expected_result, actual_result, rtol=1e-6
                )


1108 1109
'''
TODO(Ruting) test complex dtype when composite api support
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
# d_ddout is none, d_dy is none, dtype is complex64
class TestDygraphTripleGradMatmulcase6(TestCase):
    def setUp(self):
        self.input_numpy_x = None
        self.input_numpy_y = None
        self.input_numpy_dout = None
        self.input_numpy_ddx = None
        self.input_numpy_ddy = None
        self.input_numpy_ddy_conj = None
        self.input_numpy_dout_conj = None
        self.places = ["cpu"]
        if paddle.is_compiled_with_cuda():
            self.places.append("gpu")

    def actual(self):
        x = paddle.to_tensor(
            self.input_numpy_x, stop_gradient=False, dtype='complex64'
        )
        y = paddle.to_tensor(
            self.input_numpy_y, stop_gradient=False, dtype='complex64'
        )
        out = paddle.matmul(x, y, False, False)

        dout = paddle.to_tensor(
            self.input_numpy_dout, stop_gradient=False, dtype='complex64'
        )
        (dx, dy) = paddle.grad(
            [out], [x, y], [dout], retain_graph=True, create_graph=True
        )
        ddx = paddle.to_tensor(
            self.input_numpy_ddx, stop_gradient=False, dtype='complex64'
        )
        ddy = paddle.to_tensor(
            self.input_numpy_ddy, stop_gradient=False, dtype='complex64'
        )
        (dx_double_grad,) = paddle.grad(
            [dx, dy],
            [x],
            [ddx, ddy],
            retain_graph=True,
            create_graph=True,
        )
        d_x, d_y, d_dout, d_ddx, d_ddy = paddle.grad(
            [dx_double_grad],
            [x, y, dout, ddx, ddy],
            retain_graph=False,
            create_graph=False,
        )
        return d_x, d_y, d_dout, d_ddx, d_ddy

    # case1: no d_ddout,no d_dy, dims = 1
    def test_matmul_triple_grad_case1(self):
        def init_data():
            self.input_numpy_x = np.random.random([3]).astype(
                'float32'
            ) + 1j * np.random.random(
                [
                    3,
                ]
            ).astype(
                'float32'
            )
            self.input_numpy_y = np.random.random([3]).astype(
                'float32'
            ) + 1j * np.random.random(
                [
                    3,
                ]
            ).astype(
                'float32'
            )
            self.input_numpy_dout = np.ones(
                [
                    1,
                ],
                dtype="float32",
            )
            self.input_numpy_ddx = np.ones(
                [
                    3,
                ],
                dtype="float32",
            )
            self.input_numpy_ddy = np.ones(
                [
                    3,
                ],
                dtype="float32",
            )
            self.input_numpy_ddy_conj = np.conjugate(self.input_numpy_ddy)
            self.input_numpy_dout_conj = np.conjugate(self.input_numpy_dout)

        init_data()
        d_x_expected = np.zeros(
            [
                3,
            ],
            dtype="float32",
        )
        d_y_expected = np.zeros(
            [
                3,
            ],
            dtype="float32",
        )
        d_dout_expected = np.matmul(
            self.input_numpy_ddy_conj,
            np.ones(
                [
                    3,
                ],
                dtype="float32",
            ),
        )
        d_ddx_expected = np.zeros(
            [
                3,
            ],
            dtype="float32",
        )
        d_ddy_expected = (
            np.ones(
                [
                    3,
                ],
                dtype="float32",
            )
            * self.input_numpy_dout_conj[0]
        )
        expected_results = (
            d_x_expected,
            d_y_expected,
            d_dout_expected,
            d_ddx_expected,
            d_ddy_expected,
        )

        for place in self.places:
            paddle.device.set_device(place)
            actual_results = self.actual()
            for expected_result, actual_result in zip(
                expected_results, actual_results
            ):
                np.testing.assert_allclose(
                    expected_result, actual_result, rtol=1e-6
                )
1256
'''
1257

W
Weilong Wu 已提交
1258 1259
if __name__ == '__main__':
    unittest.main()