Open3D icon indicating copy to clipboard operation
Open3D copied to clipboard

inconsistent behavior of as_tuple in nonzero method between open3d and pytorch

Open vincentme opened this issue 11 months ago • 1 comments

Checklist

Describe the issue

Seems that the behavior of as_tuple in nonzero method is not consistent with pytorch, and it is reversed from the meaning of as_tuple.

For instance, a.nonzero(as_tuple=True) retur a tensor and a.nonzero(as_tuple=False) return a list of tensors.

Steps to reproduce the bug

import open3d.core as o3c

a = o3c.Tensor([[3, 0, 0], [0, 4, 0], [5, 6, 0]])

print("a = \n{}\n".format(a))
print("a.nonzero() = \n{}\n".format(a.nonzero()))
print("a.nonzero(as_tuple = True) = \n{}".format(a.nonzero(as_tuple=True)))


import torch

a_tr = torch.Tensor([[3, 0, 0], [0, 4, 0], [5, 6, 0]])

print()
print("a_tr = \n{}\n".format(a_tr))
print("a_tr.nonzero() = \n{}\n".format(a_tr.nonzero()))
print("a_tr.nonzero(as_tuple = True) = \n{}".format(a_tr.nonzero(as_tuple=True)))

Error message

a = 
[[3 0 0],
 [0 4 0],
 [5 6 0]]
Tensor[shape={3, 3}, stride={3, 1}, Int64, CPU:0, 0x55d13980e480]

a.nonzero() = 
[[0 1 2 2]
Tensor[shape={4}, stride={1}, Int64, CPU:0, 0x55d139807770], [0 1 0 1]
Tensor[shape={4}, stride={1}, Int64, CPU:0, 0x55d134c006a0]]

a.nonzero(as_tuple = True) = 
[[0 1 2 2],
 [0 1 0 1]]
Tensor[shape={2, 4}, stride={4, 1}, Int64, CPU:0, 0x55d139b75c00]

a_tr = 
tensor([[3., 0., 0.],
        [0., 4., 0.],
        [5., 6., 0.]])

a_tr.nonzero() = 
tensor([[0, 0],
        [1, 1],
        [2, 0],
        [2, 1]])

a_tr.nonzero(as_tuple = True) = 
(tensor([0, 1, 2, 2]), tensor([0, 1, 0, 1]))

Expected behavior

No response

Open3D, Python and System information

- Operating system: Ubuntu 24.04 
- Python version: Python 3.12
- Open3D version: output from python: 0.19
- System architecture: x86 
- Is this a remote workstation?: no
- How did you install Open3D?: pip

Additional information

No response

vincentme avatar Feb 09 '25 05:02 vincentme

Yeah, there are 2 things here. The non tuple version is transposed compared to numpy and pytorch. Debatable if this is a bug.

But the fact that the "as_tuple" parameter is inverted is a bug. The documentation even says that it's supposed to be the other way around: https://www.open3d.org/docs/latest/tutorial/core/tensor.html#Nonzero-operations (0.19.0: https://www.open3d.org/docs/0.19.0/tutorial/core/tensor.html#Nonzero-operations)

Kroppeb avatar Nov 03 '25 10:11 Kroppeb