mirror of
https://github.com/pytorch/pytorch.git
synced 2025-11-01 22:14:53 +08:00
Compare commits
320 Commits
mlazos/use
...
ciflow/tru
| Author | SHA1 | Date | |
|---|---|---|---|
| 05b98392d1 | |||
| de47db1cfb | |||
| 5eb5a20f97 | |||
| 31489d30bd | |||
| be1e65f502 | |||
| 5aa2b2289a | |||
| 79a2dbe9ec | |||
| 942125a6b4 | |||
| ba819dc881 | |||
| 700b6d22e8 | |||
| fa21c89451 | |||
| 7ad880e219 | |||
| 1be59e9fde | |||
| f30affbef0 | |||
| f42a2f1441 | |||
| e154a852fd | |||
| 1d0555100e | |||
| 3e2800dc1c | |||
| ad0a47d92b | |||
| 73997578c7 | |||
| 43fffb8595 | |||
| 2e8442fac4 | |||
| bb1ff5a369 | |||
| 77cbd4e043 | |||
| a83ce9d5fe | |||
| c95331cd83 | |||
| 1efebd5638 | |||
| a0dbea65e6 | |||
| 13c9ef51d9 | |||
| 6833d2f254 | |||
| 94d89dbf93 | |||
| 3f148162d3 | |||
| b0caf4fdb6 | |||
| 45f4d0dda5 | |||
| 54b5c6e74f | |||
| 951ea096b8 | |||
| b982c1a717 | |||
| 0afa77db11 | |||
| f577b631f8 | |||
| 33e67d1dd1 | |||
| 029d95db8e | |||
| 6f26bc7b67 | |||
| e34d064b52 | |||
| d88137444d | |||
| 087c7b2f5f | |||
| e263e3aa79 | |||
| a2bb393c35 | |||
| f750ebdb21 | |||
| 4b154faad1 | |||
| 8ef111eb54 | |||
| d665e57c3b | |||
| 99b18ec71a | |||
| 81e6b015d7 | |||
| e44bdcbd75 | |||
| 9efa19ccee | |||
| 8ddb577253 | |||
| e635263dcd | |||
| 576feb523b | |||
| 2fc047bd9f | |||
| 745a9d962b | |||
| abae549796 | |||
| 141a10e1c7 | |||
| 7e0f5462b3 | |||
| c91f575aed | |||
| f72b55e91a | |||
| 1115e0fc50 | |||
| 5515da310e | |||
| 643f208d77 | |||
| 22947d7c07 | |||
| 45a3e195ef | |||
| f61beebf00 | |||
| cf716c9688 | |||
| 69f80f4784 | |||
| 416b3ace72 | |||
| e5b6f6349b | |||
| 7d7c5ae8e6 | |||
| 183358a9f1 | |||
| 4cdc74b9f7 | |||
| a5c5404553 | |||
| 59dca2d82f | |||
| 2e3b261908 | |||
| 8077299bd2 | |||
| 197d5b4329 | |||
| 391ac27a26 | |||
| 67c9aea71d | |||
| ee326e80e5 | |||
| 690337abef | |||
| e9d6c69d39 | |||
| 22427995f6 | |||
| c0a2be67c4 | |||
| afa0b4695f | |||
| 40df9f673f | |||
| 8673d9897b | |||
| 7b58f15e10 | |||
| 1d1a757bfe | |||
| 40876a33cd | |||
| 760acdc5e1 | |||
| 8d98e7acd6 | |||
| 70a0491b41 | |||
| df9eb561f4 | |||
| dae2fd762e | |||
| dec95a75ad | |||
| b797ea9517 | |||
| e5d2c8f12f | |||
| a9d4c2d592 | |||
| e2fd435d78 | |||
| 0fc2587fd0 | |||
| ca6372ceec | |||
| bbe07eb5fc | |||
| 89964801b6 | |||
| 2c22765284 | |||
| 501add1e2c | |||
| 4b5925ba69 | |||
| 019f8ed4bd | |||
| 17ec427a57 | |||
| 9e093f979b | |||
| 7ebca96122 | |||
| 14a46ede88 | |||
| ab23e9b30c | |||
| 311a537282 | |||
| 5a6aec8adb | |||
| ce179d1444 | |||
| 3ea6e9451f | |||
| 5962bd90c4 | |||
| e0fe4fe5bb | |||
| 4d0c4e6896 | |||
| d517304a1b | |||
| fadd417340 | |||
| 1609c4d5f0 | |||
| 21dfc971e5 | |||
| b71fafd7ee | |||
| 0a505caad6 | |||
| 13d10c6079 | |||
| 5ca27b33d9 | |||
| ffc158cb09 | |||
| c85a982eb6 | |||
| 76de3696e2 | |||
| 884b510df1 | |||
| 6295224fb9 | |||
| a380b160f3 | |||
| 36cc0a6f00 | |||
| d686ab3647 | |||
| b72851c401 | |||
| 267d766992 | |||
| f3e9391814 | |||
| 2e1a2bd3c6 | |||
| b061f4e769 | |||
| 5bebdf42c7 | |||
| f9c861584f | |||
| ec19497b20 | |||
| 97e64709fc | |||
| c2f1967480 | |||
| f4b033fdf4 | |||
| 2c25cc7084 | |||
| 2f231de458 | |||
| fecce12d46 | |||
| 40ad21a93b | |||
| 928ebf50bc | |||
| 23256b321b | |||
| ca51b0eec9 | |||
| 2f912e0c32 | |||
| 788c7b6f8f | |||
| 7ece048762 | |||
| 3f353cafad | |||
| 5f5c7b48d2 | |||
| 880d3ddfdc | |||
| 29fba0504d | |||
| 766339d76b | |||
| 40be6bcd1a | |||
| 601fd57c21 | |||
| 4391105988 | |||
| f1ad58bb26 | |||
| 9da99a0dbc | |||
| 9daa07c7ed | |||
| fe04454c81 | |||
| da1133250a | |||
| 484bd9bf68 | |||
| dbe2b61267 | |||
| e549c572b6 | |||
| 75956318cb | |||
| d4cf41755a | |||
| b51f674452 | |||
| 770723e55e | |||
| a95d0d04b4 | |||
| 506d63fabd | |||
| 0efaf64271 | |||
| fa01b64af4 | |||
| 7a8cdb843a | |||
| d0b5e8526e | |||
| f4e853470f | |||
| e749f2d8cc | |||
| 7c8e8466cb | |||
| d13cbe3fb1 | |||
| 7ffad9b32c | |||
| c1f4d4265f | |||
| da88b3555e | |||
| 2d0e47b93e | |||
| 7f99a04424 | |||
| f6c74aa4e4 | |||
| 8f83ebec0e | |||
| bc4a38bd50 | |||
| 1e5c70d83c | |||
| 3a60712378 | |||
| 59c9eb5a53 | |||
| 9bf086b49c | |||
| 40407802c4 | |||
| 3ae028b157 | |||
| 7df9f45c29 | |||
| 2466732048 | |||
| 04490d5ba5 | |||
| b5d8df8fdd | |||
| 0e0d1712ed | |||
| eab4e875f5 | |||
| abbfd648d7 | |||
| b4327590cb | |||
| e1077e3c67 | |||
| 45a5317dfe | |||
| 0783f49e36 | |||
| 4fa7d72228 | |||
| 697256880d | |||
| 4709438fbd | |||
| 41f79bff88 | |||
| 166b988122 | |||
| a7ba175dfd | |||
| b55011fd0d | |||
| 75fcd3128d | |||
| d90e20f550 | |||
| a976bb7f42 | |||
| 74e3e51a41 | |||
| 16e7ce5c87 | |||
| 447d8a8eae | |||
| 3ee9bf7496 | |||
| 2f4fc7db81 | |||
| 29f0d14320 | |||
| 6ca5b803c0 | |||
| a67ffdf668 | |||
| fd68bc6638 | |||
| 0bf16a54e8 | |||
| 67aed45904 | |||
| 051141b58b | |||
| 14a4b6a5db | |||
| 1ad1ae6b69 | |||
| 90d56d25fb | |||
| b97ff03aeb | |||
| fdcf208f65 | |||
| 263a0ac4b5 | |||
| 594bc23aa6 | |||
| aea9c80348 | |||
| 4ddd5eb041 | |||
| 5caefe39b6 | |||
| abaf3329fc | |||
| 5f3730ff6d | |||
| e57d66c6a9 | |||
| fcdaf197ee | |||
| 066c7fb037 | |||
| 2ddea8a158 | |||
| 2645ccb198 | |||
| 81b174c826 | |||
| a1a75d3c22 | |||
| 134d27cf9d | |||
| cdd86ca04e | |||
| c19ca5328a | |||
| d9b1b717f5 | |||
| cecb2f8ded | |||
| 8b12a94edc | |||
| 9e41c11203 | |||
| 71d3b3b6bd | |||
| ef2b1d3361 | |||
| 9920717cb4 | |||
| 99ecfb01c5 | |||
| 2c4092e876 | |||
| e5ee365a96 | |||
| 3260ab7390 | |||
| 09e0f52037 | |||
| 817f3e7682 | |||
| 442d540fe8 | |||
| f2c379768f | |||
| 2009f30b50 | |||
| f1a2d26341 | |||
| 6262031ab6 | |||
| adf0570d87 | |||
| 368e7275fd | |||
| e973096b0b | |||
| 0ee2c92c73 | |||
| 4965702964 | |||
| 19dc9443e5 | |||
| 5263c1cb1e | |||
| ab67952e0f | |||
| e5099a0afd | |||
| f9603a17ed | |||
| 27597f8ae4 | |||
| 973f82393d | |||
| 5a3b21fd46 | |||
| 3301607cac | |||
| 33b4f01298 | |||
| 456e43f4e1 | |||
| b4f7e43b22 | |||
| 4e889a372c | |||
| 5e5e6a8d32 | |||
| 1c55add027 | |||
| f98bd3af1a | |||
| 75cf1693aa | |||
| 62bd418e76 | |||
| 58dba16e99 | |||
| 8faa309c62 | |||
| ad4ff1b88f | |||
| afe4cbcbd5 | |||
| 355d748bd1 | |||
| 4ae51d3c42 | |||
| 77f3d2d0ae | |||
| d98b7610e6 | |||
| 411b2f1d24 | |||
| f1f9fe1152 | |||
| eb4f8e9486 | |||
| 9b21fd9ef1 | |||
| 93cf5a2f80 | |||
| bdb27239fe | |||
| b8642958d0 | |||
| 3a47c15917 | |||
| b69d677726 |
@ -183,6 +183,7 @@ include_patterns = [
|
||||
'benchmarks/instruction_counts/**/*.py',
|
||||
'tools/**/*.py',
|
||||
'torchgen/**/*.py',
|
||||
'torch/utils/pytree/__init__.py',
|
||||
'torch/utils/_pytree.py',
|
||||
'torch/utils/_cxx_pytree.py',
|
||||
'torch/utils/benchmark/utils/common.py',
|
||||
|
||||
@ -76,6 +76,7 @@ sparse
|
||||
storage
|
||||
torch.testing <testing>
|
||||
torch.utils <utils>
|
||||
torch.utils.pytree
|
||||
torch.utils.benchmark <benchmark_utils>
|
||||
torch.utils.checkpoint <checkpoint>
|
||||
torch.utils.cpp_extension <cpp_extension>
|
||||
|
||||
7
docs/source/torch.utils.pytree.rst
Normal file
7
docs/source/torch.utils.pytree.rst
Normal file
@ -0,0 +1,7 @@
|
||||
torch.utils.pytree
|
||||
==================
|
||||
|
||||
.. currentmodule:: torch.utils.pytree
|
||||
|
||||
.. automodule:: torch.utils.pytree
|
||||
:members:
|
||||
@ -29,6 +29,7 @@ files =
|
||||
benchmarks/instruction_counts,
|
||||
tools,
|
||||
torch/profiler/_memory_profiler.py,
|
||||
torch/utils/pytree/__init__.py,
|
||||
torch/utils/_pytree.py,
|
||||
torch/utils/_cxx_pytree.py,
|
||||
torch/utils/benchmark/utils/common.py,
|
||||
|
||||
@ -147,8 +147,8 @@ class GraphModule(torch.nn.Module):
|
||||
|
||||
t: "f32[10]" = l_x_ + l_y_
|
||||
|
||||
trace_point_tensor_spec : torch.utils._pytree.TreeSpec = self.trace_point_tensor_spec
|
||||
trace_point_tensor_input_spec : torch.utils._pytree.TreeSpec = self.trace_point_tensor_input_spec
|
||||
trace_point_tensor_spec : torch.utils.pytree.PyTreeSpec = self.trace_point_tensor_spec
|
||||
trace_point_tensor_input_spec : torch.utils.pytree.PyTreeSpec = self.trace_point_tensor_input_spec
|
||||
res: "f32[10]" = torch.ops.higher_order.flat_apply(trace_point_tensor_spec, trace_point_tensor_input_spec, l_x_, l_y_, t); trace_point_tensor_spec = trace_point_tensor_input_spec = l_x_ = l_y_ = t = None
|
||||
return (res,)
|
||||
""", # NOQA: B950
|
||||
|
||||
@ -40,6 +40,7 @@ import torch._inductor.test_case
|
||||
import torch.onnx.operators
|
||||
import torch.utils._pytree as python_pytree
|
||||
import torch.utils.cpp_extension
|
||||
import torch.utils.pytree as generic_pytree
|
||||
from torch import Tensor
|
||||
from torch._C import FileCheck
|
||||
from torch._dynamo import allow_in_graph
|
||||
@ -104,6 +105,7 @@ from torch.testing._internal.logging_utils import logs_to_string
|
||||
|
||||
|
||||
pytree_modules = {
|
||||
"generic": generic_pytree,
|
||||
"python": python_pytree,
|
||||
}
|
||||
if python_pytree._cxx_pytree_dynamo_traceable:
|
||||
|
||||
@ -8245,7 +8245,7 @@ graph():
|
||||
%to : [num_users=1] = call_function[target=operator.getitem](args = (%tree_flatten_spec, 0), kwargs = {})
|
||||
%sum_1 : [num_users=1] = call_function[target=torch.ops.aten.sum.default](args = (%to,), kwargs = {})
|
||||
%_spec_1 : [num_users=1] = get_attr[target=_spec_1]
|
||||
%tree_unflatten : [num_users=1] = call_function[target=torch.utils._pytree.tree_unflatten](args = ((%sum_1,), %_spec_1), kwargs = {})
|
||||
%tree_unflatten : [num_users=1] = call_function[target=torch.utils.pytree.tree_unflatten](args = ((%sum_1,), %_spec_1), kwargs = {})
|
||||
return tree_unflatten""",
|
||||
)
|
||||
|
||||
|
||||
@ -249,11 +249,11 @@ def forward(self, x, y):
|
||||
_spec_0 = self._spec_0
|
||||
_spec_1 = self._spec_1
|
||||
_spec_4 = self._spec_4
|
||||
tree_flatten = torch.utils._pytree.tree_flatten((x_1, y_1)); x_1 = y_1 = None
|
||||
tree_flatten = torch.utils.pytree.tree_flatten((x_1, y_1)); x_1 = y_1 = None
|
||||
getitem = tree_flatten[0]; tree_flatten = None
|
||||
x = getitem[0]
|
||||
y = getitem[1]; getitem = None
|
||||
tree_unflatten_1 = torch.utils._pytree.tree_unflatten([x, y], _spec_1); x = y = _spec_1 = None
|
||||
tree_unflatten_1 = torch.utils.pytree.tree_unflatten([x, y], _spec_1); x = y = _spec_1 = None
|
||||
getitem_1 = tree_unflatten_1[0]; tree_unflatten_1 = None
|
||||
getitem_2 = getitem_1[0]
|
||||
getitem_3 = getitem_1[1]; getitem_1 = None
|
||||
@ -261,7 +261,7 @@ def forward(self, x, y):
|
||||
bar = self.bar(foo); foo = None
|
||||
tree_flatten_spec_1 = torch.fx._pytree.tree_flatten_spec(bar, _spec_4); bar = _spec_4 = None
|
||||
getitem_10 = tree_flatten_spec_1[0]; tree_flatten_spec_1 = None
|
||||
tree_unflatten = torch.utils._pytree.tree_unflatten((getitem_10,), _spec_0); getitem_10 = _spec_0 = None
|
||||
tree_unflatten = torch.utils.pytree.tree_unflatten((getitem_10,), _spec_0); getitem_10 = _spec_0 = None
|
||||
return tree_unflatten""",
|
||||
)
|
||||
|
||||
|
||||
@ -820,12 +820,13 @@ class TestPythonPytree(TestCase):
|
||||
script = """
|
||||
import sys
|
||||
import torch
|
||||
import torch.utils._pytree
|
||||
assert "torch.utils.pytree" in sys.modules
|
||||
assert "torch.utils._pytree" in sys.modules
|
||||
if "torch.utils._cxx_pytree" in sys.modules:
|
||||
raise RuntimeError("importing torch.utils._pytree should not import torch.utils._cxx_pytree")
|
||||
if "optree" in sys.modules:
|
||||
raise RuntimeError("importing torch.utils._pytree should not import optree")
|
||||
if not torch.utils.pytree.PYTORCH_USE_CXX_PYTREE:
|
||||
if "torch.utils._cxx_pytree" in sys.modules:
|
||||
raise RuntimeError("importing torch.utils._pytree should not import torch.utils._cxx_pytree")
|
||||
if "optree" in sys.modules:
|
||||
raise RuntimeError("importing torch.utils._pytree should not import optree")
|
||||
"""
|
||||
try:
|
||||
subprocess.check_output(
|
||||
|
||||
@ -1,3 +1,5 @@
|
||||
# Owner(s): ["module: pytree"]
|
||||
|
||||
"""
|
||||
Python polyfills for torch.utils.pytree
|
||||
"""
|
||||
@ -7,7 +9,6 @@ from __future__ import annotations
|
||||
from collections import deque
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, TYPE_CHECKING
|
||||
from typing_extensions import TypeIs
|
||||
|
||||
import torch.utils._pytree as python_pytree
|
||||
from torch.utils._pytree import BUILTIN_TYPES, STANDARD_DICT_TYPES
|
||||
@ -18,7 +19,7 @@ from ..decorators import substitute_in_graph
|
||||
if TYPE_CHECKING:
|
||||
import builtins
|
||||
from collections.abc import Callable, Iterable, Mapping
|
||||
from typing_extensions import Self
|
||||
from typing_extensions import Self, TypeIs
|
||||
|
||||
|
||||
__all__: list[str] = []
|
||||
@ -346,8 +347,10 @@ if python_pytree._cxx_pytree_dynamo_traceable:
|
||||
assert callable(self._unflatten_func)
|
||||
return self._unflatten_func(self._metadata, subtrees)
|
||||
|
||||
def _is_pytreespec_instance(obj: Any, /) -> TypeIs[PyTreeSpec]:
|
||||
return isinstance(obj, PyTreeSpec)
|
||||
def _is_pytreespec_instance(
|
||||
obj: Any, /
|
||||
) -> TypeIs[PyTreeSpec | python_pytree.TreeSpec]:
|
||||
return isinstance(obj, (PyTreeSpec, python_pytree.TreeSpec))
|
||||
|
||||
@substitute_in_graph( # type: ignore[arg-type]
|
||||
optree.treespec_leaf,
|
||||
@ -550,7 +553,7 @@ if python_pytree._cxx_pytree_dynamo_traceable:
|
||||
def tree_unflatten(treespec: PyTreeSpec, leaves: Iterable[Any]) -> PyTree:
|
||||
if not _is_pytreespec_instance(treespec):
|
||||
raise TypeError(
|
||||
f"tree_unflatten(leaves, treespec): Expected `treespec` to be instance of "
|
||||
f"Expected `treespec` to be an instance of "
|
||||
f"PyTreeSpec but got item of type {type(treespec)}."
|
||||
)
|
||||
return treespec.unflatten(leaves)
|
||||
|
||||
@ -3450,6 +3450,7 @@ MOD_INLINELIST = [
|
||||
"torch.utils._python_dispatch",
|
||||
"torch.utils._pytree",
|
||||
"torch.utils.hooks",
|
||||
"torch.utils.pytree",
|
||||
]
|
||||
assert sorted(set(MOD_INLINELIST)) == MOD_INLINELIST
|
||||
MOD_INLINELIST = set(MOD_INLINELIST)
|
||||
|
||||
@ -39,13 +39,13 @@ from torch.utils._pytree import (
|
||||
_register_pytree_node,
|
||||
Context,
|
||||
FlattenFunc,
|
||||
FromDumpableContextFn,
|
||||
FromDumpableContextFunc,
|
||||
GetAttrKey,
|
||||
KeyPath,
|
||||
keystr,
|
||||
MappingKey,
|
||||
SequenceKey,
|
||||
ToDumpableContextFn,
|
||||
ToDumpableContextFunc,
|
||||
tree_flatten_with_path,
|
||||
UnflattenFunc,
|
||||
)
|
||||
@ -485,8 +485,8 @@ def register_dataclass_as_pytree_node(
|
||||
unflatten_fn: Optional[UnflattenFunc] = None,
|
||||
*,
|
||||
serialized_type_name: Optional[str] = None,
|
||||
to_dumpable_context: Optional[ToDumpableContextFn] = None,
|
||||
from_dumpable_context: Optional[FromDumpableContextFn] = None,
|
||||
to_dumpable_context: Optional[ToDumpableContextFunc] = None,
|
||||
from_dumpable_context: Optional[FromDumpableContextFunc] = None,
|
||||
return_none_fields: bool = False,
|
||||
) -> None:
|
||||
assert dataclasses.is_dataclass(cls), (
|
||||
|
||||
@ -42,7 +42,7 @@ def _try_remove_connecting_pytrees(curr_module_node: torch.fx.Node) -> None:
|
||||
%foo : [num_users=1] = call_module[target=foo](args = (%getitem_1, %getitem_2), kwargs = {})
|
||||
%tree_flatten_spec : [num_users=1] = call_function[target=torch.fx._pytree.tree_flatten_spec](args = (%foo, %_spec_1), kwargs = {})
|
||||
%getitem_4 : [num_users=1] = call_function[target=operator.getitem](args = (%tree_flatten_spec, 0), kwargs = {})
|
||||
%tree_unflatten_1 : [num_users=2] = call_function[target=torch.utils._pytree.tree_unflatten](args = ([%getitem_4], %_spec_2), kwargs = {})
|
||||
%tree_unflatten_1 : [num_users=2] = call_function[target=torch.utils.pytree.tree_unflatten](args = ([%getitem_4], %_spec_2), kwargs = {})
|
||||
%getitem_5 : [num_users=1] = call_function[target=operator.getitem](args = (%tree_unflatten_1, 0), kwargs = {})
|
||||
%getitem_7 : [num_users=0] = call_function[target=operator.getitem](args = (%tree_unflatten_1, 1), kwargs = {})
|
||||
%getitem_6 : [num_users=1] = call_function[target=operator.getitem](args = (%getitem_5, 0), kwargs = {})
|
||||
@ -293,7 +293,7 @@ def _swap_module_helper(
|
||||
%y : [num_users=1] = placeholder[target=y]
|
||||
|
||||
%_spec_0 : [num_users=1] = get_attr[target=_spec_0]
|
||||
%tree_unflatten : [num_users=2] = call_function[target=torch.utils._pytree.tree_unflatten](args = ([%x, %y], %_spec_0), kwargs = {})
|
||||
%tree_unflatten : [num_users=2] = call_function[target=torch.utils.pytree.tree_unflatten](args = ([%x, %y], %_spec_0), kwargs = {})
|
||||
%getitem : [num_users=2] = call_function[target=operator.getitem](args = (%tree_unflatten, 0), kwargs = {})
|
||||
%getitem_1 : [num_users=1] = call_function[target=operator.getitem](args = (%getitem, 0), kwargs = {})
|
||||
%getitem_2 : [num_users=1] = call_function[target=operator.getitem](args = (%getitem, 1), kwargs = {})
|
||||
|
||||
@ -11,6 +11,7 @@ from torch.utils import (
|
||||
data as data,
|
||||
deterministic as deterministic,
|
||||
hooks as hooks,
|
||||
pytree as pytree,
|
||||
)
|
||||
from torch.utils.backend_registration import (
|
||||
generate_methods_for_privateuse1_backend,
|
||||
|
||||
@ -1,3 +1,5 @@
|
||||
# Owner(s): ["module: pytree"]
|
||||
|
||||
"""
|
||||
Contains utility functions for working with nested python data structures.
|
||||
|
||||
@ -21,13 +23,21 @@ from typing_extensions import deprecated, Self, TypeAlias, TypeIs
|
||||
import torch.utils._pytree as python_pytree
|
||||
from torch.torch_version import TorchVersion as _TorchVersion
|
||||
from torch.utils._pytree import (
|
||||
Context,
|
||||
DumpableContext,
|
||||
FlattenFunc,
|
||||
FlattenWithKeysFunc,
|
||||
FromDumpableContextFunc,
|
||||
is_namedtuple,
|
||||
is_namedtuple_class,
|
||||
is_namedtuple_instance,
|
||||
is_structseq,
|
||||
is_structseq_class,
|
||||
is_structseq_instance,
|
||||
KeyEntry,
|
||||
KeyPath,
|
||||
PyTree,
|
||||
ToDumpableContextFunc,
|
||||
UnflattenFunc,
|
||||
)
|
||||
|
||||
|
||||
@ -51,8 +61,9 @@ __all__ = [
|
||||
"FlattenFunc",
|
||||
"UnflattenFunc",
|
||||
"DumpableContext",
|
||||
"ToDumpableContextFn",
|
||||
"FromDumpableContextFn",
|
||||
"ToDumpableContextFunc",
|
||||
"FromDumpableContextFunc",
|
||||
"PyTreeSpec",
|
||||
"TreeSpec",
|
||||
"LeafSpec",
|
||||
"keystr",
|
||||
@ -99,19 +110,8 @@ S = TypeVar("S")
|
||||
U = TypeVar("U")
|
||||
R = TypeVar("R")
|
||||
|
||||
|
||||
TreeSpec: TypeAlias = PyTreeSpec
|
||||
|
||||
Context = Any
|
||||
PyTree = Any
|
||||
FlattenFunc = Callable[[PyTree], tuple[list[Any], Context]]
|
||||
UnflattenFunc = Callable[[Iterable[Any], Context], PyTree]
|
||||
OpTreeUnflattenFunc = Callable[[Context, Iterable[Any]], PyTree]
|
||||
DumpableContext = Any # Any json dumpable text
|
||||
ToDumpableContextFn = Callable[[Context], DumpableContext]
|
||||
FromDumpableContextFn = Callable[[DumpableContext], Context]
|
||||
KeyPath = tuple[KeyEntry, ...]
|
||||
FlattenWithKeysFunc = Callable[[PyTree], tuple[list[tuple[KeyEntry, Any]], Any]]
|
||||
OpTreeUnflattenFunc: TypeAlias = Callable[[Context, Iterable[Any]], PyTree]
|
||||
|
||||
|
||||
def _reverse_args(func: UnflattenFunc) -> OpTreeUnflattenFunc:
|
||||
@ -128,8 +128,8 @@ def register_pytree_node(
|
||||
unflatten_fn: UnflattenFunc,
|
||||
*,
|
||||
serialized_type_name: Optional[str] = None,
|
||||
to_dumpable_context: Optional[ToDumpableContextFn] = None,
|
||||
from_dumpable_context: Optional[FromDumpableContextFn] = None,
|
||||
to_dumpable_context: Optional[ToDumpableContextFunc] = None,
|
||||
from_dumpable_context: Optional[FromDumpableContextFunc] = None,
|
||||
flatten_with_keys_fn: Optional[FlattenWithKeysFunc] = None,
|
||||
) -> None:
|
||||
"""Register a container-like type as pytree node.
|
||||
@ -196,8 +196,8 @@ def _register_pytree_node(
|
||||
unflatten_fn: UnflattenFunc,
|
||||
*,
|
||||
serialized_type_name: Optional[str] = None,
|
||||
to_dumpable_context: Optional[ToDumpableContextFn] = None,
|
||||
from_dumpable_context: Optional[FromDumpableContextFn] = None,
|
||||
to_dumpable_context: Optional[ToDumpableContextFunc] = None,
|
||||
from_dumpable_context: Optional[FromDumpableContextFunc] = None,
|
||||
) -> None:
|
||||
"""Register a container-like type as pytree node for the C++ pytree only.
|
||||
|
||||
@ -247,8 +247,8 @@ def _private_register_pytree_node(
|
||||
unflatten_fn: UnflattenFunc,
|
||||
*,
|
||||
serialized_type_name: Optional[str] = None,
|
||||
to_dumpable_context: Optional[ToDumpableContextFn] = None,
|
||||
from_dumpable_context: Optional[FromDumpableContextFn] = None,
|
||||
to_dumpable_context: Optional[ToDumpableContextFunc] = None,
|
||||
from_dumpable_context: Optional[FromDumpableContextFunc] = None,
|
||||
) -> None:
|
||||
"""This is an internal function that is used to register a pytree node type
|
||||
for the C++ pytree only. End-users should use :func:`register_pytree_node`
|
||||
@ -265,8 +265,10 @@ def _private_register_pytree_node(
|
||||
)
|
||||
|
||||
|
||||
def _is_pytreespec_instance(obj: Any, /) -> TypeIs[TreeSpec]:
|
||||
return isinstance(obj, TreeSpec)
|
||||
def _is_pytreespec_instance(
|
||||
obj: Any, /
|
||||
) -> TypeIs[Union[TreeSpec, python_pytree.TreeSpec]]:
|
||||
return isinstance(obj, (TreeSpec, python_pytree.TreeSpec))
|
||||
|
||||
|
||||
def treespec_leaf() -> TreeSpec:
|
||||
@ -972,7 +974,7 @@ def treespec_dumps(treespec: TreeSpec, protocol: Optional[int] = None) -> str:
|
||||
"""Serialize a treespec to a JSON string."""
|
||||
if not _is_pytreespec_instance(treespec):
|
||||
raise TypeError(
|
||||
f"treespec_dumps(treespec): Expected `treespec` to be instance of "
|
||||
f"Expected `treespec` to be instance of "
|
||||
f"PyTreeSpec but got item of type {type(treespec)}."
|
||||
)
|
||||
|
||||
@ -993,16 +995,22 @@ def treespec_loads(serialized: str) -> TreeSpec:
|
||||
return treespec
|
||||
|
||||
|
||||
class _DummyLeaf:
|
||||
class _Asterisk(str):
|
||||
__slots__ = ()
|
||||
|
||||
def __new__(cls) -> Self:
|
||||
return super().__new__(cls, "*")
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return "*"
|
||||
return "*" # no quotes
|
||||
|
||||
|
||||
_asterisk = _Asterisk()
|
||||
del _Asterisk
|
||||
|
||||
|
||||
def treespec_pprint(treespec: TreeSpec) -> str:
|
||||
dummy_tree = tree_unflatten(
|
||||
[_DummyLeaf() for _ in range(treespec.num_leaves)],
|
||||
treespec,
|
||||
)
|
||||
dummy_tree = tree_unflatten([_asterisk] * treespec.num_leaves, treespec)
|
||||
return repr(dummy_tree)
|
||||
|
||||
|
||||
|
||||
@ -1,3 +1,5 @@
|
||||
# Owner(s): ["module: pytree"]
|
||||
|
||||
"""
|
||||
Contains utility functions for working with nested python data structures.
|
||||
|
||||
@ -20,6 +22,7 @@ import functools
|
||||
import importlib
|
||||
import importlib.metadata
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
import types
|
||||
import warnings
|
||||
@ -36,10 +39,11 @@ from typing import (
|
||||
Optional,
|
||||
overload,
|
||||
Protocol,
|
||||
TYPE_CHECKING,
|
||||
TypeVar,
|
||||
Union,
|
||||
)
|
||||
from typing_extensions import deprecated, NamedTuple, Self
|
||||
from typing_extensions import deprecated, NamedTuple, Self, TypeAlias, TypeIs
|
||||
|
||||
from torch.torch_version import TorchVersion as _TorchVersion
|
||||
|
||||
@ -50,8 +54,9 @@ __all__ = [
|
||||
"FlattenFunc",
|
||||
"UnflattenFunc",
|
||||
"DumpableContext",
|
||||
"ToDumpableContextFn",
|
||||
"FromDumpableContextFn",
|
||||
"ToDumpableContextFunc",
|
||||
"FromDumpableContextFunc",
|
||||
"PyTreeSpec",
|
||||
"TreeSpec",
|
||||
"LeafSpec",
|
||||
"keystr",
|
||||
@ -117,17 +122,21 @@ class EnumEncoder(json.JSONEncoder):
|
||||
return cast(str, super().default(obj))
|
||||
|
||||
|
||||
Context = Any
|
||||
PyTree = Any
|
||||
FlattenFunc = Callable[[PyTree], tuple[list[Any], Context]]
|
||||
UnflattenFunc = Callable[[Iterable[Any], Context], PyTree]
|
||||
DumpableContext = Any # Any json dumpable text
|
||||
ToDumpableContextFn = Callable[[Context], DumpableContext]
|
||||
FromDumpableContextFn = Callable[[DumpableContext], Context]
|
||||
ToStrFunc = Callable[["TreeSpec", list[str]], str]
|
||||
MaybeFromStrFunc = Callable[[str], Optional[tuple[Any, Context, str]]]
|
||||
KeyPath = tuple[KeyEntry, ...]
|
||||
FlattenWithKeysFunc = Callable[[PyTree], tuple[list[tuple[KeyEntry, Any]], Any]]
|
||||
Context: TypeAlias = Any
|
||||
PyTree: TypeAlias = Any
|
||||
FlattenFunc: TypeAlias = Callable[[PyTree], tuple[list[Any], Context]]
|
||||
UnflattenFunc: TypeAlias = Callable[[Iterable[Any], Context], PyTree]
|
||||
DumpableContext: TypeAlias = Any # Any json dumpable text
|
||||
ToDumpableContextFunc: TypeAlias = Callable[[Context], DumpableContext]
|
||||
FromDumpableContextFunc: TypeAlias = Callable[[DumpableContext], Context]
|
||||
ToDumpableContextFn: TypeAlias = ToDumpableContextFunc
|
||||
FromDumpableContextFn: TypeAlias = FromDumpableContextFunc
|
||||
ToStrFunc: TypeAlias = Callable[["TreeSpec", list[str]], str]
|
||||
MaybeFromStrFunc: TypeAlias = Callable[[str], Optional[tuple[Any, Context, str]]]
|
||||
KeyPath: TypeAlias = tuple[KeyEntry, ...]
|
||||
FlattenWithKeysFunc: TypeAlias = Callable[
|
||||
[PyTree], tuple[list[tuple[KeyEntry, Any]], Any]
|
||||
]
|
||||
|
||||
|
||||
# A NodeDef holds two callables:
|
||||
@ -160,8 +169,8 @@ SUPPORTED_NODES: dict[type[Any], NodeDef] = {}
|
||||
class _SerializeNodeDef(NamedTuple):
|
||||
typ: type[Any]
|
||||
serialized_type_name: str
|
||||
to_dumpable_context: Optional[ToDumpableContextFn]
|
||||
from_dumpable_context: Optional[FromDumpableContextFn]
|
||||
to_dumpable_context: Optional[ToDumpableContextFunc]
|
||||
from_dumpable_context: Optional[FromDumpableContextFunc]
|
||||
|
||||
|
||||
SUPPORTED_SERIALIZED_TYPES: dict[type[Any], _SerializeNodeDef] = {}
|
||||
@ -198,8 +207,8 @@ def register_pytree_node(
|
||||
unflatten_fn: UnflattenFunc,
|
||||
*,
|
||||
serialized_type_name: Optional[str] = None,
|
||||
to_dumpable_context: Optional[ToDumpableContextFn] = None,
|
||||
from_dumpable_context: Optional[FromDumpableContextFn] = None,
|
||||
to_dumpable_context: Optional[ToDumpableContextFunc] = None,
|
||||
from_dumpable_context: Optional[FromDumpableContextFunc] = None,
|
||||
flatten_with_keys_fn: Optional[FlattenWithKeysFunc] = None,
|
||||
) -> None:
|
||||
"""Register a container-like type as pytree node.
|
||||
@ -522,8 +531,8 @@ def _register_pytree_node(
|
||||
maybe_from_str_fn: Optional[MaybeFromStrFunc] = None, # deprecated
|
||||
*,
|
||||
serialized_type_name: Optional[str] = None,
|
||||
to_dumpable_context: Optional[ToDumpableContextFn] = None,
|
||||
from_dumpable_context: Optional[FromDumpableContextFn] = None,
|
||||
to_dumpable_context: Optional[ToDumpableContextFunc] = None,
|
||||
from_dumpable_context: Optional[FromDumpableContextFunc] = None,
|
||||
flatten_with_keys_fn: Optional[FlattenWithKeysFunc] = None,
|
||||
) -> None:
|
||||
"""Register a container-like type as pytree node for the Python pytree only.
|
||||
@ -589,8 +598,8 @@ def _private_register_pytree_node(
|
||||
unflatten_fn: UnflattenFunc,
|
||||
*,
|
||||
serialized_type_name: Optional[str] = None,
|
||||
to_dumpable_context: Optional[ToDumpableContextFn] = None,
|
||||
from_dumpable_context: Optional[FromDumpableContextFn] = None,
|
||||
to_dumpable_context: Optional[ToDumpableContextFunc] = None,
|
||||
from_dumpable_context: Optional[FromDumpableContextFunc] = None,
|
||||
flatten_with_keys_fn: Optional[FlattenWithKeysFunc] = None,
|
||||
) -> None:
|
||||
"""This is an internal function that is used to register a pytree node type
|
||||
@ -1072,7 +1081,9 @@ def _is_leaf(tree: PyTree, is_leaf: Optional[Callable[[PyTree], bool]] = None) -
|
||||
# children_specs: specs for each child of the root Node
|
||||
# num_leaves: the number of leaves
|
||||
@dataclasses.dataclass(init=True, frozen=True, eq=True, repr=False)
|
||||
class TreeSpec:
|
||||
class PyTreeSpec:
|
||||
"""Representing the structure of the pytree."""
|
||||
|
||||
type: Any
|
||||
_context: Context
|
||||
_children: list[Self]
|
||||
@ -1140,6 +1151,7 @@ class TreeSpec:
|
||||
return self._children
|
||||
|
||||
def is_leaf(self) -> bool:
|
||||
"""Test whether the treespec represents a leaf."""
|
||||
return self.num_nodes == 1 and self.num_leaves == 1
|
||||
|
||||
def children(self) -> list[Self]:
|
||||
@ -1149,12 +1161,14 @@ class TreeSpec:
|
||||
return self._children[index]
|
||||
|
||||
def flatten_up_to(self, tree: PyTree) -> list[PyTree]:
|
||||
def helper(treespec: TreeSpec, tree: PyTree, subtrees: list[PyTree]) -> None:
|
||||
"""Flatten the subtrees in ``tree`` up to the structure of this treespec and return a list of subtrees."""
|
||||
|
||||
def helper(treespec: TreeSpec, node: PyTree, subtrees: list[PyTree]) -> None:
|
||||
if treespec.is_leaf():
|
||||
subtrees.append(tree)
|
||||
subtrees.append(node)
|
||||
return
|
||||
|
||||
node_type = _get_node_type(tree)
|
||||
node_type = _get_node_type(node)
|
||||
if treespec.type not in BUILTIN_TYPES:
|
||||
# Always require custom node types to match exactly
|
||||
if node_type != treespec.type:
|
||||
@ -1163,7 +1177,7 @@ class TreeSpec:
|
||||
f"expected {treespec.type!r}, but got {node_type!r}.",
|
||||
)
|
||||
flatten_fn = SUPPORTED_NODES[node_type].flatten_fn
|
||||
children, context = flatten_fn(tree)
|
||||
children, context = flatten_fn(node)
|
||||
if len(children) != treespec.num_children:
|
||||
raise ValueError(
|
||||
f"Node arity mismatch; "
|
||||
@ -1185,10 +1199,10 @@ class TreeSpec:
|
||||
f"Node type mismatch; "
|
||||
f"expected {treespec.type!r}, but got {node_type!r}.",
|
||||
)
|
||||
if len(tree) != treespec.num_children:
|
||||
if len(node) != treespec.num_children:
|
||||
raise ValueError(
|
||||
f"Node arity mismatch; "
|
||||
f"expected {treespec.num_children}, but got {len(tree)}.",
|
||||
f"expected {treespec.num_children}, but got {len(node)}.",
|
||||
)
|
||||
|
||||
if both_standard_dict:
|
||||
@ -1200,7 +1214,7 @@ class TreeSpec:
|
||||
else treespec._context[1]
|
||||
)
|
||||
expected_keys = dict_context
|
||||
got_key_set = set(tree)
|
||||
got_key_set = set(node)
|
||||
expected_key_set = set(expected_keys)
|
||||
if got_key_set != expected_key_set:
|
||||
missing_keys = expected_key_set.difference(got_key_set)
|
||||
@ -1211,11 +1225,11 @@ class TreeSpec:
|
||||
if extra_keys:
|
||||
message += f"; extra key(s): {extra_keys}"
|
||||
raise ValueError(f"Node keys mismatch{message}.")
|
||||
children = [tree[key] for key in expected_keys]
|
||||
children = [node[key] for key in expected_keys]
|
||||
else:
|
||||
# node_type is treespec.type
|
||||
flatten_fn = SUPPORTED_NODES[node_type].flatten_fn
|
||||
children, context = flatten_fn(tree)
|
||||
children, context = flatten_fn(node)
|
||||
if (
|
||||
node_type is not deque # ignore mismatch of `maxlen` for deque
|
||||
) and context != treespec._context:
|
||||
@ -1232,6 +1246,7 @@ class TreeSpec:
|
||||
return subtrees
|
||||
|
||||
def unflatten(self, leaves: Iterable[Any]) -> PyTree:
|
||||
"""Reconstruct a pytree from the leaves."""
|
||||
if not isinstance(leaves, (list, tuple)):
|
||||
leaves = list(leaves)
|
||||
if len(leaves) != self.num_leaves:
|
||||
@ -1277,6 +1292,9 @@ class TreeSpec:
|
||||
return hash((node_type, hashable_context, tuple(self._children)))
|
||||
|
||||
|
||||
TreeSpec: TypeAlias = PyTreeSpec
|
||||
|
||||
|
||||
# NOTE: subclassing a dataclass is subtle. In order to enable reasoning about
|
||||
# this class with `dataclasses.fields`, etc., while having a simplified
|
||||
# constructor that takes no argument, we wrap with `dataclass(init=True, ...)`
|
||||
@ -1336,6 +1354,39 @@ def treespec_dict(
|
||||
return TreeSpec(dict, list(dct.keys()), list(dct.values()))
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import torch.utils._cxx_pytree as cxx
|
||||
|
||||
|
||||
def _is_pytreespec_instance(obj: Any) -> TypeIs[Union[TreeSpec, "cxx.TreeSpec"]]:
|
||||
if isinstance(obj, TreeSpec):
|
||||
return True
|
||||
if "torch.utils._cxx_pytree" in sys.modules:
|
||||
# The C++ pytree module is not always available, so we check if it is loaded.
|
||||
# If the C++ pytree module is loaded, we can check if the treespec
|
||||
# is an instance of the C++ TreeSpec class.
|
||||
from torch.utils._cxx_pytree import TreeSpec as CxxTreeSpec
|
||||
|
||||
if isinstance(obj, CxxTreeSpec):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _ensure_python_treespec_instance(
|
||||
treespec: Union[TreeSpec, "cxx.TreeSpec"],
|
||||
) -> TreeSpec:
|
||||
if isinstance(treespec, TreeSpec):
|
||||
return treespec
|
||||
|
||||
if not _is_pytreespec_instance(treespec):
|
||||
raise TypeError(
|
||||
f"Expected `treespec` to be an instance of "
|
||||
f"PyTreeSpec but got item of type {type(treespec)}."
|
||||
)
|
||||
dummy_tree = treespec.unflatten([0] * treespec.num_leaves)
|
||||
return tree_structure(dummy_tree)
|
||||
|
||||
|
||||
def tree_flatten(
|
||||
tree: PyTree,
|
||||
is_leaf: Optional[Callable[[PyTree], bool]] = None,
|
||||
@ -1366,10 +1417,10 @@ def tree_unflatten(leaves: Iterable[Any], treespec: TreeSpec) -> PyTree:
|
||||
"""Given a list of values and a TreeSpec, builds a pytree.
|
||||
This is the inverse operation of `tree_flatten`.
|
||||
"""
|
||||
if not isinstance(treespec, TreeSpec):
|
||||
if not _is_pytreespec_instance(treespec):
|
||||
raise TypeError(
|
||||
f"tree_unflatten(leaves, treespec): Expected `treespec` to be "
|
||||
f"instance of TreeSpec but got item of type {type(treespec)}.",
|
||||
f"Expected `treespec` to be an instance of "
|
||||
f"PyTreeSpec but got item of type {type(treespec)}."
|
||||
)
|
||||
return treespec.unflatten(leaves)
|
||||
|
||||
@ -1800,34 +1851,30 @@ def _broadcast_to_and_flatten(
|
||||
treespec: TreeSpec,
|
||||
is_leaf: Optional[Callable[[PyTree], bool]] = None,
|
||||
) -> Optional[list[Any]]:
|
||||
if not isinstance(treespec, TreeSpec):
|
||||
raise AssertionError("treespec must be a TreeSpec")
|
||||
def broadcast_prefix(
|
||||
prefix_tree: PyTree,
|
||||
full_tree: PyTree,
|
||||
is_leaf: Optional[Callable[[PyTree], bool]] = None,
|
||||
) -> list[Any]:
|
||||
result: list[Any] = []
|
||||
|
||||
if tree_is_leaf(tree, is_leaf=is_leaf):
|
||||
return [tree] * treespec.num_leaves
|
||||
if treespec.is_leaf():
|
||||
def add_leaves(x: Any, subtree: PyTree) -> None:
|
||||
subtreespec = tree_structure(subtree, is_leaf=is_leaf)
|
||||
result.extend([x] * subtreespec.num_leaves)
|
||||
|
||||
tree_map_(
|
||||
add_leaves,
|
||||
prefix_tree,
|
||||
full_tree,
|
||||
is_leaf=is_leaf,
|
||||
)
|
||||
return result
|
||||
|
||||
full_tree = tree_unflatten([0] * treespec.num_leaves, treespec)
|
||||
try:
|
||||
return broadcast_prefix(tree, full_tree, is_leaf=is_leaf)
|
||||
except ValueError:
|
||||
return None
|
||||
node_type = _get_node_type(tree)
|
||||
if node_type != treespec.type:
|
||||
return None
|
||||
|
||||
flatten_fn = SUPPORTED_NODES[node_type].flatten_fn
|
||||
child_pytrees, context = flatten_fn(tree)
|
||||
|
||||
# Check if the Node is different from the spec
|
||||
if len(child_pytrees) != treespec.num_children or context != treespec._context:
|
||||
return None
|
||||
|
||||
# Recursively flatten the children
|
||||
result: list[Any] = []
|
||||
for child, child_spec in zip(child_pytrees, treespec._children):
|
||||
flat = _broadcast_to_and_flatten(child, child_spec, is_leaf=is_leaf)
|
||||
if flat is not None:
|
||||
result += flat
|
||||
else:
|
||||
return None
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
@ -1941,11 +1988,7 @@ _SUPPORTED_PROTOCOLS[1] = _ProtocolFn(_treespec_to_json, _json_to_treespec)
|
||||
|
||||
|
||||
def treespec_dumps(treespec: TreeSpec, protocol: Optional[int] = None) -> str:
|
||||
if not isinstance(treespec, TreeSpec):
|
||||
raise TypeError(
|
||||
f"treespec_dumps(treespec, protocol): Expected `treespec` to be instance of "
|
||||
f"TreeSpec but got item of type {type(treespec)}.",
|
||||
)
|
||||
treespec = _ensure_python_treespec_instance(treespec)
|
||||
|
||||
if protocol is None:
|
||||
protocol = DEFAULT_TREESPEC_SERIALIZATION_PROTOCOL
|
||||
@ -1974,16 +2017,22 @@ def treespec_loads(serialized: str) -> TreeSpec:
|
||||
)
|
||||
|
||||
|
||||
class _DummyLeaf:
|
||||
class _Asterisk(str):
|
||||
__slots__ = ()
|
||||
|
||||
def __new__(cls) -> Self:
|
||||
return super().__new__(cls, "*")
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return "*"
|
||||
return "*" # no quotes
|
||||
|
||||
|
||||
_asterisk = _Asterisk()
|
||||
del _Asterisk
|
||||
|
||||
|
||||
def treespec_pprint(treespec: TreeSpec) -> str:
|
||||
dummy_tree = tree_unflatten(
|
||||
[_DummyLeaf() for _ in range(treespec.num_leaves)],
|
||||
treespec,
|
||||
)
|
||||
dummy_tree = tree_unflatten([_asterisk] * treespec.num_leaves, treespec)
|
||||
return repr(dummy_tree)
|
||||
|
||||
|
||||
|
||||
216
torch/utils/pytree/__init__.py
Normal file
216
torch/utils/pytree/__init__.py
Normal file
@ -0,0 +1,216 @@
|
||||
# Owner(s): ["module: pytree"]
|
||||
|
||||
"""
|
||||
Contains utility functions for working with nested python data structures.
|
||||
|
||||
A *pytree* is Python nested data structure. It is a tree in the sense that
|
||||
nodes are Python collections (e.g., list, tuple, dict) and the leaves are
|
||||
Python values. Furthermore, a pytree should not contain reference cycles.
|
||||
|
||||
pytrees are useful for working with nested collections of Tensors. For example,
|
||||
one can use `tree_map` to map a function over all Tensors inside some nested
|
||||
collection of Tensors and `tree_leaves` to get a flat list of all Tensors
|
||||
inside some nested collection. pytrees are helpful for implementing nested
|
||||
collection support for PyTorch APIs.
|
||||
"""
|
||||
|
||||
import os as _os
|
||||
import sys as _sys
|
||||
from typing import Any as _Any, Optional as _Optional
|
||||
|
||||
import torch.utils._pytree as python
|
||||
from torch.utils._exposed_in import exposed_in as _exposed_in
|
||||
from torch.utils._pytree import ( # these type aliases are identical in both implementations
|
||||
FlattenFunc,
|
||||
FlattenWithKeysFunc,
|
||||
FromDumpableContextFunc,
|
||||
PyTree,
|
||||
ToDumpableContextFunc,
|
||||
UnflattenFunc,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"PyTreeSpec",
|
||||
"register_pytree_node",
|
||||
"tree_flatten",
|
||||
"tree_unflatten",
|
||||
"tree_iter",
|
||||
"tree_leaves",
|
||||
"tree_structure",
|
||||
"tree_map",
|
||||
"tree_map_",
|
||||
"tree_map_only",
|
||||
"tree_map_only_",
|
||||
"tree_all",
|
||||
"tree_any",
|
||||
"tree_all_only",
|
||||
"tree_any_only",
|
||||
"treespec_pprint",
|
||||
"is_namedtuple",
|
||||
"is_namedtuple_class",
|
||||
"is_namedtuple_instance",
|
||||
"is_structseq",
|
||||
"is_structseq_class",
|
||||
"is_structseq_instance",
|
||||
]
|
||||
|
||||
|
||||
# NB: Once this variable is read from the environment, the underlying pytree
|
||||
# implementation is frozen. It cannot be swapped to another at runtime.
|
||||
PYTORCH_USE_CXX_PYTREE: bool = _os.getenv("PYTORCH_USE_CXX_PYTREE", "0") not in {
|
||||
"0",
|
||||
"",
|
||||
}
|
||||
|
||||
|
||||
if PYTORCH_USE_CXX_PYTREE:
|
||||
import torch.utils._cxx_pytree as cxx # noqa: F401
|
||||
|
||||
if not python._cxx_pytree_dynamo_traceable:
|
||||
raise ImportError(
|
||||
"Cannot import package `optree`. "
|
||||
"Please install `optree` via `python -m pip install --upgrade optree`. "
|
||||
"Or set the environment variable `PYTORCH_USE_CXX_PYTREE=0`."
|
||||
)
|
||||
|
||||
|
||||
_sys.modules[f"{__name__}.cxx"] = _sys.modules.get("torch.utils._cxx_pytree") # type: ignore[assignment]
|
||||
|
||||
|
||||
if not PYTORCH_USE_CXX_PYTREE:
|
||||
from torch.utils._pytree import (
|
||||
is_namedtuple,
|
||||
is_namedtuple_class,
|
||||
is_namedtuple_instance,
|
||||
is_structseq,
|
||||
is_structseq_class,
|
||||
is_structseq_instance,
|
||||
PyTreeSpec,
|
||||
register_pytree_node as _register_pytree_node,
|
||||
tree_all,
|
||||
tree_all_only,
|
||||
tree_any,
|
||||
tree_any_only,
|
||||
tree_flatten,
|
||||
tree_iter,
|
||||
tree_leaves,
|
||||
tree_map,
|
||||
tree_map_,
|
||||
tree_map_only,
|
||||
tree_map_only_,
|
||||
tree_structure,
|
||||
tree_unflatten,
|
||||
treespec_pprint,
|
||||
)
|
||||
|
||||
PyTreeSpec = _exposed_in(__name__)(PyTreeSpec) # type: ignore[misc]
|
||||
else:
|
||||
from torch.utils._cxx_pytree import ( # type: ignore[assignment,no-redef]
|
||||
is_namedtuple,
|
||||
is_namedtuple_class,
|
||||
is_namedtuple_instance,
|
||||
is_structseq,
|
||||
is_structseq_class,
|
||||
is_structseq_instance,
|
||||
PyTreeSpec,
|
||||
register_pytree_node as _register_pytree_node,
|
||||
tree_all,
|
||||
tree_all_only,
|
||||
tree_any,
|
||||
tree_any_only,
|
||||
tree_flatten,
|
||||
tree_iter,
|
||||
tree_leaves,
|
||||
tree_map,
|
||||
tree_map_,
|
||||
tree_map_only,
|
||||
tree_map_only_,
|
||||
tree_structure,
|
||||
tree_unflatten,
|
||||
treespec_pprint,
|
||||
)
|
||||
|
||||
|
||||
# Change `__module__` of reexported public APIs to 'torch.utils.pytree'
|
||||
__func_names = frozenset(
|
||||
{
|
||||
"tree_all",
|
||||
"tree_all_only",
|
||||
"tree_any",
|
||||
"tree_any_only",
|
||||
"tree_flatten",
|
||||
"tree_iter",
|
||||
"tree_leaves",
|
||||
"tree_map",
|
||||
"tree_map_",
|
||||
"tree_map_only",
|
||||
"tree_map_only_",
|
||||
"tree_structure",
|
||||
"tree_unflatten",
|
||||
"treespec_pprint",
|
||||
"is_namedtuple",
|
||||
"is_namedtuple_class",
|
||||
"is_namedtuple_instance",
|
||||
"is_structseq",
|
||||
"is_structseq_class",
|
||||
"is_structseq_instance",
|
||||
}
|
||||
)
|
||||
globals().update(
|
||||
{
|
||||
name: _exposed_in(__name__)(member)
|
||||
for name, member in globals().items()
|
||||
if name in __func_names
|
||||
}
|
||||
)
|
||||
del __func_names, _exposed_in
|
||||
|
||||
|
||||
def register_pytree_node(
|
||||
cls: type[_Any],
|
||||
/,
|
||||
# intentionally use `*_func` over `*_fn` to match annotations
|
||||
flatten_func: FlattenFunc,
|
||||
unflatten_func: UnflattenFunc,
|
||||
) -> None:
|
||||
"""Register a container-like type as pytree node.
|
||||
|
||||
Args:
|
||||
cls (type): A Python type to treat as an internal pytree node.
|
||||
flatten_func (callable): A function to be used during flattening, taking an instance of
|
||||
``cls`` and returning a pair, with (1) an iterable for the children to be flattened
|
||||
recursively, and (2) some hashable auxiliary data to be stored in the treespec and to be
|
||||
passed to the ``unflatten_func``.
|
||||
unflatten_func (callable): A function taking two arguments: the unflattened children, and
|
||||
the auxiliary data that was returned by ``flatten_func`` and stored in the treespec.
|
||||
The function should return an instance of ``cls``.
|
||||
|
||||
Example::
|
||||
|
||||
>>> # xdoctest: +SKIP
|
||||
>>> from collections import UserList
|
||||
... class MyList(UserList): pass
|
||||
>>> # Registry a Python type with lambda functions
|
||||
... register_pytree_node(
|
||||
... MyList,
|
||||
... lambda lst: (list(lst), None),
|
||||
... lambda children, _: MyList(children),
|
||||
... )
|
||||
"""
|
||||
_register_pytree_node(
|
||||
cls,
|
||||
flatten_func,
|
||||
unflatten_func,
|
||||
)
|
||||
|
||||
|
||||
def __getattr__(name: str) -> _Any:
|
||||
if name == "cxx":
|
||||
# Lazy import
|
||||
import torch.utils._cxx_pytree as cxx # noqa: F811
|
||||
|
||||
_sys.modules[f"{__name__}.cxx"] = globals()["cxx"] = cxx
|
||||
return cxx
|
||||
|
||||
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
||||
8
torch/utils/pytree/cxx.pyi
Normal file
8
torch/utils/pytree/cxx.pyi
Normal file
@ -0,0 +1,8 @@
|
||||
# Owner(s): ["module: pytree"]
|
||||
|
||||
from .._cxx_pytree import * # noqa: F403
|
||||
from .._cxx_pytree import (
|
||||
__all__ as __all__,
|
||||
_broadcast_to_and_flatten as _broadcast_to_and_flatten,
|
||||
KeyPath as KeyPath,
|
||||
)
|
||||
15
torch/utils/pytree/python.pyi
Normal file
15
torch/utils/pytree/python.pyi
Normal file
@ -0,0 +1,15 @@
|
||||
# Owner(s): ["module: pytree"]
|
||||
|
||||
from .._pytree import * # noqa: F403
|
||||
from .._pytree import (
|
||||
__all__ as __all__,
|
||||
_broadcast_to_and_flatten as _broadcast_to_and_flatten,
|
||||
arg_tree_leaves as arg_tree_leaves,
|
||||
BUILTIN_TYPES as BUILTIN_TYPES,
|
||||
GetAttrKey as GetAttrKey,
|
||||
KeyEntry as KeyEntry,
|
||||
KeyPath as KeyPath,
|
||||
MappingKey as MappingKey,
|
||||
SequenceKey as SequenceKey,
|
||||
SUPPORTED_NODES as SUPPORTED_NODES,
|
||||
)
|
||||
Reference in New Issue
Block a user