8000 [pytree] support PyStructSequence types for Python pytree by XuehaiPan · Pull Request #113258 · pytorch/pytorch · GitHub
[go: up one dir, main page]

Skip to content

[pytree] support PyStructSequence types for Python pytree #113258

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 143 commits into
base: gh/XuehaiPan/14/base
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
143 commits
Select commit Hold shift + click to select a range
2fc3da2
[pytree] support PyStructSequence types for Python pytree
XuehaiPan Nov 8, 2023
62f0b8d
Update on "[pytree] support PyStructSequence types for Python pytree"
XuehaiPan Nov 8, 2023
6a294a8
Update on "[pytree] support PyStructSequence types for Python pytree"
XuehaiPan Nov 8, 2023
8f546f7
Update on "[pytree] support PyStructSequence types for Python pytree"
XuehaiPan Nov 8, 2023
43a2325
Update on "[pytree] support PyStructSequence types for Python pytree"
XuehaiPan Nov 11, 2023
ebc1b27
Update on "[pytree] support PyStructSequence types for Python pytree"
XuehaiPan Nov 11, 2023
cf1ae5e
Update on "[pytree] support PyStructSequence types for Python pytree"
XuehaiPan Nov 11, 2023
8475b97
Update on "[pytree] support PyStructSequence types for Python pytree"
XuehaiPan Nov 11, 2023
d89d657
Update on "[pytree] support PyStructSequence types for Python pytree&quo 10000 t;
XuehaiPan Nov 18, 2023
2eb6fff
Update on "[pytree] support PyStructSequence types for Python pytree"
XuehaiPan Nov 18, 2023
c5fa703
Update on "[pytree] support PyStructSequence types for Python pytree"
XuehaiPan Nov 18, 2023
9a940b5
Update on "[pytree] support PyStructSequence types for Python pytree"
XuehaiPan Nov 22, 2023
380cfd0
Update on "[pytree] support PyStructSequence types for Python pytree"
XuehaiPan Nov 22, 2023
e0a01e0
Update on "[pytree] support PyStructSequence types for Python pytree"
XuehaiPan Nov 28, 2023
aa066d2
Update on "[pytree] support PyStructSequence types for Python pytree"
XuehaiPan Nov 30, 2023
d9d16a7
Update on "[pytree] support PyStructSequence types for Python pytree"
XuehaiPan Nov 30, 2023
14297e9
Update on "[pytree] support PyStructSequence types for Python pytree"
XuehaiPan Nov 30, 2023
ebc844c
Update on "[pytree] support PyStructSequence types for Python pytree"
XuehaiPan Nov 30, 2023
26faa30
Update on "[pytree] support PyStructSequence types for Python pytree"
XuehaiPan Nov 30, 2023
845f037
Update on "[pytree] support PyStructSequence types for Python pytree"
XuehaiPan Nov 30, 2023
05e7983
Update on "[pytree] support PyStructSequence types for Python pytree"
XuehaiPan Nov 30, 2023
bc3ca2f
Update on "[pytree] support PyStructSequence types for Python pytree"
XuehaiPan Dec 1, 2023
f0baf18
Update on "[pytree] support PyStructSequence types for Python pytree"
XuehaiPan Dec 1, 2023
a61ff5a
Update on "[pytree] support PyStructSequence types for Python pytree"
XuehaiPan Dec 7, 2023
6f2be9b
Update on "[pytree] support PyStructSequence types for Python pytree"
XuehaiPan Dec 8, 2023
ec64d86
Update on "[pytree] support PyStructSequence types for Python pytree"
XuehaiPan Dec 24, 2023
5e31000
Update on "[pytree] support PyStructSequence types for Python pytree"
XuehaiPan Jan 20, 2024
ed91b71
Update
XuehaiPan Mar 20, 2024
c5431ae
Update
XuehaiPan Mar 22, 2024
28605bd
Update
XuehaiPan Mar 24, 2024
484f024
Update
XuehaiPan Apr 21, 2024
28d82e5
Update
XuehaiPan Apr 21, 2024
e4224e7
Update
XuehaiPan Jun 21, 2024
78adeb4
Update
XuehaiPan Jul 22, 2024
27050fe
Update
XuehaiPan Aug 12, 2024
b0c0291
Update
XuehaiPan Oct 20, 2024
2b0c0d3
Update
XuehaiPan Oct 20, 2024
59ee2c8
Update
XuehaiPan Oct 20, 2024
0bb2611
Update
XuehaiPan Oct 20, 2024
3a8a3c4
Update
XuehaiPan Oct 20, 2024
3bc59c4
Update
XuehaiPan Oct 20, 2024
d103d6f
Update
XuehaiPan Oct 21, 2024
baf9639
Update
XuehaiPan Oct 21, 2024
2705eb0
Update
XuehaiPan Oct 21, 2024
ab26fb5
Update
XuehaiPan Oct 21, 2024
6392274
Update
XuehaiPan Oct 21, 2024
9963e2b
Update
XuehaiPan Oct 21, 2024
a0a7275
Update
XuehaiPan Oct 21, 2024
f692809
Update
XuehaiPan Oct 21, 2024
312b879
Update
XuehaiPan Oct 21, 2024
6a3a30b
Update
XuehaiPan Oct 21, 2024
0bde528
Update
XuehaiPan Oct 21, 2024
e2fbde8
Update
XuehaiPan Oct 22, 2024
0ccaa9b
Update
XuehaiPan Oct 22, 2024
61762c2
Update
XuehaiPan Oct 22, 2024
d622085
Update
XuehaiPan Oct 22, 2024
02e5a90
Update
XuehaiPan Oct 22, 2024
a6ae9ba
Update
XuehaiPan Oct 24, 2024
9d6d32d
Update
XuehaiPan Oct 24, 2024
d5cb3bb
Update
XuehaiPan Oct 24, 2024
7531a9f
Update
XuehaiPan Oct 25, 2024
81bab69
Update
XuehaiPan Oct 29, 2024
d5df9f5
Update
XuehaiPan Oct 29, 2024
0f2580c
Update
XuehaiPan Oct 29, 2024
f2429c0
Update
XuehaiPan Oct 29, 2024
35f3b8a
Update
XuehaiPan Oct 29, 2024
5987236
Update
XuehaiPan Oct 29, 2024
83d8183
Update
XuehaiPan Oct 29, 2024
607cc30
Update
XuehaiPan Oct 30, 2024
73f5fb3
Update
XuehaiPan Oct 30, 2024
2af386d
Update
XuehaiPan Nov 5, 2024
15d65d9
Update
XuehaiPan Nov 11, 2024
4fd7c75
Update
XuehaiPan Nov 17, 2024
40dadf3
Update
XuehaiPan Nov 20, 2024
a4a45b3
Update
XuehaiPan Nov 20, 2024
b2c5515
Update
XuehaiPan Nov 20, 2024
c8450bf
Update
XuehaiPan Nov 20, 2024
65c0297
Update
XuehaiPan Nov 20, 2024
92946c4
Update
XuehaiPan Nov 20, 2024
0f4b8fc
Update
XuehaiPan Nov 20, 2024
ca5f6df
Update
XuehaiPan Nov 21, 2024
735ac30
Update
XuehaiPan Nov 21, 2024
ae21d50
Update
XuehaiPan Nov 21, 2024
f5591b0
Update
XuehaiPan Nov 21, 2024
d7dd93e
Update
XuehaiPan Nov 22, 2024
d3b1ad0
Update
XuehaiPan Nov 22, 2024
ff1052b
Update
XuehaiPan Nov 26, 2024
baa1b22
Update
XuehaiPan Nov 26, 2024
6c73653
Update
XuehaiPan Nov 27, 2024
188d3ca
Update
XuehaiPan Dec 2, 2024
fe8181e
Update
XuehaiPan Dec 2, 2024
6c93d67
Update
XuehaiPan Dec 7, 2024
6cceebd
Update
XuehaiPan Dec 9, 2024
90f2365
Update
XuehaiPan Dec 13, 2024
7faa200
Update
8000 XuehaiPan Jan 13, 2025
f251e7c
Update
XuehaiPan Feb 4, 2025
ff5523d
Update
XuehaiPan Feb 25, 2025
98a7dab
Update
XuehaiPan Feb 25, 2025
74c7d88
Update
XuehaiPan Feb 25, 2025
97a7ef3
Update
XuehaiPan Feb 25, 2025
23807f0
Update
XuehaiPan Feb 25, 2025
8573d0d
Update
XuehaiPan Feb 25, 2025
ee4586e
Update
XuehaiPan Feb 25, 2025
d1848b5
Update
XuehaiPan Feb 25, 2025
b930161
Update
XuehaiPan Feb 25, 2025
bf63d7a
Update
XuehaiPan Feb 26, 2025
7bcc529
Update
XuehaiPan Feb 26, 2025
c6dbbee
Update
XuehaiPan Feb 26, 2025
c8f6b44
Update
XuehaiPan Feb 26, 2025
2d7f03a
Update
XuehaiPan Feb 26, 2025
e9741e4
Update
XuehaiPan Feb 26, 2025
a11008d
Update
XuehaiPan Feb 26, 2025
61d14ef
Update
XuehaiPan Feb 28, 2025
ecf82cc
Update
XuehaiPan Mar 3, 2025
db4ff87
Update
XuehaiPan Mar 6, 2025
0573e00
Update
XuehaiPan Mar 7, 2025
4e9fe91
Update
XuehaiPan Mar 8, 2025
8b03f5c
Update
XuehaiPan Mar 8, 2025
4dd5394
Update
XuehaiPan Mar 8, 2025
c2ae349
Update
XuehaiPan Mar 9, 2025
8e2ca8d
Update
XuehaiPan Mar 11, 2025
b23377e
Update
XuehaiPan Mar 12, 2025
cd7154e
Update
XuehaiPan Mar 13, 2025
acff96a
Update
XuehaiPan Mar 14, 2025
58d6cf7
Update
XuehaiPan Mar 20, 2025
9451abd
Update
XuehaiPan Mar 31, 2025
8976c0a
Update
XuehaiPan Mar 31, 2025
67a7b31
Update
XuehaiPan Mar 31, 2025
ea3874a
Update
XuehaiPan Apr 1, 2025
84e9321
Update
XuehaiPan Apr 2, 2025
c3c1119
Update
XuehaiPan Apr 2, 2025
a4d0a3c
Update
XuehaiPan Apr 2, 2025
9f70896
Update
XuehaiPan Apr 3, 2025
4fe3104
Update
XuehaiPan Apr 5, 2025
cfc602b
Update
XuehaiPan Apr 7, 2025
f009887
Update
XuehaiPan Apr 23, 2025
ce0fd35
Update
XuehaiPan Apr 26, 2025
4523c06
Update
XuehaiPan May 1, 2025
e4184c7
Update
8000 XuehaiPan May 5, 2025
7fb72b0
Update
XuehaiPan May 8, 2025
056a129
Update
XuehaiPan May 14, 2025
d7f944e
Update
XuehaiPan May 14, 2025
797bb0f
Update
XuehaiPan May 16, 2025
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
9 changes: 9 additions & 0 deletions test/test_pytree.py
Original file line number Diff line number Diff line change
Expand Up @@ -958,6 +958,12 @@ def test_treespec_repr(self):
python_pytree.TreeSpec(dict, [], []),
],
),
# python_pytree.tree_structure(torch.return_types.sort((torch.zeros(1), torch.zeros(1))))
python_pytree.TreeSpec(
python_pytree.structseq,
torch.return_types.sort,
[python_leafspec, python_leafspec],
),
],
)
def test_pytree_serialize(self, spec):
Expand Down Expand Up @@ -1471,6 +1477,9 @@ def test_treespec_repr(self):
cxx_pytree.tree_structure(
defaultdict(list, {"a": [0, 1], "b": [1, 2], "c": {}})
),
cxx_pytree.tree_structure(
torch.return_types.sort((torch.zeros(1), torch.zeros(1)))
),
],
)
def test_pytree_serialize(self, spec):
Expand Down
26 changes: 16 additions & 10 deletions torch/fx/_pytree.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
from typing import Any, Callable, Optional, TypeVar
from typing_extensions import NamedTuple

import torch.return_types
from torch.utils._pytree import PyTree, tree_flatten, TreeSpec
from torch.utils._pytree import PyTree, structseq, tree_flatten, TreeSpec


FlattenFuncSpec = Callable[[PyTree, TreeSpec], list]
Expand Down Expand Up @@ -93,21 +92,28 @@ def _namedtuple_flatten_spec_exact_match(d: NamedTuple, spec: TreeSpec) -> bool:
return len(d) == spec.num_children


register_pytree_flatten_spec(dict, _dict_flatten_spec, _dict_flatten_spec_exact_match)
register_pytree_flatten_spec(list, _list_flatten_spec, _list_flatten_spec_exact_match)
register_pytree_flatten_spec(
tuple,
_tuple_flatten_spec,
_tuple_flatten_spec_exact_match,
)
for return_type in torch.return_types.all_return_types:
register_pytree_flatten_spec(
return_type,
_tuple_flatten_spec,
_tuple_flatten_spec_exact_match,
)
register_pytree_flatten_spec(
list,
_list_flatten_spec,
_list_flatten_spec_exact_match,
)
register_pytree_flatten_spec(
dict,
_dict_flatten_spec,
_dict_flatten_spec_exact_match,
)
register_pytree_flatten_spec(
namedtuple, # type: ignore[arg-type]
_namedtuple_flatten_spec,
_namedtuple_flatten_spec_exact_match,
)
register_pytree_flatten_spec(
structseq,
_tuple_flatten_spec,
_tuple_flatten_spec_exact_match,
)
62 changes: 32 additions & 30 deletions torch/return_types.py
Original file line number Diff line number Diff line change
@@ -1,51 +1,53 @@
import inspect
import warnings
from typing_extensions import deprecated

import torch
from torch.utils._pytree import register_pytree_node, SequenceKey
from torch._C import _return_types as return_types


__all__ = ["pytree_register_structseq", "all_return_types"]

all_return_types = []

# error: Module has no attribute "_return_types"
return_types = torch._C._return_types # type: ignore[attr-defined]
all_return_types = []


@deprecated(
"torch.return_types.pytree_register_structseq is now a no-op "
"and will be removed in a future release.",
category=FutureWarning,
)
def pytree_register_structseq(cls):
def structseq_flatten(structseq):
return list(structseq), None

def structseq_flatten_with_keys(structseq):
values, context = structseq_flatten(structseq)
return [(SequenceKey(i), v) for i, v in enumerate(values)], context
from torch.utils._pytree import is_structseq_class

Copy link
Contributor

Choose a reason for hiding this comment

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

Do we still need this function ("pytree_register_structseq")? Are you keeping it here just for BC?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Are you keeping it here just for BC?

Yes, just for BC.

def structseq_unflatten(values, context):
return cls(values)
if is_structseq_class(cls):
return

register_pytree_node(
cls,
structseq_flatten,
structseq_unflatten,
flatten_with_keys_fn=structseq_flatten_with_keys,
)
raise TypeError(f"Class {cls!r} is not a PyStructSequence class.")


for name in dir(return_types):
if name.startswith("__"):
_name, _attr = "", None
for _name in dir(return_types):
if _name.startswith("__"):
continue

_attr = getattr(return_types, name)
globals()[name] = _attr
_attr = getattr(return_types, _name)
globals()[_name] = _attr

if not name.startswith("_"):
__all__.append(name)
if not _name.startswith("_"):
__all__.append(_name)
all_return_types.append(_attr)

with warnings.catch_warnings():
warnings.filterwarnings(
"ignore",
category=FutureWarning,
module=__name__,
append=False,
)
# Today everything in torch.return_types is a structseq, aka a "namedtuple"-like
# thing defined by the Python C-API. We're going to need to modify this when that
# is no longer the case.
# NB: I don't know how to check that something is a "structseq" so we do a fuzzy
# check for tuple
if inspect.isclass(_attr) and issubclass(_attr, tuple):
pytree_register_structseq(_attr)
for _attr in all_return_types:
if isinstance(_attr, type) and issubclass(_attr, tuple):
pytree_register_structseq(_attr)

del _name, _attr, warnings, deprecated
15 changes: 6 additions & 9 deletions torch/utils/_cxx_pytree.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,15 +253,12 @@ def _private_register_pytree_node(
for the C++ pytree only. End-users should use :func:`register_pytree_node`
instead.
"""
# TODO(XuehaiPan): remove this condition when we make Python pytree out-of-box support
# PyStructSequence types
if not optree.is_structseq_class(cls):
optree.register_pytree_node(
cls,
flatten_fn,
_reverse_args(unflatten_fn),
namespace="torch",
)
optree.register_pytree_node(
cls,
flatten_fn,
_reverse_args(unflatten_fn),
namespace="torch",
)


def _is_pytreespec_instance(obj: Any, /) -> TypeIs[TreeSpec]:
Expand Down
47 changes: 47 additions & 0 deletions torch/utils/_pytree.py
Original file line number Diff line number Diff line change
Expand Up @@ -927,6 +927,39 @@ def _deque_unflatten(values: Iterable[T], context: Context) -> deque[T]:
return deque(values, maxlen=context)


def _structseq_flatten(d: structseq[T]) -> tuple[list[T], Context]:
return list(d), type(d)


def _structseq_flatten_with_keys(
d: structseq[T],
) -> tuple[list[tuple[KeyEntry, T]], Context]:
values, context = _structseq_flatten(d)
return [(SequenceKey(i), v) for i, v in enumerate(values)], context


def _structseq_unflatten(values: Iterable[T], context: Context) -> structseq[T]:
return context(values) # type: ignore[no-any-return]


def _structseq_serialize(context: Context) -> DumpableContext:
json_structseq = {
"class_module": context.__module__,
"class_name": context.__qualname__,
}
return json_structseq


def _structseq_deserialize(dumpable_context: DumpableContext) -> Context:
class_module = dumpable_context["class_module"]
class_name = dumpable_context["class_name"]
assert isinstance(class_module, str)
assert isinstance(class_name, str)
module = importlib.import_module(class_module)
context = getattr(module, class_name)
return context


_private_register_pytree_node(
tuple,
_tuple_flatten,
Expand Down Expand Up @@ -980,6 +1013,15 @@ def _deque_unflatten(values: Iterable[T], context: Context) -> deque[T]:
serialized_type_name="collections.deque",
flatten_with_keys_fn=_deque_flatten_with_keys,
)
_private_register_pytree_node(
structseq,
_structseq_flatten,
_structseq_unflatten,
serialized_type_name="structseq",
to_dumpable_context=_structseq_serialize,
from_dumpable_context=_structseq_deserialize,
flatten_with_keys_fn=_structseq_flatten_with_keys,
)


STANDARD_DICT_TYPES: frozenset[type] = frozenset({dict, OrderedDict, defaultdict})
Expand All @@ -992,6 +1034,7 @@ def _deque_unflatten(values: Iterable[T], context: Context) -> deque[T]:
OrderedDict,
defaultdict,
deque,
structseq,
},
)

Expand All @@ -1007,6 +1050,10 @@ def _is_namedtuple_instance(tree: Any) -> bool:

def _get_node_type(tree: Any) -> Any:
node_type = type(tree)
# Only structseq types that are not explicitly registered should return `structseq`.
# If a structseq type is explicitly registered, then the actual type will be returned.
if node_type not in SUPPORTED_NODES and is_structseq_class(node_type):
return structseq
# All namedtuple types are implicitly registered as pytree nodes.
# XXX: Other parts of the codebase expect namedtuple types always return
# `namedtuple` instead of the actual namedtuple type. Even if the type
Expand Down
Loading
0