Skip to content

Exception type changed when it's raised in backward operation #46088

@mfkasim1

Description

@mfkasim1

🐛 Bug

If there is an exception raised in the backward operation of custom function, PyTorch always raised RuntimeError and does not preserve the exception type.

To Reproduce

import torch

class MyFunc(torch.autograd.Function):
    @staticmethod
    def forward(ctx, x):
        return x

    @staticmethod
    def backward(ctx, gradx):
        raise TypeError("this should be TypeError")

a = torch.tensor(2.).requires_grad_()
a1 = MyFunc.apply(a)
print(torch.autograd.grad(a1, a))

The output:

Traceback (most recent call last):
  File "test.py", line 14, in <module>
    print(torch.autograd.grad(a1, a))
  File "/home/mfkasim/anaconda3/lib/python3.7/site-packages/torch/autograd/__init__.py", line 192, in grad
    inputs, allow_unused)
RuntimeError: this should be TypeError

It becomes RuntimeError despite it's specified as TypeError

Expected behavior

The exception type should be conserved.

Environment

  • PyTorch Version (e.g., 1.0): 1.6.0+cpu
  • OS (e.g., Linux): Ubuntu
  • How you installed PyTorch (conda, pip, source): pip
  • Build command you used (if compiling from source):
  • Python version: 3.7.4
  • CUDA/cuDNN version: N/A
  • GPU models and configuration: N/A
  • Any other relevant information:

Additional context

cc @ezyang @albanD @zou3519 @gqchen @pearu @nikitaved

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNot as big of a feature, but technically not a bug. Should be easy to fixmodule: autogradRelated to torch.autograd, and the autograd engine in generalmodule: bootcampWe plan to do a full writeup on the issue, and then get someone to do it for onboardingmodule: pybindRelated to our Python bindings / interactions with other Python librariestriagedThis issue has been looked at a team member, and triaged and prioritized into an appropriate module

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions