-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtree_utils.py
More file actions
82 lines (62 loc) · 2.41 KB
/
Copy pathtree_utils.py
File metadata and controls
82 lines (62 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# Copyright 2026 The dataclass_array Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tree utils.
Because `jax.tree_utils`, `tf.nest`, ... recurse inside `dca.DataclassArray`,
we need another API which doesn't.
"""
from __future__ import annotations
import collections.abc
from typing import Any, Callable, TypeVar
from etils import epy
from etils.etree.typing import Tree # pylint: disable=g-importing-member
from typing_extensions import TypeVarTuple, Unpack # pytype: disable=not-supported-yet # pylint: disable=g-multiple-import
# TODO(epot): Remove once pytype support `Unpack`
del TypeVar, TypeVarTuple, Unpack
Unpack = Any
TypeVarTuple = Any
_InsT = Any # TypeVarTuple('_InsT')
_OutT = Any # TypeVar('_OutT')
def tree_map( # pylint: disable=redefined-builtin
fn: Callable[[Unpack[Tree[_InsT]]], _OutT], # pyrefly: ignore[bad-specialization]
*trees: Unpack[Tree[_InsT]], # pyrefly: ignore[bad-specialization]
) -> Tree[_OutT]:
"""Apply a function recursively to each element of a nested data struct.
Contrary to `jax.tree_utils`, `dca.DataclassArray` are leaf when used with
this function.
Args:
fn: Function to map.
*trees: Args to pass tht fn. Should have the same structure.
Returns:
Same structure as `trees` after `fn` has been applied.
"""
arg = trees[0]
for struct_cls, map_fn in _TYPE_TO_MAP_FN.items():
if isinstance(arg, struct_cls):
return map_fn(fn, *trees)
# Leaf
return fn(*trees)
def _map_mapping(fn, *dicts):
dict_cls = type(dicts[0])
return dict_cls((k, tree_map(fn, *vals)) for k, vals in epy.zip_dict(*dicts))
def _map_sequence(fn, *lists):
list_cls = type(lists[0])
# TODO(py310): Use strict=True
return list_cls(tree_map(fn, *vals) for vals in zip(*lists))
_TYPE_TO_MAP_FN = {
dict: _map_mapping,
collections.abc.Mapping: _map_mapping,
tuple: _map_sequence,
list: _map_sequence,
collections.abc.Sequence: _map_mapping,
}