test_imperative_double_grad.py 40.4 KB
Newer Older
1
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#
# 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

18
import numpy as np
19 20 21

import paddle
import paddle.fluid as fluid
22
import paddle.nn.functional as F
23 24
from paddle.fluid.wrapped_decorator import wrap_decorator
from paddle.vision.models import resnet50, resnet101
25 26 27 28


def _dygraph_guard_(func):
    def __impl__(*args, **kwargs):
J
Jiabin Yang 已提交
29
        if fluid._non_static_mode():
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
            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'):
    x_np = np.random.uniform(low=low, high=high, size=size).astype(dtype)
    return fluid.dygraph.to_variable(x_np)


46
class TestEagerGrad(TestCase):
47
    def test_simple_example_eager_grad(self):
48 49 50 51 52 53 54 55 56 57 58 59 60 61
        np.random.seed(2021)
        paddle.set_device('cpu')
        np_x = np.random.random((3, 3))
        np_y = np.random.random((3, 1))
        x = paddle.to_tensor(np_x, dtype="float64", stop_gradient=False)
        y = paddle.to_tensor(np_y, dtype="float64", stop_gradient=False)
        out = paddle.matmul(x, y)
        dx = fluid.dygraph.grad(out, x)

        dout = np.ones_like(np_y)
        expected_dx = np.matmul(dout, np.transpose(np_y))

        # stop_gradient = !create_graph, create_graph default false
        self.assertEqual(dx[0].stop_gradient, True)
62
        np.testing.assert_allclose(dx[0].numpy(), expected_dx, rtol=1e-05)
63

64
    def test_simple_example_eager_grad_allow_unused(self):
65 66 67 68 69 70 71 72 73 74 75 76 77 78
        np.random.seed(2021)
        paddle.set_device('cpu')
        np_x = np.random.random((3, 3))
        np_y = np.random.random((3, 1))
        np_z = np.random.random((3, 1))
        x = paddle.to_tensor(np_x, dtype="float64", stop_gradient=False)
        y = paddle.to_tensor(np_y, dtype="float64", stop_gradient=False)
        z = paddle.to_tensor(np_z, dtype="float64", stop_gradient=False)
        out_z = paddle.nn.functional.sigmoid(z)
        out = paddle.matmul(x, y)

        dx = fluid.dygraph.grad(out, [x, z], allow_unused=True)
        dout = np.ones_like(np_y)
        expected_dx = np.matmul(dout, np.transpose(np_y))
79
        np.testing.assert_allclose(dx[0].numpy(), expected_dx, rtol=1e-05)
80 81 82
        # stop_gradient = !create_graph, create_graph default false
        self.assertEqual(dx[0].stop_gradient, True)
        # x is unused input in the graph
83
        self.assertIsNone(dx[1])
84

85
    def test_simple_example_eager_grad_not_allow_unused(self):
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
        np.random.seed(2021)
        paddle.set_device('cpu')
        np_x = np.random.random((3, 3))
        np_y = np.random.random((3, 1))
        np_z = np.random.random((3, 1))
        x = paddle.to_tensor(np_x, dtype="float64", stop_gradient=False)
        y = paddle.to_tensor(np_y, dtype="float64", stop_gradient=False)
        z = paddle.to_tensor(np_z, dtype="float64", stop_gradient=False)
        out_z = paddle.nn.functional.sigmoid(z)
        out = paddle.matmul(x, y)

        try:
            # allow_unused is false in default
            dx = fluid.dygraph.grad(out, [x, z])
        except ValueError as e:
101
            error_msg = str(e)
102 103
            assert error_msg.find("allow_unused") > 0

104
    def test_simple_example_eager_grad_duplicate_input(self):
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
        np.random.seed(2021)
        paddle.set_device('cpu')
        np_x = np.random.random((3, 3))
        np_y = np.random.random((3, 1))
        np_z = np.random.random((3, 1))
        x = paddle.to_tensor(np_x, dtype="float64", stop_gradient=False)
        y = paddle.to_tensor(np_y, dtype="float64", stop_gradient=False)
        z = paddle.to_tensor(np_z, dtype="float64", stop_gradient=False)
        out_z = paddle.nn.functional.sigmoid(z)
        out = paddle.matmul(x, y)

        try:
            # duplicate input will arise RuntimeError errors
            dx = fluid.dygraph.grad(out, [x, x])
        except RuntimeError as e:
120
            error_msg = str(e)
121 122
            assert error_msg.find("duplicate") > 0

123
    def test_simple_example_eager_grad_duplicate_output(self):
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
        np.random.seed(2021)
        paddle.set_device('cpu')
        np_x = np.random.random((3, 3))
        np_y = np.random.random((3, 1))
        np_z = np.random.random((3, 1))
        x = paddle.to_tensor(np_x, dtype="float64", stop_gradient=False)
        y = paddle.to_tensor(np_y, dtype="float64", stop_gradient=False)
        z = paddle.to_tensor(np_z, dtype="float64", stop_gradient=False)
        out_z = paddle.nn.functional.sigmoid(z)
        out = paddle.matmul(x, y)

        try:
            # duplicate output will arise RuntimeError errors
            dx = fluid.dygraph.grad([out, out], [x])
        except RuntimeError as e:
139
            error_msg = str(e)
140 141
            assert error_msg.find("duplicate") > 0

142
    def test_simple_example_eager_two_grad_output(self):
143 144 145 146 147 148
        x1 = paddle.to_tensor([1.0, 2.0])
        x1.stop_gradient = False
        x2 = paddle.to_tensor([1.0, 2.0])
        x2.stop_gradient = False
        out1 = x1 * 2
        out2 = x2 * 2
149

150
        dout2_record_by_hook = []
151

152 153
        def record_hook(grad):
            dout2_record_by_hook.append(grad)
154

155
        out2.register_hook(record_hook)
156

157 158 159
        out3 = paddle.multiply(out1, out2)
        out4 = paddle.mean(out3)
        egr_dout2, egr_dout3 = paddle.grad([out4], [out2, out3])
160

161 162 163
        np.testing.assert_array_equal(
            dout2_record_by_hook[0].numpy(), np.array([1.0, 2.0])
        )
164 165 166 167 168 169 170 171 172 173 174 175 176 177

        x1 = paddle.to_tensor([1.0, 2.0])
        x1.stop_gradient = False
        x2 = paddle.to_tensor([1.0, 2.0])
        x2.stop_gradient = False
        out1 = x1 * 2
        out2 = x2 * 2

        out3 = paddle.multiply(out1, out2)
        out4 = paddle.mean(out3)
        dout2, dout3 = paddle.grad([out4], [out2, out3])

        self.assertEqual(dout2.stop_gradient, egr_dout2.stop_gradient)
        self.assertEqual(dout3.stop_gradient, egr_dout3.stop_gradient)
178 179
        np.testing.assert_array_equal(dout2.numpy(), egr_dout2.numpy())
        np.testing.assert_array_equal(dout3.numpy(), egr_dout3.numpy())
180

181

182 183 184 185 186
class TestDygraphDoubleGrad(TestCase):
    def setUp(self):
        self.sort_sum_gradient = False
        self.shape = [5, 10]

187 188 189 190 191 192 193 194 195 196
    def grad(
        self,
        outputs,
        inputs,
        grad_outputs=None,
        no_grad_vars=None,
        retain_graph=None,
        create_graph=False,
        allow_unused=False,
    ):
197
        fluid.set_flags({'FLAGS_sort_sum_gradient': self.sort_sum_gradient})
198 199 200 201 202 203 204 205 206
        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,
        )
207 208

    @dygraph_guard
209
    def test_exception(self):
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
        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):
228 229 230 231 232
            self.grad(
                [random_var(shape), random_var(shape)],
                [random_var(shape)],
                [random_var(shape)],
            )
233 234

        with self.assertRaises(AssertionError):
235 236 237
            self.grad(
                [random_var(shape)], [random_var(shape)], no_grad_vars=[1]
            )
238 239

        with self.assertRaises(AssertionError):
Z
Zeng Jinle 已提交
240
            self.grad([random_var(shape)], [random_var(shape)], no_grad_vars=1)
241 242

    @dygraph_guard
243
    def test_simple_example(self):
244 245 246 247 248
        x = random_var(self.shape)
        x.stop_gradient = False
        y = x + 1

        for create_graph in [False, True]:
249 250 251
            (dx,) = self.grad(
                [x], [x], create_graph=create_graph, retain_graph=True
            )
252 253 254 255
            self.assertEqual(dx.shape, x.shape)
            self.assertTrue(np.all(dx.numpy() == 1))
            self.assertNotEqual(dx.stop_gradient, create_graph)

256 257 258
            (dx_mul_2,) = self.grad(
                [y, x], [x], create_graph=create_graph, retain_graph=True
            )
259 260 261 262
            self.assertEqual(dx_mul_2.shape, x.shape)
            self.assertTrue(np.all(dx_mul_2.numpy() == 2))
            self.assertNotEqual(dx_mul_2.stop_gradient, create_graph)

263 264 265
            (none_grad,) = self.grad(
                [x], [y], create_graph=create_graph, allow_unused=True
            )
266
            self.assertIsNone(none_grad)
267

268 269 270
            (grad_with_none_and_not_none,) = self.grad(
                [x, y], [y], create_graph=create_graph
            )
271 272
            self.assertTrue(grad_with_none_and_not_none.shape, x.shape)
            self.assertTrue(np.all(grad_with_none_and_not_none.numpy() == 1))
273 274 275
            self.assertNotEqual(
                grad_with_none_and_not_none.stop_gradient, create_graph
            )
276 277

    @dygraph_guard
278
    def test_example_no_grad_vars(self):
279 280 281 282 283
        x = random_var(self.shape)
        x_np = x.numpy()
        numel = x_np.size
        x.stop_gradient = False

284 285
        y1 = F.relu(x)
        y2 = F.relu(x)
286 287 288
        z = y1 + y2
        w = z * z

289
        w_mean = paddle.mean(w)
290 291
        del y1, z, w

292 293 294
        (dx_actual,) = self.grad(
            [w_mean], [x], create_graph=True, no_grad_vars=[y2]
        )
295 296 297 298

        self.assertFalse(y2.stop_gradient)
        self.assertFalse(dx_actual.stop_gradient)

299 300 301 302 303 304 305
        dx_expected = (
            1.0
            / float(numel)
            * (np.maximum(x_np, 0) + y2.numpy())
            * (x_np > 0)
            * 2
        ).astype('float32')
306

307
        np.testing.assert_allclose(dx_actual.numpy(), dx_expected, rtol=1e-05)
308 309

    @dygraph_guard
310
    def test_none_one_initial_gradient(self):
311 312 313 314 315 316
        numel = 1
        for s in self.shape:
            numel *= s

        half_numel = int(numel / 2)
        half_x_positive = np.random.uniform(low=1, high=2, size=[half_numel])
317 318 319 320 321 322
        half_x_negative = np.random.uniform(
            low=-2, high=-1, size=[numel - half_numel]
        )
        x_np = np.array(list(half_x_positive) + list(half_x_negative)).astype(
            'float32'
        )
323 324 325
        np.random.shuffle(x_np)

        x = fluid.dygraph.to_variable(x_np)
326 327
        x.stop_gradient = False

328
        alpha = 0.2
329
        y = paddle.nn.functional.leaky_relu(x, alpha)
330 331 332 333
        y = y * y
        z = y * y

        x_np = x.numpy()
334 335
        relu_x_np = np.maximum(x_np, alpha * x_np).astype('float32')
        relu_x_grad_np = ((x_np > 0) + (x_np < 0) * alpha).astype('float32')
336
        dy_expected = (relu_x_np * relu_x_grad_np * 2).astype('float32')
337 338 339
        dz_expected = (np.power(relu_x_np, 3) * relu_x_grad_np * 4).astype(
            'float32'
        )
340

341 342
        random_grad_y = random_var(y.shape, low=1, high=2)
        random_grad_z = random_var(z.shape, low=1, high=2)
343 344 345 346 347 348 349 350 351
        ones_grad_y = np.ones(y.shape).astype('float32')
        ones_grad_z = np.ones(z.shape).astype('float32')

        original_random_grad_y = random_grad_y.numpy()
        original_random_grad_z = random_grad_z.numpy()

        for grad_y in [random_grad_y]:
            for grad_z in [random_grad_z]:
                for create_graph in [False, True]:
352 353 354 355 356 357 358
                    (dx_actual,) = self.grad(
                        outputs=[y, z],
                        inputs=[x],
                        grad_outputs=[grad_y, grad_z],
                        create_graph=create_graph,
                        retain_graph=True,
                    )
359

360 361
                    grad_y_np = (
                        ones_grad_y if grad_y is None else grad_y.numpy()
362
                    )
363 364
                    grad_z_np = (
                        ones_grad_z if grad_z is None else grad_z.numpy()
365 366
                    )

367 368 369 370 371 372
                    dx_expected = (
                        dy_expected * grad_y_np + dz_expected * grad_z_np
                    )
                    np.testing.assert_allclose(
                        dx_actual.numpy(), dx_expected, rtol=1e-05
                    )
373 374 375

                    if grad_y is not None:
                        self.assertTrue(grad_y.stop_gradient)
376 377 378
                        np.testing.assert_array_equal(
                            grad_y.numpy(), original_random_grad_y
                        )
379 380 381

                    if grad_z is not None:
                        self.assertTrue(grad_z.stop_gradient)
382 383 384
                        np.testing.assert_array_equal(
                            grad_z.numpy(), original_random_grad_z
                        )
385 386

    @dygraph_guard
387
    def test_example_with_gradient_accumulation_and_create_graph(self):
388 389 390 391 392
        x = random_var(self.shape)
        x_np = x.numpy()
        numel = x_np.size
        x.stop_gradient = False

393
        y = F.relu(x)
394 395 396
        z = y + 1
        w = z * z

397
        w_mean = paddle.mean(w)
398 399
        del y, z, w

400
        (dx_actual,) = self.grad([w_mean], [x], create_graph=True)
401 402 403 404 405
        del w_mean

        self.assertFalse(dx_actual.stop_gradient)

        # Theoritical result based on math calculation
406 407 408
        dx_expected = (
            1.0 / float(numel) * (np.maximum(x_np, 0) + 1) * (x_np > 0) * 2
        ).astype('float32')
409
        np.testing.assert_allclose(dx_actual.numpy(), dx_expected, rtol=1e-05)
410

411
        loss = paddle.mean(dx_actual * dx_actual + x * x)
412
        loss.backward(retain_graph=True)
413

414
        x_grad_actual = x.gradient()
415 416 417 418 419
        x_grad_expected = (
            2.0
            / float(numel)
            * (x_np + dx_expected * (x_np > 0) * 2 / float(numel))
        ).astype('float32')
420
        np.testing.assert_allclose(x_grad_actual, x_grad_expected, rtol=1e-05)
421 422 423

        for i in range(5):
            loss.backward(retain_graph=True)
424
            x_grad_actual = x.gradient()
425 426 427 428 429 430 431 432
            x_grad_expected = (i + 2) * (
                2.0
                / float(numel)
                * (x_np + dx_expected * (x_np > 0) * 2 / float(numel))
            ).astype('float32')
            np.testing.assert_allclose(
                x_grad_actual, x_grad_expected, rtol=1e-05
            )
433

434
    @dygraph_guard
435
    def test_example_with_gradient_accumulation_and_no_grad_vars(self):
436 437 438 439 440
        x = random_var(self.shape)
        x_np = x.numpy()
        numel = x_np.size
        x.stop_gradient = False

441 442
        y1 = F.relu(x)
        y2 = F.relu(x)
443 444 445
        z = y1 + y2
        w = z * z

446
        w_mean = paddle.mean(w)
447 448
        del y1, z, w

449 450 451 452 453 454 455
        (dx_actual,) = self.grad(
            [w_mean],
            [x],
            retain_graph=True,
            create_graph=True,
            no_grad_vars=[y2],
        )
456 457 458 459

        self.assertFalse(y2.stop_gradient)
        self.assertFalse(dx_actual.stop_gradient)

460 461 462 463 464 465 466
        dx_expected = (
            1.0
            / float(numel)
            * (np.maximum(x_np, 0) + y2.numpy())
            * (x_np > 0)
            * 2
        ).astype('float32')
467
        np.testing.assert_allclose(dx_actual.numpy(), dx_expected, rtol=1e-05)
468

469
        loss = paddle.mean(dx_actual * dx_actual + x * x)
470
        loss.backward()
471

472
        x_grad_actual = x.gradient()
473 474 475 476 477
        x_grad_expected = (
            2.0
            / float(numel)
            * (x_np + dx_expected * (x_np > 0) * 4 / float(numel))
        ).astype('float32')
478
        np.testing.assert_allclose(x_grad_actual, x_grad_expected, rtol=1e-05)
479

480
    @dygraph_guard
481
    def test_example_with_gradient_accumulation_and_not_create_graph(self):
482 483 484 485 486
        x = random_var(self.shape)
        x_np = x.numpy()
        numel = x_np.size
        x.stop_gradient = False

487
        y = F.relu(x)
488 489 490
        z = y + 1
        w = z * z

491
        w_mean = paddle.mean(w)
492 493
        del y, z, w

494
        (dx_actual,) = self.grad([w_mean], [x], create_graph=False)
495 496 497 498
        del w_mean

        self.assertTrue(dx_actual.stop_gradient)

499 500 501
        dx_expected = (
            1.0 / float(numel) * (np.maximum(x_np, 0) + 1) * (x_np > 0) * 2
        ).astype('float32')
502

503
        np.testing.assert_allclose(dx_actual.numpy(), dx_expected, rtol=1e-05)
504

505
        loss = paddle.mean(dx_actual * dx_actual + x * x)
506
        loss.backward()
507

508 509
        x_grad_actual = x.gradient()
        x_grad_expected = (2.0 * x_np / float(numel)).astype('float32')
510
        np.testing.assert_allclose(x_grad_actual, x_grad_expected, rtol=1e-05)
511

512 513 514 515 516 517 518

class TestDygraphDoubleGradSortGradient(TestDygraphDoubleGrad):
    def setUp(self):
        self.sort_sum_gradient = True
        self.shape = [5, 10]


H
hong 已提交
519
class TestDygraphDoubleGradVisitedUniq(TestCase):
520
    def test_compare(self):
521 522 523 524 525
        value = (
            np.random.uniform(-0.5, 0.5, 100)
            .reshape(10, 2, 5)
            .astype("float32")
        )
H
hong 已提交
526 527

        def model_f(input):
528
            linear = paddle.nn.Linear(5, 3)
H
hong 已提交
529 530
            for i in range(10):
                if i == 0:
531
                    out = linear(input)
H
hong 已提交
532
                else:
533
                    out = out + linear(input)
H
hong 已提交
534 535
            return out

536 537
        fluid.set_flags({'FLAGS_sort_sum_gradient': True})

H
hong 已提交
538
        with fluid.dygraph.guard():
C
cnn 已提交
539
            paddle.seed(123)
L
Leo Chen 已提交
540
            paddle.framework.random._manual_program_seed(123)
H
hong 已提交
541 542 543 544 545
            a = fluid.dygraph.to_variable(value)
            a.stop_gradient = False

            out = model_f(a)

546 547 548 549 550 551 552
            dx = fluid.dygraph.grad(
                outputs=[out],
                inputs=[a],
                create_graph=False,
                only_inputs=True,
                allow_unused=False,
            )
H
hong 已提交
553 554 555 556

            grad_1 = dx[0].numpy()

        with fluid.dygraph.guard():
C
cnn 已提交
557
            paddle.seed(123)
L
Leo Chen 已提交
558
            paddle.framework.random._manual_program_seed(123)
H
hong 已提交
559 560 561 562
            a = fluid.dygraph.to_variable(value)
            a.stop_gradient = False

            out = model_f(a)
563
            out.backward()
H
hong 已提交
564 565 566

            grad_2 = a.gradient()

567
        np.testing.assert_array_equal(grad_1, grad_2)
568 569 570


class TestRaiseNoDoubleGradOp(TestCase):
571
    def test_no_grad_op(self):
572
        with fluid.dygraph.guard():
573
            x = paddle.ones(shape=[2, 3, 2, 2], dtype='float32')
574
            x.stop_gradient = False
575
            y = paddle.static.nn.group_norm(x, groups=1)
576

577 578 579
            dx = fluid.dygraph.grad(
                outputs=[y], inputs=[x], create_graph=True, retain_graph=True
            )[0]
580

581
            loss = paddle.mean(dx)
582 583
            loss.backward()

H
hong 已提交
584

W
Weilong Wu 已提交
585 586 587 588 589 590
class TestDoubleGradResNet(TestCase):
    def setUp(self):
        paddle.seed(123)
        paddle.framework.random._manual_program_seed(123)
        self.data = np.random.rand(1, 3, 224, 224).astype(np.float32)

Z
Zeng Jinle 已提交
591
    @dygraph_guard
W
Weilong Wu 已提交
592
    def test_resnet_resnet50(self):
593 594 595 596 597 598 599 600 601
        model = resnet50(pretrained=False)
        egr_data = paddle.to_tensor(self.data)
        egr_data.stop_gradient = False
        egr_out = model(egr_data)
        egr_preds = paddle.argmax(egr_out, axis=1)
        egr_label_onehot = paddle.nn.functional.one_hot(
            paddle.to_tensor(egr_preds), num_classes=egr_out.shape[1]
        )
        egr_target = paddle.sum(egr_out * egr_label_onehot, axis=1)
W
Weilong Wu 已提交
602

603 604 605
        egr_g = paddle.grad(outputs=egr_target, inputs=egr_out)[0]
        egr_g_numpy = egr_g.numpy()
        self.assertEqual(list(egr_g_numpy.shape), list(egr_out.shape))
W
Weilong Wu 已提交
606 607 608

        model = resnet50(pretrained=False)
        data = paddle.to_tensor(self.data)
Z
Zeng Jinle 已提交
609
        data.stop_gradient = False
W
Weilong Wu 已提交
610
        out = model(data)
Z
Zeng Jinle 已提交
611
        preds = paddle.argmax(out, axis=1)
612 613 614
        label_onehot = paddle.nn.functional.one_hot(
            paddle.to_tensor(preds), num_classes=out.shape[1]
        )
Z
Zeng Jinle 已提交
615 616 617 618 619 620
        target = paddle.sum(out * label_onehot, axis=1)

        g = paddle.grad(outputs=target, inputs=out)[0]
        g_numpy = g.numpy()
        self.assertEqual(list(g_numpy.shape), list(out.shape))

621 622
        np.testing.assert_array_equal(egr_out, out)
        np.testing.assert_array_equal(egr_g_numpy, g_numpy)
Z
Zeng Jinle 已提交
623

W
Weilong Wu 已提交
624 625
    @dygraph_guard
    def test_resnet_resnet101(self):
626 627 628 629 630 631 632 633 634
        model = resnet101(pretrained=False)
        egr_data = paddle.to_tensor(self.data)
        egr_data.stop_gradient = False
        egr_out = model(egr_data)
        egr_preds = paddle.argmax(egr_out, axis=1)
        egr_label_onehot = paddle.nn.functional.one_hot(
            paddle.to_tensor(egr_preds), num_classes=egr_out.shape[1]
        )
        egr_target = paddle.sum(egr_out * egr_label_onehot, axis=1)
W
Weilong Wu 已提交
635

636 637 638
        egr_g = paddle.grad(outputs=egr_target, inputs=egr_out)[0]
        egr_g_numpy = egr_g.numpy()
        self.assertEqual(list(egr_g_numpy.shape), list(egr_out.shape))
W
Weilong Wu 已提交
639 640 641 642 643 644

        model = resnet101(pretrained=False)
        data = paddle.to_tensor(self.data)
        data.stop_gradient = False
        out = model(data)
        preds = paddle.argmax(out, axis=1)
645 646 647
        label_onehot = paddle.nn.functional.one_hot(
            paddle.to_tensor(preds), num_classes=out.shape[1]
        )
W
Weilong Wu 已提交
648
        target = paddle.sum(out * label_onehot, axis=1)
Z
Zeng Jinle 已提交
649

W
Weilong Wu 已提交
650 651 652
        g = paddle.grad(outputs=target, inputs=out)[0]
        g_numpy = g.numpy()
        self.assertEqual(list(g_numpy.shape), list(out.shape))
Z
Zeng Jinle 已提交
653

654 655
        np.testing.assert_array_equal(egr_out, out)
        np.testing.assert_array_equal(egr_g_numpy, g_numpy)
Z
Zeng Jinle 已提交
656 657


658 659 660
class TestDoubleGradBasics(TestCase):
    def test_matmul(self):
        input_numpy = np.ones([3, 3]) * 2
661 662 663 664 665
        x = paddle.to_tensor(input_numpy, stop_gradient=False, dtype='float32')
        y = paddle.to_tensor(input_numpy, stop_gradient=False, dtype='float32')
        grad_out = paddle.to_tensor(
            np.ones([3, 3]), stop_gradient=False, dtype='float32'
        )
666

667 668 669 670 671
        out = paddle.matmul(x, y, False, False)
        new_x_g, new_y_g = paddle.grad(
            [out], [x, y], [grad_out], retain_graph=True, create_graph=True
        )
        new_x_g.backward()
672

673 674
        out_ref = np.ones([3, 3]) * 12.0
        np.testing.assert_array_equal(out.numpy(), out_ref)
675

676 677 678 679
        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)
680

681 682
        x_grad_ref = np.ones([3, 3]) * 0.0
        np.testing.assert_array_equal(x.grad.numpy(), x_grad_ref)
683

684 685
        y_grad_ref = np.ones([3, 3]) * 3.0
        np.testing.assert_array_equal(y.grad.numpy(), y_grad_ref)
686

687 688
        grad_out_grad_ref = np.ones([3, 3]) * 6.0
        np.testing.assert_array_equal(grad_out.grad.numpy(), grad_out_grad_ref)
689 690


691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
class TestDygraphDoubleGradMatmul(TestCase):
    # case1: ddy is none, no broadcast,dims != 1
    def test_matmul_double_grad_case1(self):
        input_numpy_x = np.random.random([3, 3]).astype('float32')
        input_numpy_y = np.random.random([3, 3]).astype('float32')

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

            dout = paddle.to_tensor(
                np.ones([3, 3]), stop_gradient=False, dtype='float32'
            )
709 710
            (dx, dy) = paddle.grad(
                [out], [x, y], [dout], retain_graph=True, create_graph=True
711 712 713 714
            )
            ddx = paddle.to_tensor(
                np.ones([3, 3]), stop_gradient=False, dtype='float32'
            )
715
            ddy = ddx
716
            dx_double_grad, dy_double_grad, ddout = paddle.grad(
717
                [dx, dy],
718
                [x, y, dout],
719
                [ddx, ddy],
720 721 722 723 724 725
                retain_graph=True,
                create_graph=True,
            )
            return dx_double_grad, dy_double_grad, ddout

        def expected():
726 727 728 729
            dx_double_grad_expected = np.matmul(
                np.ones([3, 3], dtype="float32"),
                np.ones([3, 3], dtype="float32"),
            )
730 731 732 733
            dy_double_grad_expected = np.matmul(
                np.ones([3, 3], dtype="float32"),
                np.ones([3, 3], dtype="float32"),
            )
734
            ddout_expected1 = np.matmul(
735 736
                np.ones([3, 3], dtype="float32"), input_numpy_y
            )
737 738 739 740
            ddout_expected2 = np.matmul(
                input_numpy_x, np.ones([3, 3], dtype="float32")
            )
            ddout_expected = ddout_expected1 + ddout_expected2
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
            return (
                dx_double_grad_expected,
                dy_double_grad_expected,
                ddout_expected,
            )

        expected_results = expected()
        places = ["cpu"]
        if paddle.is_compiled_with_cuda():
            places.append("gpu")
        for place in places:
            paddle.device.set_device(place)
            actual_results = actual()
            for expected_result, actual_result in zip(
                expected_results, actual_results
            ):
                np.testing.assert_allclose(
                    expected_result, actual_result, rtol=1e-6
                )

    # case2: ddx is none,no broadcast, dims != 1
    def test_matmul_double_grad_case2(self):
        input_numpy_x = np.random.random([3, 3]).astype('float32')
        input_numpy_y = np.random.random([3, 3]).astype('float32')

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

            dout = paddle.to_tensor(
                np.ones([3, 3]), stop_gradient=False, dtype='float32'
            )
            (dy,) = paddle.grad(
                [out], [y], [dout], retain_graph=True, create_graph=True
            )
            ddy = paddle.to_tensor(
                np.ones([3, 3]), stop_gradient=False, dtype='float32'
            )
784 785
            # when x isnot be differentiate in first grad dy in second grad could be None in composite op
            dx_double_grad, ddout = paddle.grad(
786
                [dy],
787
                [x, dout],
788 789 790 791
                [ddy],
                retain_graph=True,
                create_graph=True,
            )
792
            return dx_double_grad, ddout
793 794 795 796 797 798 799 800 801 802 803 804 805 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

        def expected():
            dx_double_grad_expected = np.matmul(
                np.ones([3, 3], dtype="float32"),
                np.ones([3, 3], dtype="float32"),
            )
            ddout_expected = np.matmul(
                input_numpy_x, np.ones([3, 3], dtype="float32")
            )
            return (
                dx_double_grad_expected,
                ddout_expected,
            )

        expected_results = expected()
        places = ["cpu"]
        if paddle.is_compiled_with_cuda():
            places.append("gpu")
        for place in places:
            paddle.device.set_device(place)
            actual_results = actual()
            for expected_result, actual_result in zip(
                expected_results, actual_results
            ):
                np.testing.assert_allclose(
                    expected_result, actual_result, rtol=1e-6
                )

    # case3: ddx is none, dims = 1
    def test_matmul_double_grad_case3(self):
        input_numpy_x = np.random.random([3]).astype('float32')
        input_numpy_y = np.random.random([3]).astype('float32')

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

            dout = paddle.to_tensor(
                np.ones([1]), stop_gradient=False, dtype='float32'
            )
            (dy,) = paddle.grad(
                [out], [y], [dout], retain_graph=True, create_graph=True
            )
            ddy = paddle.to_tensor(
                np.ones([3]), stop_gradient=False, dtype='float32'
            )
844 845
            # when x is not be differentiate in first grad, dy from second grad could be None in composite api.
            dx_double_grad, ddout = paddle.grad(
846
                [dy],
847
                [x, dout],
848 849 850 851
                [ddy],
                retain_graph=True,
                create_graph=True,
            )
852
            return dx_double_grad, ddout
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

        def expected():
            dx_double_grad_expected = np.ones([3], dtype="float32")
            ddout_expected = np.matmul(
                input_numpy_x, np.ones([3], dtype="float32")
            )
            return (
                dx_double_grad_expected,
                ddout_expected,
            )

        expected_results = expected()
        places = ["cpu"]
        if paddle.is_compiled_with_cuda():
            places.append("gpu")
        for place in places:
            paddle.device.set_device(place)
            actual_results = actual()
            for expected_result, actual_result in zip(
                expected_results, actual_results
            ):
                np.testing.assert_allclose(
                    expected_result, actual_result, rtol=1e-6
                )

    # case4: ddy is none, dims = 1
    def test_matmul_double_grad_case4(self):
        input_numpy_x = np.random.random([3]).astype('float32')
        input_numpy_y = np.random.random([3]).astype('float32')

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

            dout = paddle.to_tensor(
                np.ones([1]), stop_gradient=False, dtype='float32'
            )
            (dx,) = paddle.grad(
                [out], [x], [dout], retain_graph=True, create_graph=True
            )
            ddx = paddle.to_tensor(
                np.ones([3]), stop_gradient=False, dtype='float32'
            )
901 902
            # when y is not be differentiate in first grad, dx from second grad could be None in composite api.
            dy_double_grad, ddout = paddle.grad(
903
                [dx],
904
                [y, dout],
905 906 907 908
                [ddx],
                retain_graph=True,
                create_graph=True,
            )
909
            return dy_double_grad, ddout
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927

        def expected():
            dy_double_grad_expected = np.ones([3], dtype="float32")
            ddout_expected = np.matmul(
                input_numpy_y, np.ones([3], dtype="float32")
            )
            return (
                dy_double_grad_expected,
                ddout_expected,
            )

        expected_results = expected()
        places = ["cpu"]
        if paddle.is_compiled_with_cuda():
            places.append("gpu")
        for place in places:
            paddle.device.set_device(place)
            actual_results = actual()
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 953 954 955 956 957 958
            for expected_result, actual_result in zip(
                expected_results, actual_results
            ):
                np.testing.assert_allclose(
                    expected_result, actual_result, rtol=1e-6
                )

    # case5: ddx is none, broadcast, dims != 1
    def test_matmul_double_grad_case5(self):
        input_numpy_x = np.random.random([2, 1]).astype('float32')
        input_numpy_y = np.random.random([1]).astype('float32')

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

            dout = paddle.to_tensor(
                np.ones([2]), stop_gradient=False, dtype='float32'
            )
            (dy,) = paddle.grad(
                [out], [y], [dout], retain_graph=True, create_graph=True
            )
            ddy = paddle.to_tensor(
                np.ones([1]), stop_gradient=False, dtype='float32'
            )
959
            dx_double_grad, ddout = paddle.grad(
960
                [dy],
961
                [x, dout],
962 963 964 965
                [ddy],
                retain_graph=True,
                create_graph=True,
            )
966
            return dx_double_grad, ddout
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 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014

        def expected():
            dx_double_grad_expected = np.ones([2, 1], dtype="float32")
            ddout_expected = np.matmul(
                input_numpy_x, np.ones([1], dtype="float32")
            )
            return (
                dx_double_grad_expected,
                ddout_expected,
            )

        expected_results = expected()
        places = ["cpu"]
        if paddle.is_compiled_with_cuda():
            places.append("gpu")
        for place in places:
            paddle.device.set_device(place)
            actual_results = actual()
            for expected_result, actual_result in zip(
                expected_results, actual_results
            ):
                np.testing.assert_allclose(
                    expected_result, actual_result, rtol=1e-6
                )

    # case6: ddy is none, broadcast, dims != 1
    def test_matmul_double_grad_case6(self):
        input_numpy_x = np.random.random([2, 1]).astype('float32')
        input_numpy_y = np.random.random([1]).astype('float32')

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

            dout = paddle.to_tensor(
                np.ones([2]), stop_gradient=False, dtype='float32'
            )
            (dx,) = paddle.grad(
                [out], [x], [dout], retain_graph=True, create_graph=True
            )
            ddx = paddle.to_tensor(
                np.ones([2, 1]), stop_gradient=False, dtype='float32'
            )
1015
            dy_double_grad, ddout = paddle.grad(
1016
                [dx],
1017
                [y, dout],
1018 1019 1020 1021
                [ddx],
                retain_graph=True,
                create_graph=True,
            )
1022
            return dy_double_grad, ddout
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045

        def expected():
            dy_double_grad_expected = np.ones([1], dtype="float32") * 2
            ddout_expected = np.ones([2], dtype="float32") * input_numpy_y[0]
            return (
                dy_double_grad_expected,
                ddout_expected,
            )

        expected_results = expected()
        places = ["cpu"]
        if paddle.is_compiled_with_cuda():
            places.append("gpu")
        for place in places:
            paddle.device.set_device(place)
            actual_results = actual()
            for expected_result, actual_result in zip(
                expected_results, actual_results
            ):
                np.testing.assert_allclose(
                    expected_result, actual_result, rtol=1e-6
                )

1046 1047
    # TODO(Ruting) test complex dtype when composite api support
    '''
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
    # case7: ddx is none, dims = 1, complex dtype
    def test_matmul_double_grad_case7(self):
        input_numpy_x = np.random.random([3]).astype(
            'float32'
        ) + 1j * np.random.random([3]).astype('float32')
        input_numpy_y = np.random.random([3]).astype(
            'float32'
        ) + 1j * np.random.random([3]).astype('float32')
        input_numpy_y_conj = np.conjugate(input_numpy_y)

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

            dout = paddle.to_tensor(
                np.ones([1]), stop_gradient=False, dtype='complex64'
            )
            (dx,) = paddle.grad(
                [out], [x], [dout], retain_graph=True, create_graph=True
            )
            ddx = paddle.to_tensor(
                np.ones([3]), stop_gradient=False, dtype='complex64'
            )
1076 1077
            # when y is not be differentiate in first grad, dx from second grad could be None in composite api.
            dy_double_grad, ddout = paddle.grad(
1078
                [dx],
1079
                [y, dout],
1080 1081 1082 1083
                [ddx],
                retain_graph=True,
                create_graph=True,
            )
1084
            return dy_double_grad, ddout
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111

        def expected():
            dy_double_grad_expected = np.ones(
                [3], dtype="float32"
            ) + 0j * np.ones([3], dtype="float32")
            ddout_expected = np.matmul(
                input_numpy_y_conj, np.ones([3], dtype="float32")
            )
            return (
                dy_double_grad_expected,
                ddout_expected,
            )

        expected_results = expected()
        places = ["cpu"]
        if paddle.is_compiled_with_cuda():
            places.append("gpu")
        for place in places:
            paddle.device.set_device(place)
            actual_results = actual()
            for expected_result, actual_result in zip(
                expected_results, actual_results
            ):
                np.testing.assert_allclose(
                    expected_result, actual_result, rtol=1e-6
                )

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
    # case8: ddy is none, dims = 1, complex dtype
    def test_matmul_double_grad_case8(self):
        input_numpy_x = np.random.random([3]).astype(
            'float32'
        ) + 1j * np.random.random([3]).astype('float32')
        input_numpy_y = np.random.random([3]).astype(
            'float32'
        ) + 1j * np.random.random([3]).astype('float32')
        input_numpy_x_conj = np.conjugate(input_numpy_x)

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

            dout = paddle.to_tensor(
                np.ones([1]), stop_gradient=False, dtype='complex64'
            )
            (dy,) = paddle.grad(
                [out], [y], [dout], retain_graph=True, create_graph=True
            )
            ddy = paddle.to_tensor(
                np.ones([3]), stop_gradient=False, dtype='complex64'
            )
1141
            dx_double_grad, ddout = paddle.grad(
1142
                [dy],
1143
                [x, dout],
1144 1145 1146 1147
                [ddy],
                retain_graph=True,
                create_graph=True,
            )
1148
            return dx_double_grad, ddout
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172

        def expected():
            dx_double_grad_expected = np.ones([3], dtype="float32")
            ddout_expected = np.matmul(
                input_numpy_x_conj, np.ones([3], dtype="float32")
            )
            return (
                dx_double_grad_expected,
                ddout_expected,
            )

        expected_results = expected()
        places = ["cpu"]
        if paddle.is_compiled_with_cuda():
            places.append("gpu")
        for place in places:
            paddle.device.set_device(place)
            actual_results = actual()
            for expected_result, actual_result in zip(
                expected_results, actual_results
            ):
                np.testing.assert_allclose(
                    expected_result, actual_result, rtol=1e-6
                )
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
    '''

    def test_value_error(self):
        def test():
            import paddle
            import paddle.nn as nn

            model = nn.Sequential(nn.Linear(3, 4))

            x = paddle.randn([4, 1])
            y = paddle.randn([4, 1])
            z = paddle.randn([4, 1])
            x.stop_gradient = False
            y.stop_gradient = False
            z.stop_gradient = False
            out = model(paddle.concat((x, y, z), axis=1))

            data = {
                "x": x,
                "y": y,
                "z": z,
                "u": out[:, 0:1],
                "v": out[:, 1:2],
                "w": out[:, 2:3],
                "p": out[:, 3:4],
            }

            v = out[:, 1:2]
            z = paddle.grad(v, x, create_graph=True)[0]
            zz = paddle.grad(z, x, create_graph=True)[0]

        with self.assertRaises(ValueError):
            test()
1206 1207


1208 1209
if __name__ == '__main__':
    unittest.main()