metaopt / optree

OpTree: Optimized PyTree Utilities
https://optree.readthedocs.io
Apache License 2.0
146 stars 7 forks source link

[BUG] Wrong tree path results with custom `is_leaf` condition #75

Closed ASEM000 closed 1 year ago

ASEM000 commented 1 year ago

Required prerequisites

What version of OpTree are you using?

0.9.1

System information

import optree as ot
import sys
print(ot.__version__)
# 0.9.1
print(sys.version, sys.platform)
# 3.11.0 | packaged by conda-forge | (main, Jan 14 2023, 12:26:40) [Clang 14.0.6 ] darwin

Problem description

Incorrect path in optree.tree_flatten_with_path.

The following reproduce the problem

Reproducible example code

import optree as ot
import sys
print(ot.__version__)
# 0.9.1
print(sys.version, sys.platform)
# 3.11.0 | packaged by conda-forge | (main, Jan 14 2023, 12:26:40) [Clang 14.0.6 ] darwin

tree = {"a":1, "b":2, "c": [3,4,5]}

leaves,treedef = ot.tree_flatten(tree, is_leaf=lambda x: False if id(tree) ==id(x) else True)
print(leaves) # one level
# [1, 2, [3, 4, 5]]
print(ot.treespec_paths(treedef)) # one level paths
# [('a',), ('b',), ('c',)]

paths,leaves,treedef = ot.tree_flatten_with_path(tree, is_leaf=lambda x: False if id(tree) ==id(x) else True)
print(leaves) # one level
# [1, 2, [3, 4, 5]]
print(paths) # one level paths
# []

Traceback

No response

Expected behavior

Expected output is

# [('a',), ('b',), ('c',)]

Additional context

No response

XuehaiPan commented 1 year ago

Hi @ASEM000, thanks for raising this issue! It's a bug that the paths are always empty when the is_leaf argument is passed. I will open a PR to fix this.