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 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
12 changes: 12 additions & 0 deletions python/taichi/lang/matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,11 @@ def __init__(self,
is_matrix = isinstance(arr[0], Iterable) and not is_vector(self)
initializer = _make_entries_initializer(is_matrix)
self.ndim = 2 if is_matrix else 1
if not is_matrix and isinstance(arr[0], Iterable):
flattened = []
for row in arr:
flattened += row
arr = flattened

if in_python_scope() or is_ref:
mat = initializer.pyscope_or_ref(arr)
Expand Down Expand Up @@ -553,6 +558,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 @@ -562,6 +572,8 @@ 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:
return Vector(entries)
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 @@ -701,6 +701,24 @@ def bar():
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()


@test_utils.test(arch=[ti.cuda, ti.cpu], real_matrix=True)
def test_local_matrix_read():

Expand Down