Skip to content
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
4 changes: 3 additions & 1 deletion keras/src/tree/optree_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,12 @@ def is_nested(structure):

def traverse(func, structure, top_down=True):
# From https://github.com/google/jax/pull/19695
structure_id = id(structure)

def traverse_children():
children, treedef = optree.tree_flatten(
structure,
is_leaf=lambda x: x is not structure,
is_leaf=lambda x: id(x) != structure_id,
none_is_leaf=True,
namespace="keras",
)
Expand Down
7 changes: 5 additions & 2 deletions keras/src/tree/torchtree_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,12 @@ def func(x):
)
return None

structure_id = id(structure)

def traverse_children():
children, treedef = torch_tree.tree_flatten(
structure,
is_leaf=lambda x: x is not structure,
is_leaf=lambda x: id(x) != structure_id,
)
if treedef.num_nodes == 1 and treedef.num_leaves == 1:
return structure
Expand All @@ -62,7 +64,7 @@ def traverse(func, structure, top_down=True):
def traverse_children():
children, treedef = torch_tree.tree_flatten(
structure,
is_leaf=lambda x: x is not structure,
is_leaf=lambda x: id(x) != structure_id,
)
if treedef.num_nodes == 1 and treedef.num_leaves == 1:
return structure
Expand All @@ -73,6 +75,7 @@ def traverse_children():
)

structure = _dict_to_ordered_dict(structure)
structure_id = id(structure)
if top_down:
ret = func(structure)
if ret is None:
Expand Down