Repository navigation
Support getattr for tensor subclasses in pre-dispatch export via patching tensor.getattr - #143946
tugsbayasgalan wants to merge 9 commits into
Conversation
…hing tensor.getattr [ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/143946
Note: Links to docs will display an error until the docs builds have been completed. ✅ No FailuresAs of commit 6b322b7 with merge base e56768f ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
…rt via patching tensor.getattr" [ghstack-poisoned]
|
@tugsbayasgalan has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator. |
…rt via patching tensor.getattr" Previous discussion: #143671 (comment) and #143671 Differential Revision: [D67693609](https://our.internmc.facebook.com/intern/diff/D67693609) [ghstack-poisoned]
| # This has side effect of proxying stuff like | ||
| # proxy.node.meta["val"] = extract_val(val) because at that time, torch function | ||
| # mode is still active. It seems bad to turn it off inside proxy_tensor.py, so | ||
| # I guess we will just rely on DCE for now to remove extra stuff like detach |
There was a problem hiding this comment.
relying on DCE generally sounds ok. But I don't really follow this description - what does it mean that we proxy stuff like proxy.node.meta["val"] = extract_val(val)? Is it just the fact that extract_val() calls detach()? Or is there other stuff going on too
There was a problem hiding this comment.
Yup! extract_val calls detach and we are proxying that in the graph.
There was a problem hiding this comment.
got it. the extra detach() that gets DCEd sounds pretty harmless.
If we decide for some reason we want to avoid it later then we can always roll our own track_tensor_tree that just manually calls aten.detach.default(x) instead of x.detach()
| # and the attributes we can proxy. | ||
| tensor_type_to_old_getattribute = {} | ||
| for arg in args: | ||
| if is_traceable_wrapper_subclass(arg): |
There was a problem hiding this comment.
nit: you can short-circuit and also skip if type(arg) has already been seen (say you have 100 params that are all of the same subclass type)
| ): | ||
| attrs_to_proxy.append(attr) | ||
| inner_tensors, _ = arg.__tensor_flatten__() | ||
| attrs_to_proxy.extend(inner_tensors) |
There was a problem hiding this comment.
This line seems redundant? Any attribute names of "inner_tensors" that are returned from tensor_flatten should already show up as extra attributes that you found from dir(arg).
There was a problem hiding this comment.
Yep good point!
| ) | ||
|
|
||
| try: | ||
| for arg in args: |
There was a problem hiding this comment.
Any reason you're looping through args a second time here? I think you can just loop through tensor_type_to_old_getattribute.items() (the key is the tensor type, which should be equivalent to arg.__class__
>>> import torch
>>> from torch.testing._internal.two_tensor import TwoTensor
>>> x = TwoTensor(torch.ones(2), torch.ones(2))
>>> x.__class__ is type(x)
True
There was a problem hiding this comment.
Ah yep true!
| torch.ops.profiler._record_function_enter_new.default, | ||
| torch.ops.profiler._record_function_exit._RecordFunction, | ||
| torch.ops.aten.detach.default, | ||
| builtins.getattr, |
There was a problem hiding this comment.
I think this shows up when you are calling extract_val because then you access all inner attributes and check if they are FakeTensor etc.
There was a problem hiding this comment.
I don't follow though - why do we need to mark these two functions as impure?
My understanding is the main reason we mark some ops as impure is that they has some nonlocal side-effects, and we want to make sure that our graph passes like DCE don't remove them just because they look like dead code.
But both detach and getattr are actual pure functions (they don't have secret side effects)
There was a problem hiding this comment.
Hmmm so fx DCE calls is_impure function on every node before DCE-ing. These special cased operators will return False (suggesting it is safe to delete). Since we don't want to actually run DCE aggresively, we will by default return True. As a result, only nodes that are marked in this if statement will be deleted.
There was a problem hiding this comment.
oh I see... it's probably worth a comment for every op that we add to this list (otherwise a year from now someone reading this will have no idea why getattr/detach need to be DCE'd but not other ops). Can you add one describing the situation? (and in particular - that it's not fundamental, and that we can avoid tracing these "dead" getattr/detach calls in principle, but it would require carefully re-writing track_tensor_tree to not do any tensor method calls)
|
|
||
| def forward(self, x): | ||
| res = 2 * self.p1 + self.p2 | ||
| res2 = res + res.constant_attribute |
There was a problem hiding this comment.
One thing to call out is that if you look at the expecttest result below, there isn't a node for the res.constant_attribute access, e.g.:
%constant_attribute = call_function[target=builtins.getattr](args = (res, "constant_attribute"), kwargs = {})
%add_1 = call_function[target=torch.ops.aten.add.Tensor](args = (%add, %constant_attribute), kwargs = {})
Instead, the constant gets inlined in the graph to its value (4):
%add_1 = call_function[target=torch.ops.aten.add.Tensor](args = (%add, 4), kwargs = {})
This... may or may not be ok. It seems fine for this example, where the constant is just an integer. Once we get constructor support working, though, then you'll have to make sure code like this can be traced properly:
def f(subclass):
constant_metadata_namedtuple = subclass.metadata
new_subclass = Subclass(subclass.elem, constant_metadata_namedtuple)
Where if the constant metadata is something a bit more complicated (e.g. a named tuple holding constant values, which is the case for float8), then we'll need to make sure it shows up in a reasonable way as a contructor argument.
| self.p2 = torch.nn.Parameter( | ||
| TwoTensor( | ||
| TwoTensor(torch.ones(3, 4), torch.ones(3, 4)), | ||
| TwoTensor(torch.ones(3, 4), torch.ones(3, 4)), |
There was a problem hiding this comment.
A few more testing ideas:
(1) a test where you have TwoTensor(ConstantExtraMetadataTensor, ConstantExtraMetadataTensor), to test that we are properly proxying getattrs on subclass types that don't show up in the top-level arguments
(2) a test with a subclass that has more complicated constant metadata (e.g. a NamedTuple, to be a bit more representative of Float8). Mostly to make sure that something reasonable happens today, and also that we can augment later when we get constructor support (see comment below)
There was a problem hiding this comment.
Discussed offline. (2) won't actually be tested comprehensively given current state (need an operator or subclass constructor that consumes complicated metadata).
There was a problem hiding this comment.
Tbh it still seems worth testing to make sure something reasonable happens. e.g.:
named_tuple_val = subclass_tensor.metadata
# `named_tuple_val.foo` should get inlined as a constant
return subclass_tensor.elem * named_tuple_val.foo
There was a problem hiding this comment.
Updated the test case.
…rt via patching tensor.getattr" Previous discussion: #143671 (comment) and #143671 Differential Revision: [D67693609](https://our.internmc.facebook.com/intern/diff/D67693609) [ghstack-poisoned]
| # time as it is invoked in hot-path | ||
| from .subclass_utils import get_types_for_subclass | ||
|
|
||
| self.subclass_type = get_types_for_subclass(self.original_subclass) |
There was a problem hiding this comment.
Don't know why this still exist, i deleted it and repurposed the helper function for my use case lol
…rt via patching tensor.getattr" Previous discussion: #143671 (comment) and #143671 Differential Revision: [D67693609](https://our.internmc.facebook.com/intern/diff/D67693609) [ghstack-poisoned]
|
@tugsbayasgalan has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator. |
…rt via patching tensor.getattr" Previous discussion: #143671 (comment) and #143671 Differential Revision: [D67693609](https://our.internmc.facebook.com/intern/diff/D67693609) [ghstack-poisoned]
|
@tugsbayasgalan has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator. |
…rt via patching tensor.getattr" Previous discussion: #143671 (comment) and #143671 Differential Revision: [D67693609](https://our.internmc.facebook.com/intern/diff/D67693609) [ghstack-poisoned]
| inner_tensor = getattr(tensor_subclass, key) | ||
| result.extend(get_types_for_subclass(inner_tensor)) | ||
| return result | ||
| def get_types_for_subclass(tensor_subclass) -> Dict[Any, List[Any]]: |
There was a problem hiding this comment.
can we do better than Any -> Any? It seems like this is actually Dict[type, List[torch.Tensor]]?
From the function name it's not immediately clear why we're returning a dict - maybe worth a quick comment on the top saying that the values are all of the instances that we found of each subclass type
| {}, | ||
| ) | ||
| # Even though the name says tensor tracking, the impl | ||
| # suggests it tracks everything? |
There was a problem hiding this comment.
You probably want to remove the comment before merging. But from what we talked about in the test, this function will only actually track Tensors and SymInts (for everything else, we it will not track any proxies because other outputs will be treated as constants during tracing)
| inner_repr = repr(self.elem) | ||
| return f"CustomTensor({inner_repr})" | ||
|
|
||
| def get_complicated_metadata(self): |
There was a problem hiding this comment.
to be more representative you probably want the metadata here to be an actual attribute on the object (that e.g. is part of the output of tensor_flatten).
bdhirsh
left a comment
There was a problem hiding this comment.
left a few more comments, but overall lgtm!
…rt via patching tensor.getattr" Previous discussion: #143671 (comment) and #143671 Differential Revision: [D67693609](https://our.internmc.facebook.com/intern/diff/D67693609) [ghstack-poisoned]
…rt via patching tensor.getattr" Previous discussion: #143671 (comment) and #143671 Differential Revision: [D67693609](https://our.internmc.facebook.com/intern/diff/D67693609) [ghstack-poisoned]
|
@tugsbayasgalan has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator. |
|
@pytorchbot merge (Initiating merge automatically since Phabricator Diff has merged) |
Merge startedYour 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 |
Stack from ghstack (oldest at bottom):
Previous discussion: #143671 (comment) and #143671
Differential Revision: D67693609