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

[Lang] Raise an error for the semantic change of transpose() #6813

Merged
merged 3 commits into from
Dec 6, 2022
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
7 changes: 3 additions & 4 deletions python/taichi/lang/matrix_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
from taichi.lang.matrix import Matrix, Vector
from taichi.lang.matrix_ops_utils import (arg_at, arg_foreach_check,
assert_list, assert_tensor,
assert_vector, check_matmul, dim_lt,
assert_vector, check_matmul,
check_transpose, dim_lt,
is_int_const, preconditions,
same_shapes, square_matrix)
from taichi.types.annotations import template
Expand Down Expand Up @@ -142,12 +143,10 @@ def inverse(mat):
return None


@preconditions(assert_tensor)
@preconditions(check_transpose)
@pyfunc
def transpose(mat):
shape = static(mat.get_shape())
if static(len(shape) == 1):
return Vector([mat[i] for i in static(range(shape[0]))])
return Matrix([[mat[i, j] for i in static(range(shape[0]))]
for j in static(range(shape[1]))])

Expand Down
7 changes: 7 additions & 0 deletions python/taichi/lang/matrix_ops_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,3 +172,10 @@ def check_matmul(x, y):
if x_shape[1] != y_shape[0]:
return False, f'dimension mismatch between {x_shape} and {y_shape} for matrix multiplication'
return True, None


def check_transpose(x):
ok, msg = assert_tensor(x)
if ok and len(x.get_shape()) == 1:
return False, '`transpose()` cannot apply to a vector. If you want something like `a @ b.transpose()`, write `a.outer_product(b)` instead.'
return ok, msg
16 changes: 16 additions & 0 deletions tests/python/test_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -1193,3 +1193,19 @@ def verify(x):
field = ti.Vector.field(n=3, dtype=ti.f32, shape=10)
ndarray = ti.Vector.ndarray(n=3, dtype=ti.f32, shape=(10))
_test_field_and_ndarray(field, ndarray, func, verify)


@test_utils.test()
def test_vector_transpose():
@ti.kernel
def foo():
x = ti.Vector([1, 2])
y = ti.Vector([3, 4])
z = x @ y.transpose()

with pytest.raises(
TaichiCompilationError,
match=
r"`transpose\(\)` cannot apply to a vector. If you want something like `a @ b.transpose\(\)`, write `a.outer_product\(b\)` instead."
):
foo()