Skip to content

Commit

Permalink
[BugFix] Fix setting non-tensors as data in NonTensorData (#864)
Browse files Browse the repository at this point in the history
  • Loading branch information
vmoens authored Jul 10, 2024
1 parent ceb9d05 commit fb4b629
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
8 changes: 4 additions & 4 deletions tensordict/tensorclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -2417,11 +2417,11 @@ def _stack_non_tensor(cls, list_of_non_tensor, dim=0):
first = list_of_non_tensor[0]

def _check_equal(a, b):
if isinstance(a, _ACCEPTED_CLASSES) or isinstance(b, _ACCEPTED_CLASSES):
return (a == b).all()
if isinstance(a, np.ndarray) or isinstance(b, np.ndarray):
return (a == b).all()
try:
if isinstance(a, _ACCEPTED_CLASSES) or isinstance(b, _ACCEPTED_CLASSES):
return (a == b).all() and a.shape == b.shape
if isinstance(a, np.ndarray) or isinstance(b, np.ndarray):
return (a == b).all() and a.shape == b.shape
iseq = a == b
except Exception:
iseq = False
Expand Down
10 changes: 10 additions & 0 deletions test/test_tensordict.py
Original file line number Diff line number Diff line change
Expand Up @@ -9127,6 +9127,16 @@ def test_nontensor_dict(self, non_tensor_data):
TensorDict.from_dict(non_tensor_data.to_dict()) == non_tensor_data
).all()

def test_nontensor_tensor(self):
t1 = torch.tensor([1, 2, 3], dtype=torch.float)
t2 = torch.tensor([1, 2, 3, 4], dtype=torch.float)
stack = NonTensorStack(NonTensorData(t1), NonTensorData(t2)) # this works fine
assert all(isinstance(t, torch.Tensor) for t in stack.tolist())
stack = torch.stack(
[NonTensorData(t1), NonTensorData(t2)]
) # this triggers an exception
assert all(isinstance(t, torch.Tensor) for t in stack.tolist())

def test_set(self, non_tensor_data):
non_tensor_data.set(("nested", "another_string"), "another string!")
assert (
Expand Down

0 comments on commit fb4b629

Please sign in to comment.