SIGN IN SIGN UP

[dynamo] Resolve autograd.Function static attrs in getattr (#185316)

Dynamo represents torch.autograd.Function subclasses with
AutogradFunctionVariable so apply can trace forward and backward through the
autograd_function_apply higher-order op. Attribute reads on those classes,
however, remained unresolved GetAttrVariables.

This graph-breaks when setup_context is inspected: Dynamo tried to compare an
unresolved attribute with _SingleLevelFunction.setup_context instead of the
actual staticmethod. Resolve exact built-in staticmethod descriptors through
the current tp_getattro_impl slot while preserving the special apply path.
Guard both function identity and code because setup_context checks observe
identity, while function objects can also have their code mutated in place.
Keep the guardable class source when Function() creates a sourceless variable,
so direct staticmethod, classmethod, and apply calls remain sound.

Function.apply also changes its calling convention based on whether
setup_context is the exact inherited implementation. Compute that decision
with identity to match THPFunction_apply, guard it before kwargs resolution,
and reuse it in the grad and no-grad paths. This prevents stale graphs when
setup_context is replaced and avoids the previous signature-based convention
guess after recompilation.

Missing attributes, untraceable callables, and custom descriptors graph-break
without executing arbitrary descriptor code during tracing. Classmethod values
remain unresolved so bound-method equality is not constant-folded incorrectly,
while direct calls guard the underlying function. A targeted
_is_setup_context_defined special case was avoided because fixing the attribute
hook addresses the root cause; generic getattr delegation was also avoided
because it can execute descriptors and disrupt apply handling.

Fixes #160757
Generated by my agent

Test Plan:
```
python test/dynamo/test_autograd_function.py
python test/dynamo/test_tp_getattro.py
python tools/test/test_gb_registry_linter.py
lintrunner -a
```

Pull Request resolved: https://github.com/pytorch/pytorch/pull/185316
Approved by: https://github.com/zou3519
J
Jason Ansel committed
c196b7d27dfbc1c775831b1811318287f4f2b1c3
Parent: 10583bc
Committed by PyTorch MergeBot <pytorchmergebot@users.noreply.github.com> on 8/23/2026, 7:19:42 PM