[dynamo] Fix handling of kwargs in exception constructor (#163390)

Pull Request resolved: https://github.com/pytorch/pytorch/pull/163390
Approved by: https://github.com/guilhermeleobas
This commit is contained in:
Rob Timpe
2025-09-24 18:37:30 +00:00
committed by PyTorch MergeBot
parent bc8680c298
commit 2b1236de61
4 changed files with 30 additions and 3 deletions

View File

@ -10,6 +10,7 @@ import torch._functorch.config
import torch.nn
import torch.utils.checkpoint
from torch._dynamo.bytecode_transformation import Instruction
from torch._dynamo.exc import Unsupported
from torch._dynamo.symbolic_convert import SpeculationLog, SpeculationLogDivergence
from torch.testing._internal.common_utils import (
instantiate_parametrized_tests,
@ -934,6 +935,13 @@ class ExceptionTests(torch._dynamo.test_case.TestCase):
assert exc2.__context__ is None
def test_exception_kwargs(self):
@torch.compile(backend="eager", fullgraph=True)
def fn():
raise AttributeError(name="a")
self.assertRaises(Unsupported, fn)
instantiate_parametrized_tests(ExceptionTests)

View File

@ -2726,5 +2726,15 @@
"Explanation": "Object does not allow us to make a weakref to it",
"Hints": []
}
],
"GB0273": [
{
"Gb_type": "Keyword args passed to exception constructor",
"Context": "{self} with kwargs {init_kwargs}",
"Explanation": "Dynamo does not know how to handle keyword args passed to an exception constructor",
"Hints": [
"It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues."
]
}
]
}

View File

@ -989,7 +989,7 @@ class BuiltinVariable(VariableTracker):
hints=[*graph_break_hints.SUPPORTABLE],
)
return variables.ExceptionVariable(fn, args, **kwargs)
return variables.ExceptionVariable(fn, args, kwargs)
return create_exception_class_object

View File

@ -388,10 +388,19 @@ class SuperVariable(VariableTracker):
class ExceptionVariable(VariableTracker):
# The ExceptionVariable corresponds to the BaseException class in Python
def __init__(self, exc_type, args, **kwargs) -> None:
super().__init__(**kwargs)
def __init__(
self, exc_type, args, init_kwargs=None, source=None, mutation_type=None
) -> None:
super().__init__(source=source, mutation_type=mutation_type)
self.exc_type = exc_type
self.args = args
if init_kwargs:
unimplemented_v2(
gb_type="Keyword args passed to exception constructor",
context=f"{self} with kwargs {init_kwargs}",
explanation="Dynamo does not know how to handle keyword args passed to an exception constructor",
hints=[*graph_break_hints.SUPPORTABLE],
)
# When raising a new exception while another exception is already being
# handled, the new exception's __context__ attribute is automatically
# set to the handled exception.