Skip to content
Draft
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: 6 additions & 6 deletions transformer_lens/FactoredMatrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,9 @@ def __matmul__(
"FactoredMatrix",
],
) -> Union["FactoredMatrix", Float[torch.Tensor, "... ldim"]]:
if isinstance(other, torch.Tensor):
if isinstance(other, FactoredMatrix):
return (self @ other.A) @ other.B
else:
if other.ndim < 2:
# It's a vector, so we collapse the factorisation and just return a vector
# Squeezing/Unsqueezing is to preserve broadcasting working nicely
Expand All @@ -79,8 +81,6 @@ def __matmul__(
return FactoredMatrix(self.A, self.B @ other)
else:
return FactoredMatrix(self.AB, other)
elif isinstance(other, FactoredMatrix):
return (self @ other.A) @ other.B

@overload
def __rmatmul__( # type: ignore
Expand All @@ -107,7 +107,9 @@ def __rmatmul__( # type: ignore
"FactoredMatrix",
],
) -> Union["FactoredMatrix", Float[torch.Tensor, "... rdim"]]:
if isinstance(other, torch.Tensor):
if isinstance(other, FactoredMatrix):
return other.A @ (other.B @ self)
else:
assert (
other.size(-1) == self.ldim
), f"Left matrix must match on inner dimension, shapes were self: {self.shape}, other:{other.shape}"
Expand All @@ -118,8 +120,6 @@ def __rmatmul__( # type: ignore
return FactoredMatrix(other @ self.A, self.B)
else:
return FactoredMatrix(other, self.AB)
elif isinstance(other, FactoredMatrix):
return other.A @ (other.B @ self)

def __mul__(self, scalar: Union[int, float, torch.Tensor]) -> FactoredMatrix:
"""
Expand Down