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] Fixes matrix-vector multiplication #6014

Merged
merged 8 commits into from
Sep 15, 2022
Merged
Show file tree
Hide file tree
Changes from 4 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
12 changes: 12 additions & 0 deletions python/taichi/lang/matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,10 @@ def _get_entry_to_infer(self, arr):
return _MatImpl() if is_matrix else _VecImpl()


def is_vector(x):
return isinstance(x, Vector) or getattr(x, "ndim", None) == 1


@_gen_swizzles
class Matrix(TaichiOperations):
"""The matrix class.
Expand Down Expand Up @@ -541,6 +545,11 @@ def __matmul__(self, other):

"""
assert isinstance(other, Matrix), "rhs of `@` is not a matrix / vector"
if is_vector(self) and not is_vector(other):
# left multiplication
assert self.n == other.m, f"Dimension mismatch between shapes ({self.n}, {self.m}), ({other.n}, {other.m})"
return other.transpose() @ self
# right multiplication
assert self.m == other.n, f"Dimension mismatch between shapes ({self.n}, {self.m}), ({other.n}, {other.m})"
entries = []
for i in range(self.n):
Expand All @@ -550,6 +559,9 @@ def __matmul__(self, other):
for k in range(1, other.n):
acc = acc + self(i, k) * other(k, j)
entries[i].append(acc)
if is_vector(other) and other.m == 1:
# TODO: remove `ndim` when #5783 is merged
return Vector(entries, ndim=1)
return Matrix(entries)

# host access & python scope operation
Expand Down
20 changes: 19 additions & 1 deletion tests/python/test_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def func(t: ti.i32):
m += ti.Matrix([[3, 4], [5, t]])
print(m @ v)
print(r.x, r.y, r.z, r.w)
s = w.transpose() @ m
s = w @ m
print(s)
print(m)

Expand Down Expand Up @@ -699,3 +699,21 @@ def bar():
with pytest.raises(TaichiCompilationError,
match=r'Expected 2 indices, got 1'):
bar()


@test_utils.test(arch=get_host_arch_list(), debug=True)
def test_matrix_vector_multiplication():
mat = ti.math.mat3(1)
vec = ti.math.vec3(3)
r = mat @ vec
for i in range(3):
assert r[i] == 9

@ti.kernel
def foo():
mat = ti.math.mat3(1)
vec = ti.math.vec3(3)
r = mat @ vec
assert r[0] == r[1] == r[2] == 9

foo()