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] Keep dim names in transpose #662

Merged
merged 7 commits into from
Feb 6, 2024
Merged
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
26 changes: 15 additions & 11 deletions tensordict/_lazy.py
Original file line number Diff line number Diff line change
Expand Up @@ -2329,27 +2329,31 @@ def _transpose(self, dim0, dim1):
# example: shape = [5, 4, 3, 2, 1], stack_dim=1, dim0=1, dim1=4
# resulting shape: [5, 1, 3, 2, 4]
if dim1 == dim0 + 1:
return LazyStackedTensorDict(*self.tensordicts, stack_dim=dim1)
return LazyStackedTensorDict(
*(td.transpose(dim0, dim1 - 1) for td in self.tensordicts),
stack_dim=dim1,
)
result = LazyStackedTensorDict(*self.tensordicts, stack_dim=dim1)
else:
result = LazyStackedTensorDict(
*(td.transpose(dim0, dim1 - 1) for td in self.tensordicts),
stack_dim=dim1,
)
elif dim1 == self.stack_dim:
# example: shape = [5, 4, 3, 2, 1], stack_dim=3, dim0=1, dim1=3
# resulting shape: [5, 2, 3, 4, 1]
if dim0 + 1 == dim1:
return LazyStackedTensorDict(*self.tensordicts, stack_dim=dim0)
return LazyStackedTensorDict(
*(td.transpose(dim0 + 1, dim1) for td in self.tensordicts),
stack_dim=dim0,
)
result = LazyStackedTensorDict(*self.tensordicts, stack_dim=dim0)
else:
result = LazyStackedTensorDict(
*(td.transpose(dim0 + 1, dim1) for td in self.tensordicts),
stack_dim=dim0,
)
else:
dim0 = dim0 if dim0 < self.stack_dim else dim0 - 1
dim1 = dim1 if dim1 < self.stack_dim else dim1 - 1
return LazyStackedTensorDict(
result = LazyStackedTensorDict(
*(td.transpose(dim0, dim1) for td in self.tensordicts),
stack_dim=self.stack_dim,
)
result._td_dim_name = self._td_dim_name
return result

def _permute(
self,
Expand Down
13 changes: 12 additions & 1 deletion tensordict/_td.py
Original file line number Diff line number Diff line change
Expand Up @@ -1050,8 +1050,19 @@ def _transpose(tensor):
v1 = batch_size[dim1]
batch_size[dim1] = v0
batch_size[dim0] = v1
if self._has_names():
names = self.names
names = [
names[dim0] if i == dim1 else names[dim1] if i == dim0 else names[i]
for i in range(self.ndim)
]
else:
names = None
result = self._fast_apply(
_transpose, batch_size=torch.Size(batch_size), call_on_nested=True
_transpose,
batch_size=torch.Size(batch_size),
call_on_nested=True,
names=names,
)
self._maybe_set_shared_attributes(result)
return result
Expand Down
Loading