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

Improve missing dim error #13

Merged
merged 3 commits into from
Sep 16, 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
1 change: 1 addition & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ jobs:
name: coverage-data-${{ matrix.python-version }}
path: .coverage.*
if-no-files-found: ignore
include-hidden-files: true

Coverage:
needs: Pytest
Expand Down
3 changes: 2 additions & 1 deletion changelog.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
# Changelog

## Unreleased
## v0.3.5

- Support hashing the `folded_tensor.length` field (via a UserList), which is convenient for caching
- Improve error messaging when refolding with missing dims

## v0.3.4

Expand Down
15 changes: 11 additions & 4 deletions foldedtensor/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
except AttributeError:
DisableTorchFunctionSubclass = torch._C.DisableTorchFunction

__version__ = "0.3.4"
__version__ = "0.3.5"


class FoldedTensorLengths(UserList):
Expand Down Expand Up @@ -402,9 +402,16 @@ def refold(self, *dims: Union[Sequence[Union[int, str]], int, str]):
"sequence or each arguments to be ints or strings"
)
dims = dims[0]
dims = tuple(
dim if isinstance(dim, int) else self.full_names.index(dim) for dim in dims
)
try:
dims = tuple(
dim if isinstance(dim, int) else self.full_names.index(dim)
for dim in dims
)
except ValueError:
raise ValueError(
f"Folded tensor with available dimensions {self.full_names} "
f"could not be refolded with dimensions {list(dims)}"
)

if dims == self.data_dims:
return self
Expand Down
15 changes: 15 additions & 0 deletions tests/test_folded_tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -431,3 +431,18 @@ def test_hashable_lengths():
assert tensor.lengths is embedding(tensor).lengths
assert hash(tensor.lengths) is not None
assert hash(tensor.lengths) == hash(embedding(tensor).lengths)


def test_missing_dims():
tensor = as_folded_tensor(
[
[0, 1, 2],
[3, 4],
],
full_names=("sample", "token"),
dtype=torch.long,
)
with pytest.raises(ValueError) as e:
tensor.refold("line", "token")

assert "line" in str(e.value)
Loading