Skip to content

Support getattr for tensor subclasses in pre-dispatch export via patching tensor.getattr - #143946

Closed
tugsbayasgalan wants to merge 9 commits into
gh/tugsbayasgalan/284/basefrom
gh/tugsbayasgalan/284/head
Closed

tugsbayasgalan wants to merge 9 commits into
gh/tugsbayasgalan/284/basefrom
gh/tugsbayasgalan/284/head

Conversation

@tugsbayasgalan

@tugsbayasgalan tugsbayasgalan commented Dec 28, 2024 •

Copy link
Copy Markdown
Contributor

@pytorch-bot

pytorch-bot Bot commented Dec 28, 2024 •

Copy link
Copy Markdown

🔗 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 Failures

As of commit 6b322b7 with merge base e56768f (image):
💚 Looks good so far! There are no failures yet. 💚

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

…rt via patching tensor.getattr"

[ghstack-poisoned]
@tugsbayasgalan

Copy link
Copy Markdown
Contributor Author

@tugsbayasgalan has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator.

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Dec 28, 2024
tugsbayasgalan pushed a commit that referenced this pull request Dec 28, 2024
…hing tensor.getattr

ghstack-source-id: ec0a036
Pull Request resolved: #143946
Comment thread torch/export/_trace.py Outdated
# 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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

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.

Yup! extract_val calls detach and we are proxying that in the graph.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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()

Comment thread torch/export/_trace.py Outdated
# and the attributes we can proxy.
tensor_type_to_old_getattribute = {}
for arg in args:
if is_traceable_wrapper_subclass(arg):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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)

Comment thread torch/export/_trace.py Outdated
):
attrs_to_proxy.append(attr)
inner_tensors, _ = arg.__tensor_flatten__()
attrs_to_proxy.extend(inner_tensors)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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).

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.

Yep good point!

Comment thread torch/export/_trace.py Outdated
)

try:
for arg in args:

@bdhirsh bdhirsh Dec 30, 2024 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

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.

Ah yep true!

Comment thread torch/export/_trace.py
torch.ops.profiler._record_function_enter_new.default,
torch.ops.profiler._record_function_exit._RecordFunction,
torch.ops.aten.detach.default,
builtins.getattr,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

these two seem suspect 🤔

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.

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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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)

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.

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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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)),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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)

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.

Discussed offline. (2) won't actually be tested comprehensively given current state (need an operator or subclass constructor that consumes complicated metadata).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

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.

Updated the test case.

# 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)

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.

Don't know why this still exist, i deleted it and repurposed the helper function for my use case lol

@tugsbayasgalan

Copy link
Copy Markdown
Contributor Author

@tugsbayasgalan has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator.

tugsbayasgalan pushed a commit that referenced this pull request Jan 2, 2025
…hing tensor.getattr

ghstack-source-id: 588c19b
Pull Request resolved: #143946
@tugsbayasgalan

Copy link
Copy Markdown
Contributor Author

@tugsbayasgalan has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator.

tugsbayasgalan pushed a commit that referenced this pull request Jan 2, 2025
…hing tensor.getattr

ghstack-source-id: a3f40c9
Pull Request resolved: #143946
@bdhirsh
bdhirsh requested review from a team and IvanKobzarev January 2, 2025 19:20
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]]:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

Comment thread torch/export/_trace.py Outdated
{},
)
# Even though the name says tensor tracking, the impl
# suggests it tracks everything?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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 bdhirsh left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

left a few more comments, but overall lgtm!

tugsbayasgalan pushed a commit that referenced this pull request Jan 6, 2025
…hing tensor.getattr

ghstack-source-id: 458e7ae
Pull Request resolved: #143946
@tugsbayasgalan

Copy link
Copy Markdown
Contributor Author

@tugsbayasgalan has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator.

@facebook-github-bot

Copy link
Copy Markdown
Contributor

@pytorchbot merge

(Initiating merge automatically since Phabricator Diff has merged)

@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

@github-actions
github-actions Bot deleted the gh/tugsbayasgalan/284/head branch February 9, 2025 02:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants