Skip to content

Add _apply_fn_to_data method to TorchAOBaseTensor base class #2365

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions test/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,14 @@ def __init__(self, data):
with self.assertRaisesRegex(NotImplementedError, "arg_types"):
l.weight = torch.nn.Parameter(MyTensor(l.weight))

def test_apply_fn_to_data(self):
Copy link
Contributor

@jerryzh168 jerryzh168 Jun 13, 2025

Choose a reason for hiding this comment

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

might be good to add a small tensor and use apply_fn_to_data to implement some common methods like clone, and make sure this works functionally

self.assertTrue(hasattr(TorchAOBaseTensor, "_apply_fn_to_data"))
self.assertTrue(callable(getattr(TorchAOBaseTensor, "_apply_fn_to_data")))

method = getattr(TorchAOBaseTensor, "_apply_fn_to_data")
self.assertFalse(isinstance(method, classmethod))
self.assertFalse(isinstance(method, staticmethod))


if __name__ == "__main__":
unittest.main()
13 changes: 13 additions & 0 deletions torchao/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -577,6 +577,19 @@ def __tensor_unflatten__(
):
raise NotImplementedError("Subclasses must implement __tensor_unflatten__")

def _apply_fn_to_data(self, fn: Callable):
"""Applies a fn to all tensor components stored on this class"""
tensor_names, ctx = self.__tensor_flatten__()
new_tensors = {}
for name in tensor_names:
new_tensors[name] = fn(getattr(self, name))
return self.__class__.__tensor_unflatten__(
new_tensors,
ctx,
None,
None,
)

def __repr__(self):
raise NotImplementedError("Subclasses must implement __repr__")

Expand Down