Skip to content

Fail in repeated evaluation of 2nd derivative of a custom autograd function #18619

@jhrmnn

Description

@jhrmnn

🐛 Bug

Repeated evaluation of a 2nd derivative of a custom autograd function gives incorrect results.

To Reproduce

import torch


def mult1(x):
    return x.prod(dim=-1).prod(dim=-1)


class Mult(torch.autograd.Function):
    @staticmethod
    def forward(ctx, x):
        y = mult1(x)
        ctx.save_for_backward(x, y)
        return y

    @staticmethod
    def backward(ctx, grad_output):
        x, y = ctx.saved_tensors
        return (grad_output * y)[:, None, None] / x


mult2 = Mult.apply


def check_gradgrad_repeated(x, y):
    gy, = torch.autograd.grad(y[0], x, create_graph=True)
    ggy_1, = torch.autograd.grad(gy[0, 0, 0], x, retain_graph=True)
    gy, = torch.autograd.grad(y[0], x, create_graph=True)
    ggy_2, = torch.autograd.grad(gy[0, 0, 0], x, retain_graph=True)
    print(ggy_1[0, 0, 1], ggy_2[0, 0, 1])


x = torch.ones(2, 4, 4).requires_grad_()
check_gradgrad_repeated(x, mult1(x))
check_gradgrad_repeated(x, mult2(x))

The output is:

tensor(1.) tensor(1.)
tensor(1.) tensor(-0.)

Expected behavior

The results should be the same on repeated evaluation.

Environment

PyTorch version: 1.0.1.post2
Is debug build: No
CUDA used to build PyTorch: 9.0.176

OS: Debian GNU/Linux 9.8 (stretch)
GCC version: (Homebrew gcc 5.5.0_4) 5.5.0
CMake version: version 3.13.4

Python version: 3.7
Is CUDA available: Yes
CUDA runtime version: Could not collect
GPU models and configuration:
GPU 0: GeForce GTX 1080 Ti
GPU 1: NVS 310

Nvidia driver version: 390.87
cuDNN version: Could not collect

Versions of relevant libraries:
[pip] numpy==1.16.1
[pip] torch==1.0.1.post2
[conda] Could not collect

Metadata

Metadata

Assignees

Labels

high prioritymodule: autogradRelated to torch.autograd, and the autograd engine in generalmodule: double backwardsProblem is related to double backwards definition on an operatortriagedThis issue has been looked at a team member, and triaged and prioritized into an appropriate module

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions