Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BugFix] Fix unbind #471

Merged
merged 6 commits into from
Jul 3, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
15 changes: 15 additions & 0 deletions benchmarks/common/common_ops_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -615,6 +615,21 @@ def main():
tdc["c", "c", "c"] = c


def test_unbind_speed(benchmark):
(td,), _ = big_nested_td()
benchmark(lambda td: td.unbind(0), td)


def test_unbind_speed_stack0(benchmark):
(td,), _ = big_nested_stacked_td()
benchmark(lambda td: td.unbind(0), td)


def test_unbind_speed_stack1(benchmark):
(td,), _ = big_nested_stacked_td()
benchmark(lambda td: td.unbind(1), td)


if __name__ == "__main__":
args, unknown = argparse.ArgumentParser().parse_known_args()
pytest.main([__file__, "--capture", "no", "--exitfirst"] + unknown)
29 changes: 15 additions & 14 deletions tensordict/tensordict.py
Original file line number Diff line number Diff line change
Expand Up @@ -2366,10 +2366,6 @@ def unbind(self, dim: int) -> tuple[TensorDictBase, ...]:
Resulting tensordicts will share the storage of the initial tensordict.

"""
idx = [
((*tuple(slice(None) for _ in range(dim)), i))
for i in range(self.shape[dim])
]
if dim < 0:
dim = self.batch_dims + dim
batch_size = torch.Size([s for i, s in enumerate(self.batch_size) if i != dim])
Expand All @@ -2378,16 +2374,18 @@ def unbind(self, dim: int) -> tuple[TensorDictBase, ...]:
names = copy(names)
names = [name for i, name in enumerate(names) if i != dim]
out = []
for _idx in idx:
out.append(
self.apply(
lambda tensor, idx=_idx: tensor[idx],
batch_size=batch_size,
)
unbind_self_dict = {key: tensor.unbind(dim) for key, tensor in self.items()}
for _idx in range(self.batch_size[dim]):
td = TensorDict(
{key: tensor[_idx] for key, tensor in unbind_self_dict.items()},
batch_size=batch_size,
_run_checks=False,
device=self.device,
_is_memmap=False,
_is_shared=False,
names=names,
)
if names is not None:
for item in out:
item.names = names
out.append(td)
if self.is_shared():
out[-1].share_memory_()
elif self.is_memmap():
Expand Down Expand Up @@ -3165,6 +3163,7 @@ def unflatten_keys(
_run_checks=False,
_is_shared=self.is_shared(),
_is_memmap=self.is_memmap(),
names=self.names,
)
else:
out = self
Expand All @@ -3176,7 +3175,9 @@ def unflatten_keys(
"Unflattening key(s) in tensordict will override existing unflattened key"
)

tensordict = TensorDict({}, batch_size=self.batch_size, device=self.device)
tensordict = TensorDict(
{}, batch_size=self.batch_size, device=self.device, names=self.names
)
if key in self.keys():
tensordict.update(self[key])
for old_key, new_key in list_of_keys:
Expand Down
8 changes: 8 additions & 0 deletions test/test_tensordict.py
Original file line number Diff line number Diff line change
Expand Up @@ -5349,6 +5349,14 @@ def test_from_dict(batch_size, batch_dims, device):
assert data["d", "g"].batch_size == torch.Size(batch_size)


def test_unbind_batchsize():
td = TensorDict({"a": TensorDict({"b": torch.zeros(2, 3)}, [2, 3])}, [2])
td["a"].batch_size
tds = td.unbind(0)
assert tds[0].batch_size == torch.Size([])
assert tds[0]["a"].batch_size == torch.Size([3])


if __name__ == "__main__":
args, unknown = argparse.ArgumentParser().parse_known_args()
pytest.main([__file__, "--capture", "no", "--exitfirst"] + unknown)