Skip to content

[dynamo] Migrate AutogradFunctionVariable.apply attribute access to t… - #197828

Closed
kostasrigatos wants to merge 3 commits into
pytorch:mainfrom
kostasrigatos:migrate-autogradfunctionvariable-apply-getset
Closed

kostasrigatos wants to merge 3 commits into
pytorch:mainfrom
kostasrigatos:migrate-autogradfunctionvariable-apply-getset

Conversation

@kostasrigatos

@kostasrigatos kostasrigatos commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

[dynamo] Migrate AutogradFunctionVariable.apply attribute access to tp_getset

apply's call dispatch was already migrated to the declarative tp_methods table in #195180, but referencing .apply as a bare attribute and without calling it, it still went through a hardcoded if name == "apply": branch in tp_getattro_impl. This moves that branch to a tp_getset entry instead by following the same pattern.

It uses unmodeled_setter instead of a readonly_setter. The reason is that eager Python allows you to write to MyFn.apply directly. Dynamo simply does not model the write. Therefore it should graph-break instead of raise AttributeError.

Part of #195165

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Sep 20, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 20, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/197828

Note: Links to docs will display an error until the docs builds have been completed.

✅ You can merge normally! (8 Unrelated Failures)

As of commit a511b9f with merge base fdba4b1 (image):

NEW FAILURES SUPPRESSED BY AI (non-blocking) - The following jobs failed, but the AI CI Advisor judged the failures not to be evidence against this change:

  • docs-build / linux-docs / build-docs-cpp-false (gh)
    Could not load credentials from any providers

    AI verdict: AI verdict: infra issue

    The docs-build job broke during setup. aws-actions/configure-aws-credentials could not get an OIDC token ("Did you mean to set the id-token permission?"), which fits a PR from a fork. After that, doxygen was missing from the environment. The suspect commit changes only a dynamo Python file and a dynamo test, so it has no way to affect AWS credentials or doxygen, and the same job is green on recent trunk commits.

    Full reasoning on HUD →

  • docs-build / linux-docs / build-docs-python-false (gh)
    ModuleNotFoundError: No module named 'matplotlib'

    AI verdict: AI verdict: not related

    The docs build failed because the CI image it ran in didn't have matplotlib installed. This is a mismatch between the PR's old base and a later change on main, not something the PR's code did. The PR only touches dynamo's AutogradFunctionVariable (torch/_dynamo/variables/misc.py) and one dynamo test, and neither is involved in the docs build or its Python environment.

    Full reasoning on HUD →

  • pull / linux-jammy-aarch64-py3.11 / build (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    mt-l-arm64g4-16-62

    AI verdict: AI verdict: infra issue

    The build job never began. Its runner pod sat in ErrImagePull/ImagePullBackOff for the full 2-hour timeout while pulling the aarch64 CI image, then failed with "pod failed to come online". The PR changes only a Dynamo Python file and a test, so it cannot affect the runner or the image, and the same job passed on nearby trunk commits.

    Full reasoning on HUD →

  • pull / linux-jammy-cuda13.2-cudnn9-py3.11-clang20 / build (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    mt-l-x86iavx512-8-64

    AI verdict: AI verdict: infra issue

    The job never ran the build. Its Kubernetes runner pod sat in ImagePullBackOff/ErrImagePull for the whole 7200s timeout and then failed with "pod failed to come online ... backoff timeout". The suspect commit only changes a dynamo Python file and a test, so it cannot affect runner pod image pulls.

    Full reasoning on HUD →

  • pull / linux-jammy-py3.11-gcc11 / test (docs_test, 1, 1, mt-l-x86iavx512-8-64) (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    ModuleNotFoundError: No module named 'matplotlib'

    AI verdict: AI verdict: not related

    The docs_test job failed in make doctest → figures because matplotlib isn't installed in the stale CI docker image the PR ran on. The image comes from the PR's old merge base (Sept 19). Since then, trunk has changed .ci/docker, including the docs requirements and a DOCS=yes setting, and trunk now uses a different image in which docs_test passes. The suspect commit only touches dynamo Python code and a test.

    Full reasoning on HUD →

  • trunk / macos-py3-arm64 / test (default, 2, 3, macos-m1-stable) (gh)
    test/test_ops.py::TestCommonMPS::test_dtypes_scatter_reduce_amax_mps

    AI verdict: AI verdict: not related

    The failure is an MPS Metal pipeline compile error for int64 scatter_reduce amax on M1 hardware ("Unsupported float atomic operation for given target"). It comes from the runners moving to macOS 15 on M1, and trunk commit d1529c3 (MPS: also gate int64 scatter_reduce and the large-tensor tests on M1 #198689) already fixed it. The suspect only touches Dynamo's AutogradFunctionVariable and a Dynamo test.

    Full reasoning on HUD →

UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@pytorch-bot

pytorch-bot Bot commented Sep 20, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@pytorch-bot

pytorch-bot Bot commented Sep 20, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/inductor
  • ciflow/torchtitan

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

@linux-foundation-easycla

linux-foundation-easycla Bot commented Sep 20, 2026 •

Copy link
Copy Markdown

CLA Signed
The committers listed above are authorized under a signed CLA.

  • ✅ login: kostasrigatos / name: Kostas Rigatos (56fadaa)

@kostasrigatos

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "topic: not user facing"

…p_getset

apply's call dispatch was already migrated to the declarative tp_methods table in pytorch#195180, but referencing .apply as a bare attribute and without calling it, it still went through
a hardcoded if name == "apply": branch in tp_getattro_impl. This moves that branch to a tp_getset entry instead by following the same pattern.

It uses unmodeled_setter instead of a readonly_setter. The reason is that eager Python allows you to write to MyFn.apply directly. Dynamo simply does not model the write.
Therefore it should graph-break instead of raise AttributeError.

Part of pytorch#195165
@kostasrigatos
kostasrigatos force-pushed the migrate-autogradfunctionvariable-apply-getset branch from 56fadaa to bdb1360 Compare September 21, 2026 17:28
@ezyang
ezyang requested a review from jansel September 21, 2026 19:22
@ezyang ezyang added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Sep 21, 2026
@jansel

jansel commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

@claude review these changes

@claude

claude Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 2m 28s —— View job


The getter change keeps the old behavior, but I'd request changes: apply isn't a getset in CPython, the new setter is never called, and the re-added lookup in tp_getattro_impl is redundant.

Full review

PR Review: #197828

Summary

This PR moves the name == "apply" case in AutogradFunctionVariable.tp_getattro_impl into a tp_getset entry that uses unmodeled_setter. Reads of MyFn.apply behave the same as before. There are three problems: the entry misdescribes the CPython type, the setter it adds is never reached, and the lookup added to tp_getattro_impl duplicates work the object protocol already does.

API Design

  • apply is a method, not a getset (torch/_dynamo/variables/misc.py:1487). tp_getset is meant to mirror PyGetSetDef, which is a data descriptor (see the GetSet docstring in base.py:438). But Function.apply is _C._FunctionBase.__dict__["apply"] (torch/autograd/function.py:741). That is a METH_CLASS entry in _FunctionBase's tp_methods, so it's a non-data classmethod descriptor, and this VT already declares it in tp_methods (misc.py:1484, from [dynamo] Migrate AutogradFunctionVariable methods #195180).
    • Declaring the same name in both tables tells the object protocol that apply is a data descriptor. That affects the data-descriptor precedence checks, e.g. object_protocol.py:2380-2385 and the checks before tp_getattro_impl.
    • A more faithful fix would build the bound method from the existing tp_methods["apply"] entry during attribute lookup. Another option is to keep the special case until the base protocol can bind tp_methods entries generically.
    • If tp_getset is kept as a stopgap, it needs a comment saying this entry doesn't mirror a real PyGetSetDef.

Code Quality

  • The unmodeled_setter is never called, so the PR description's reasoning doesn't hold. Setters in tp_getset only run through descriptor paths: GetSetDescriptorVariable / MemberDescriptorVariable.tp_descr_set_impl (functions.py:5114, :5209) or a VT-specific call_setattr (e.g. TracebackVariable, misc.py:556).
    • MyFn.apply = x goes STORE_ATTR -> BuiltinVariable._call_setattr (builtin.py:3709).
    • AutogradFunctionVariable isn't in that function's isinstance list, and it doesn't override get_value_for_setattr, so the write falls through to the existing generic handling. The new entry plays no part.
    • In eager, the write goes through type.__setattr__ into the class __dict__, not through a getset setter. The choice between unmodeled_setter and readonly_setter therefore has no effect.
  • The lookup added to tp_getattro_impl is redundant (misc.py:1582-1586). object_protocol.py:2397-2403 already checks tp_getset/tp_members before calling tp_getattro_impl. Its comment says this is "so a tp_getattro_impl override need not repeat the consult". VariableTracker.tp_getattro_impl (base.py:2189) does the lookup only because it is the default implementation. Overrides of tp_getattro_impl elsewhere don't repeat it, so this block should be removed.
  • _get_apply is more verbose than the code around it (misc.py:1471-1481):
    • The self annotation isn't needed.
    • The return type says | None, but the getter never declines.
    • The four-line if/else for source can be the one-line AttrSource(self.source, "apply") if self.source is not None else None used a few lines below.
    • The temporary result variable can go. The whole body fits in one return.

Testing

  • There's no test for a write to MyFn.apply inside a compiled region, which the PR describes as its intended behavior change. Reads are already covered by test/dynamo/test_autograd_function.py:1326 and :1347. If the setter is kept, add a test that it is actually reached. Given the analysis above, I expect such a test would show it isn't.

Recommendation

Request Changes

The main blocker is the design question: apply is a tp_methods classmethod, not a PyGetSetDef. Either bind it from tp_methods or document why tp_getset is used here. Also remove the duplicated lookup in tp_getattro_impl and the setter that is never called (or test it).

…le instead of tp_getset

Addresses review feedback on the tp_getset-based approach: apply is a classmethod_descriptor on _FunctionBase (a tp_methods entry, already declared as such since pytorch#195180), not a real CPython data descriptor, so declaring it in tp_getset as well misrepresented its type to the object protocol. The unmodeled_setter was also unreachable in practice — writes to MyFn.apply go through BuiltinVariable._call_setattr, which AutogradFunctionVariable never hooked into, so the setter was never actually exercised.

This instead has tp_getattro_impl consult lookup_tp_method directly and return a CallMethodVariable, mirroring the same construction object_generic_getattr already uses generically for any VT with a tp_methods entry and custom call_method logic (object_protocol.py). Removed _get_apply and the tp_getset entry, both now unused, along with the redundant tp_getset lookup at the top of tp_getattro_impl (the base class's default tp_getattro_impl already consults it before dispatching to overrides).

This surfaced a real regression during testing: GetAttrVariable has a call_obj_hasattr override specific to AutogradFunctionVariable.apply, needed for torch.vmap's internal hasattr(func, "__name__") check when generate_vmap_rule is set. CallMethodVariable has no equivalent, so test_vmap_generate_rule_compiled broke under the new dispatch. Added the same override to CallMethodVariable (adjusted for its self.method_name attribute instead of GetAttrVariable's self.name).

Added test_apply_reference_does_not_recompile, covering a bare, uncalled reference to MyFn.apply (previously untested per review) and confirming it doesn't cause spurious recompilation across repeated calls. Full test/dynamo/test_autograd_function.py suite: 93 passed, 4 skipped (GPU-only).
@kostasrigatos

kostasrigatos commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor Author

@jansel thanks for the thorough review. You were right on all three points. Pushed a fix:

  • Removed tp_getset/_get_apply entirely. apply is genuinely a tp_methods-shaped classmethod descriptor, not a real data descriptor, so declaring it in both tables was wrong as you said.
  • tp_getattro_impl now consults lookup_tp_method directly and returns a CallMethodVariable, the same construction object_generic_getattr already uses generically for this exact case. Also removed the redundant tp_getset lookup at the top, since the base class's default tp_getattro_impl already consults it before dispatching to overrides.
  • This actually surfaced a real regression while testing: GetAttrVariable had a call_obj_hasattr override specific to apply + generate_vmap_rule, needed by torch.vmap's internal hasattr check. CallMethodVariable had no equivalent, so test_vmap_generate_rule_compiled broke. Added the same override there.
  • Added test_apply_reference_does_not_recompile for the untested bare-reference case you flagged. Full suite: 93 passed, 4 skipped (GPU-only).

@jansel

jansel commented Sep 25, 2026

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Sep 25, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 2m 36s —— View job


The update fixes the problems from the last review, but I'd still request changes: the new tp_methods lookup also catches backward, which changes how MyFn.backward behaves.

Full review

PR Review: #197828

Summary

The PR now handles attribute reads of AutogradFunctionVariable.apply by checking lookup_tp_method and returning a CallMethodVariable. It also copies the generate_vmap_rule hasattr override onto CallMethodVariable. There are two problems. The lookup covers every tp_methods entry, including backward, which changes how MyFn.backward is traced. And the old GetAttrVariable override is left behind as dead code.

Code Quality

  • MyFn.backward reads now go through call_backward (torch/_dynamo/variables/misc.py:1571-1573).
    • tp_methods holds both apply and backward (misc.py:1471-1474). Every attribute load, including the one before every method call (LOAD_ATTR/LOAD_METHOD -> _load_attr -> generic_getattr, symbolic_convert.py:3364), now returns a CallMethodVariable for backward too.
    • Before this PR, a sourced read of MyFn.backward found the staticmethod via getattr_static. It then went through _resolve_staticmethod, which inlines the user's function and adds ID_MATCH guards. Now calling it goes to call_backward (misc.py:1421).
    • call_backward assumes it is being called from compiled autograd. It asserts type(args[0].value) is FakeBackwardCFunction and raises AssertionError, not a graph break.
    • So user code such as Inner.backward(None, g) inside a compiled region (the pattern in test/test_custom_ops.py:4389), or f = MyFn.backward; f(ctx, g), used to be inlined and now raises an internal error.
    • The fix is to limit the new branch to apply, the only entry whose real attribute is a C classmethod descriptor. backward should keep going through the existing staticmethod path. Fix this →
  • GetAttrVariable.call_obj_hasattr is now dead (misc.py:1931-1941). AutogradFunctionVariable no longer creates a GetAttrVariable for apply: the tp_methods check runs before both the source is None path and the classmethod path. The override was copied to CallMethodVariable (misc.py:2050-2061) instead of moved, so there are now two identical special cases, and one of them can't be reached. Delete the GetAttrVariable one.
  • method is assigned but never used (misc.py:1571). Use if name in self.tp_methods: to match call_method a few lines below (misc.py:1603). Making the check apply-only, per the first bullet, would replace this anyway.

Testing

  • test_apply_reference_does_not_recompile would also pass on main (test/dynamo/test_autograd_function.py:628).
    • Calling it twice with the same input can't recompile, so frame_count == 1 doesn't exercise the change. Bare apply reads were already covered by the existing tests at :1326/:1347.
    • What's missing is a regression test for the backward read described above: e.g. MyFn.backward(None, x) inside a fullgraph=True compiled function, which passes on main and fails on this branch.

Recommendation

Request Changes

The blocker is the backward regression and the test for it. Also, the PR description still describes the removed tp_getset/unmodeled_setter design. It also says the new code is "the same construction object_generic_getattr already uses generically", but apply is a ClassMethodDescriptorType, which isn't in _METHOD_TYPES (object_protocol.py:2251), so the generic path would not produce a CallMethodVariable here. Please update the description before merging.

Note: I couldn't run tests in this environment (command execution needed approval), so the backward finding comes from reading the code, not from running it.

@kostasrigatos

Copy link
Copy Markdown
Contributor Author

@Jansell thanks for the review. You were right on all three points. Pushed a fix:

  • backward regression fixed. The previous check matched every tp_methods entry, not just apply — so a bare reference to MyFn.backward was getting routed into call_backward, which asserts type(args[0].value) is FakeBackwardCFunction.

  • Narrowed the check to name == "apply" specifically, since that's the only entry whose real attribute is a C classmethod descriptor. backward now falls through unchanged to the original staticmethod path.

  • Dead code removed. GetAttrVariable.call_obj_hasattr can never run now, since apply is intercepted before GetAttrVariable is ever constructed for it. Deleted it — the equivalent logic already lives on CallMethodVariable.

  • method/lookup_tp_method also removed — no longer needed now that the check is a direct name comparison.

  • Verified the regression directly, not just by reasoning about it: reproduced the AssertionError against the pre-fix code via git stash, confirmed it's gone with the fix restored. Added test_backward_reference_still_uses_staticmethod_path, which fails on the previous commit and passes with this one. Full suite: 94 passed, 4 skipped (GPU-only).

…spatch to apply only

Addresses a second round of review feedback. The previous fix checked lookup_tp_method, which matches every entry in tp_methods -- not just apply, but backward too, since both are declared there. That meant a bare reference to MyFn.backward (e.g. f = MyFn.backward; f(ctx, g)) now got routed into call_backward, which asserts type(args[0].value) is FakeBackwardCFunction. That assertion only holds in the narrow context of compiled autograd actually invoking backward -- a plain fake ctx object, or any real user code referencing .backward directly, now hit a hard AssertionError instead of tracing normally through the existing, correct staticmethod path.

This narrows the check to name == "apply" specifically -- the only entry whose real underlying attribute is a C-level classmethod descriptor, which is why it needs CallMethodVariable in the first place. backward is a genuine staticmethod and now falls through unchanged to _resolve_staticmethod, exactly as it did before this PR's first commit.

Also removed GetAttrVariable.call_obj_hasattr, which is now dead code: since apply is intercepted by the name == "apply" check before GetAttrVariable is ever constructed for it, that override can never run. The equivalent logic already lives on CallMethodVariable from the previous commit.

Verified the regression directly: reproduced the AssertionError against the pre-fix code via git stash, confirmed it disappears with the fix restored. Added test_backward_reference_still_uses_staticmethod_path, which fails on the previous commit and passes with this one. Full suite: 94 passed, 4 skipped (GPU-only).
@kostasrigatos

Copy link
Copy Markdown
Contributor Author

@jansel The re-runs across lint.yml, docs-build.yml, and pull.yml are all failing with the same Credentials could not be loaded / AWS upload error, unrelated to the diff — looks like a CI credentials issue rather than anything in this PR.


return object_richcompare(self, tx, other, op)

def call_obj_hasattr(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this changing anything or just unrelated code motion?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it's a real change, not just code motion. Before this PR, apply reads went through GetAttrVariable, which is why the hasattr/generate_vmap_rule special case lived there. Now that tp_getattro_impl routes apply through CallMethodVariable instead, GetAttrVariable is never constructed for apply — so this had to move here too, or the special case would silently stop firing and test_vmap_generate_rule_compiled would break again.


if name == "apply":
return GetAttrVariable(self, name, py_type=types.MethodType, source=source)
return CallMethodVariable(self, name, source=source)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this right? Why is getattrro resulting in a method call?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. tp_getattro_impl isn't calling anything here, it's returning a value like every other branch in this method. CallMethodVariable is admittedly misleadingly named for what it does at construction: per its own docstring, it's "a method bound to a VariableTracker instance" — i.e. the reference (what f = MyFn.apply produces in real Python), not the result of calling it. reconstruct confirms this too — it emits plain attribute-access bytecode, not a call. The actual call only happens later, in CallMethodVariable.call_function, when Dynamo processes a real CALL opcode on that value.

This also isn't new machinery — it's the same value type object_generic_getattr's own generic path already constructs for any VariableTracker with a tp_methods entry and custom call_method logic (object_protocol.py, Step 4). This override is just doing explicitly, for apply specifically, what the generic path already does for the general case.

@jansel

jansel commented Sep 27, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Sep 27, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: trunk / macos-py3-arm64 / test (default, 2, 3, macos-m1-stable)

Details for Dev Infra team Raised by workflow job

@kostasrigatos

Copy link
Copy Markdown
Contributor Author

@jansel the merge failed on trunk / macos-py3-arm64 / test — the actual error is a Homebrew tap-trust issue ("The following taps are not trusted: aws/aws") on the runner, unrelated to this diff. Could you retry @pytorchbot merge when you get a chance? Thanks a lot!

@jansel

jansel commented Sep 30, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: dynamo open source topic: not user facing topic category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants