PyTorch PR #177530 fixes __torch_function__ recursion with skip-next flag
A single state variable prevents infinite loops in tensor method dispatch.
A long-standing bug in PyTorch's tensor dispatch mechanism has been fixed with PR #177530, authored by Edward Z. Yang (ezyang) from Meta. The issue, tracked as #55093, caused infinite recursion when `__torch_function__` was overridden in custom tensor subclasses. The problem occurred because each call to `__torch_function__` could re-enter itself through the dispatch chain, especially when using `super()` calls inside the override.
The solution introduces a new internal state variable, `skip_next_torch_function`, which is checked before entering the dispatch logic. This variable is reset to false each time `has_torch_function` is evaluated, ensuring that only one level of `__torch_function__` skipping occurs per dispatch cycle. The patch works across both C++ and Python backends and revives an earlier attempt from PR #74728. Developers can now safely write `super().__torch_function__(func, types, args, kwargs)` inside their implementations without triggering infinite loops. The PR was approved by reviewers albanD and anijain2305.
- PR #177530 adds a `skip_next_torch_function` state variable to PyTorch's dispatch.
- Prevents more than one level of __torch_function__ skipping, eliminating recursion bugs.
- Fixes 1,000+ day old issue #55093; allows safe super() usage in custom tensor subclasses.
Why It Matters
Fixes a persistent recursion bug in PyTorch's dispatch system, enabling safer custom tensor subclass implementations.