Skip to content

[DRAFT] Implement getattr access for subclasses in pre-dispatch IR - #143518

Closed
tugsbayasgalan wants to merge 2 commits into
gh/tugsbayasgalan/281/basefrom
gh/tugsbayasgalan/281/head
Closed

tugsbayasgalan wants to merge 2 commits into
gh/tugsbayasgalan/281/basefrom
gh/tugsbayasgalan/281/head

Conversation

@tugsbayasgalan

@tugsbayasgalan tugsbayasgalan commented Dec 18, 2024 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

This is a draft PR that tries to prototype how to capture attribute access in pre-dispatch IR. The motivating use case is: https://github.com/pytorch/ao/blob/039cef4ad546716aa04cd54c461feb173f7fe403/tutorials/developer_api_guide/export_to_executorch.py#L54 where TorchAO overrides Embedding.weight with a tensor subclass and then do attribute access inside it. We have to solve this problem in both strict and non-strict because even when dynamo translates subclass.inner_tensor into a fx Graph, the underlying tracer that converts torch IR to aten IR will need to handle subclass.inner_tensor as well.

The basic implementation idea here is that: "We will override getattr of tensors so that we can inject torch_function handler to intercept it in make_fx". But the complications here are:

  1. We don't want to add override to getattr in tensor because it will significantly slow down the eager performance. Some synthetic benchmarking we did showed around 15% slow down (the benchmark is bit skewed because the example we tried had lot of attr accesses)
  2. We can only intercept getattr for input tensors (user inputs + param/buffers) because intercepting everything will require we do global patching.

So we decided to monkey patch inner tensors as properties in export. Then, the main difficulty here is to correctly clean up the monkey patched attr accesses. Roughly we are doing something like this:

class Foo():
    bar = 2

foo = Foo()
print(foo.bar)

def patch(obj):
    obj._real_foo = obj.bar
    def my_getter(self):
        print("handle things here ")
        return self._real_foo
    def my_setter(self, new_val):
        print("Handle setter here")
        self._real_foo = new_val
    type(obj).bar = property(my_getter, my_setter)

patch(foo)
print(foo.bar)
foo.bar = 3
print(foo.bar)

Other approaches we considered but didn't pursue:

  1. Ask subclass authors to explicitly mark inner tensors as properties which sounds bit lame
  2. If user is interested in inference IR only, don't materialize pre-dispatch IR which causes some complicated story for export side.

cc @ezyang @SherlockNoMad @EikanWang @jgong5 @wenzhe-nrv

@pytorch-bot

pytorch-bot Bot commented Dec 18, 2024 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 17 New Failures, 4 Unrelated Failures

As of commit ce869cf with merge base 9706ada (image):

NEW FAILURES - The following jobs have failed:

BROKEN TRUNK - The following jobs failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

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

tugsbayasgalan pushed a commit that referenced this pull request Dec 18, 2024
ghstack-source-id: 831052f
Pull Request resolved: #143518
This is a draft PR that tries to prototype how to capture attribute access in pre-dispatch IR. The motivating use case is: https://github.com/pytorch/ao/blob/039cef4ad546716aa04cd54c461feb173f7fe403/tutorials/developer_api_guide/export_to_executorch.py#L54 where TorchAO overrides Embedding.weight with a tensor subclass and then do attribute access inside it. We have to solve this problem in both strict and non-strict because even when dynamo translates `subclass.inner_tensor` into a fx Graph, the underlying tracer that converts torch IR to aten IR will need to handle `subclass.inner_tensor` as well. 

The basic implementation idea here is that: "We will override __getattr__ of tensors so that we can inject torch_function handler to intercept it in make_fx". But the complications here are:
1. We don't want to add override to __getattr__ in tensor because it will significantly slow down the eager performance. Some synthetic benchmarking we did showed around 15% slow down (the benchmark is bit skewed because the example we tried had lot of attr accesses) 
2. We can only intercept __getattr__ for input tensors (user inputs + param/buffers) because intercepting everything will require we do global patching. 

So we decided to monkey patch inner tensors as properties in export. Then, the main difficulty here is to correctly clean up the monkey patched attr accesses. Roughly we are doing something like this:
```
class Foo():
    bar = 2

foo = Foo()
print(foo.bar)

def patch(obj):
    obj._real_foo = obj.bar
    def my_getter(self):
        print("handle things here ")
        return self._real_foo
    def my_setter(self, new_val):
        print("Handle setter here")
        self._real_foo = new_val
    type(obj).bar = property(my_getter, my_setter)

patch(foo)
print(foo.bar)
foo.bar = 3
print(foo.bar)
```

Other approaches we considered but didn't pursue:
1. Ask subclass authors to explicitly mark inner tensors as properties which sounds bit lame
2. If user is interested in inference IR only, don't materialize pre-dispatch IR which causes some complicated story for export side. 

cc ezyang SherlockNoMad EikanWang jgong5 wenzhe-nrv

[ghstack-poisoned]
tugsbayasgalan pushed a commit that referenced this pull request Dec 19, 2024
ghstack-source-id: 76e2220
Pull Request resolved: #143518
@tugsbayasgalan tugsbayasgalan changed the title Implement getattr access for pre-dispatch IR [DRAFT] Implement getattr access for subclasses in pre-dispatch IR Dec 19, 2024
tugsbayasgalan pushed a commit that referenced this pull request Dec 20, 2024

This is a draft PR that tries to prototype how to capture attribute access in pre-dispatch IR. The motivating use case is: https://github.com/pytorch/ao/blob/039cef4ad546716aa04cd54c461feb173f7fe403/tutorials/developer_api_guide/export_to_executorch.py#L54 where TorchAO overrides Embedding.weight with a tensor subclass and then do attribute access inside it. We have to solve this problem in both strict and non-strict because even when dynamo translates subclass.inner_tensor into a fx Graph, the underlying tracer that converts torch IR to aten IR will need to handle subclass.inner_tensor as well.
I think there are roughly two ways to implement this:
1) Override getattr on tensor in export to monkey patch inner tensors as properties and add torch function handler 
2) When we first see a subclass tensor in make_fx, attach proxy to its' call inner tensors.

I tried implementing (1) here: #143518, but it turned out to be quite intrusive. So I prefer (2) for now. Only downside for (2) is we are creating proxy for unnecessarily many inner tensors but i think it is ok because:
1) torch.compile will never see tensor subclass in make_fx so it won't regress any tracing speed
2) Hopefully tensor subclasses that are used in export are not that nest-y. 

I also noticed a small bug in tensor subclass unwrapping logic. cc IvanKobzarev 



cc ezyang SherlockNoMad EikanWang jgong5 wenzhe-nrv

[ghstack-poisoned]
tugsbayasgalan pushed a commit that referenced this pull request Dec 20, 2024

This is a draft PR that tries to prototype how to capture attribute access in pre-dispatch IR. The motivating use case is: https://github.com/pytorch/ao/blob/039cef4ad546716aa04cd54c461feb173f7fe403/tutorials/developer_api_guide/export_to_executorch.py#L54 where TorchAO overrides Embedding.weight with a tensor subclass and then do attribute access inside it. We have to solve this problem in both strict and non-strict because even when dynamo translates subclass.inner_tensor into a fx Graph, the underlying tracer that converts torch IR to aten IR will need to handle subclass.inner_tensor as well.
I think there are roughly two ways to implement this:
1) Override getattr on tensor in export to monkey patch inner tensors as properties and add torch function handler 
2) When we first see a subclass tensor in make_fx, attach proxy to its' call inner tensors.

I tried implementing (1) here: #143518, but it turned out to be quite intrusive. So I prefer (2) for now. Only downside for (2) is we are creating proxy for unnecessarily many inner tensors but i think it is ok because:
1) torch.compile will never see tensor subclass in make_fx so it won't regress any tracing speed
2) Hopefully tensor subclasses that are used in export are not that nest-y. 

I also noticed a small bug in tensor subclass unwrapping logic. cc IvanKobzarev 



cc ezyang SherlockNoMad EikanWang jgong5 wenzhe-nrv

Differential Revision: [D67531713](https://our.internmc.facebook.com/intern/diff/D67531713)

[ghstack-poisoned]
tugsbayasgalan pushed a commit that referenced this pull request Dec 22, 2024

This is a draft PR that tries to prototype how to capture attribute access in pre-dispatch IR. The motivating use case is: https://github.com/pytorch/ao/blob/039cef4ad546716aa04cd54c461feb173f7fe403/tutorials/developer_api_guide/export_to_executorch.py#L54 where TorchAO overrides Embedding.weight with a tensor subclass and then do attribute access inside it. We have to solve this problem in both strict and non-strict because even when dynamo translates subclass.inner_tensor into a fx Graph, the underlying tracer that converts torch IR to aten IR will need to handle subclass.inner_tensor as well.
I think there are roughly two ways to implement this:
1) Override getattr on tensor in export to monkey patch inner tensors as properties and add torch function handler 
2) When we first see a subclass tensor in make_fx, attach proxy to its' call inner tensors.

I tried implementing (1) here: #143518, but it turned out to be quite intrusive. So I prefer (2) for now. Only downside for (2) is we are creating proxy for unnecessarily many inner tensors but i think it is ok because:
1) torch.compile will never see tensor subclass in make_fx so it won't regress any tracing speed
2) Hopefully tensor subclasses that are used in export are not that nest-y. 

I also noticed a small bug in tensor subclass unwrapping logic. cc IvanKobzarev 



cc ezyang SherlockNoMad EikanWang jgong5 wenzhe-nrv

Differential Revision: [D67531713](https://our.internmc.facebook.com/intern/diff/D67531713)

[ghstack-poisoned]
tugsbayasgalan pushed a commit that referenced this pull request Dec 22, 2024
…tch"



This is a draft PR that tries to prototype how to capture attribute access in pre-dispatch IR. The motivating use case is: https://github.com/pytorch/ao/blob/039cef4ad546716aa04cd54c461feb173f7fe403/tutorials/developer_api_guide/export_to_executorch.py#L54 where TorchAO overrides Embedding.weight with a tensor subclass and then do attribute access inside it. We have to solve this problem in both strict and non-strict because even when dynamo translates subclass.inner_tensor into a fx Graph, the underlying tracer that converts torch IR to aten IR will need to handle subclass.inner_tensor as well.
I think there are roughly two ways to implement this:
1) Override getattr on tensor in export to monkey patch inner tensors as properties and add torch function handler 
2) When we first see a subclass tensor in make_fx, attach proxy to its' call inner tensors.

I tried implementing (1) here: #143518, but it turned out to be quite intrusive. So I prefer (2) for now. Only downside for (2) is we are creating proxy for unnecessarily many inner tensors but i think it is ok because:
1) torch.compile will never see tensor subclass in make_fx so it won't regress any tracing speed
2) Hopefully tensor subclasses that are used in export are not that nest-y. 

I also noticed a small bug in tensor subclass unwrapping logic. cc IvanKobzarev 
It seems easier if we just implement it recursively so that it is easier to track the inner attrs to corresponding plain tensors and both aot_autograd and fake_tensor implement subclass unwrapping recursively. 



cc ezyang SherlockNoMad EikanWang jgong5 wenzhe-nrv

Differential Revision: [D67531713](https://our.internmc.facebook.com/intern/diff/D67531713)

[ghstack-poisoned]
tugsbayasgalan pushed a commit that referenced this pull request Dec 22, 2024

This is a draft PR that tries to prototype how to capture attribute access in pre-dispatch IR. The motivating use case is: https://github.com/pytorch/ao/blob/039cef4ad546716aa04cd54c461feb173f7fe403/tutorials/developer_api_guide/export_to_executorch.py#L54 where TorchAO overrides Embedding.weight with a tensor subclass and then do attribute access inside it. We have to solve this problem in both strict and non-strict because even when dynamo translates subclass.inner_tensor into a fx Graph, the underlying tracer that converts torch IR to aten IR will need to handle subclass.inner_tensor as well.
I think there are roughly two ways to implement this:
1) Override getattr on tensor in export to monkey patch inner tensors as properties and add torch function handler 
2) When we first see a subclass tensor in make_fx, attach proxy to its' call inner tensors.

I tried implementing (1) here: #143518, but it turned out to be quite intrusive. So I prefer (2) for now. Only downside for (2) is we are creating proxy for unnecessarily many inner tensors but i think it is ok because:
1) torch.compile will never see tensor subclass in make_fx so it won't regress any tracing speed
2) Hopefully tensor subclasses that are used in export are not that nest-y. 

I also noticed a small bug in tensor subclass unwrapping logic. cc IvanKobzarev 
It seems easier if we just implement it recursively so that it is easier to track the inner attrs to corresponding plain tensors and both aot_autograd and fake_tensor implement subclass unwrapping recursively. 



cc ezyang SherlockNoMad EikanWang jgong5 wenzhe-nrv

Differential Revision: [D67531713](https://our.internmc.facebook.com/intern/diff/D67531713)

[ghstack-poisoned]
@github-actions
github-actions Bot deleted the gh/tugsbayasgalan/281/head branch February 14, 2025 02:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants