Add inner / outer op (#348)

* inner / outer impl

* python tests

* ops list and ack

* updated descriptions

* use test helper

* removed dtype check and flatten outer to 1-D

* updated docs

* just use the reshape to flatten
This commit is contained in:
Diogo
2024-01-07 12:01:09 -05:00
committed by GitHub
parent 6ea6b4258d
commit 449b43762e
7 changed files with 140 additions and 5 deletions

View File

@@ -3250,4 +3250,46 @@ void init_ops(py::module_& m) {
Returns:
result (array): The tensor dot product.
)pbdoc");
m.def(
"inner",
&inner,
"a"_a,
"b"_a,
py::pos_only(),
py::kw_only(),
"stream"_a = none,
R"pbdoc(
inner(a: array, b: array, /, *, stream: Union[None, Stream, Device] = None) -> array
Ordinary inner product of vectors for 1-D arrays, in higher dimensions a sum product over the last axes.
Args:
a (array): Input array
b (array): Input array
Returns:
result (array): The inner product.
)pbdoc");
m.def(
"outer",
&outer,
"a"_a,
"b"_a,
py::pos_only(),
py::kw_only(),
"stream"_a = none,
R"pbdoc(
outer(a: array, b: array, /, *, stream: Union[None, Stream, Device] = None) -> array
Compute the outer product of two 1-D arrays, if the array's passed are not 1-D a flatten op will be run beforehand.
Args:
a (array): Input array
b (array): Input array
Returns:
result (array): The outer product.
)pbdoc");
}

View File

@@ -1547,6 +1547,34 @@ class TestOps(mlx_tests.MLXTestCase):
dims=([2, 1, 3], [1, 2, 0]),
)
def test_inner(self):
self.assertCmpNumpy([(3,), (3,)], mx.inner, np.inner)
self.assertCmpNumpy([(1, 1, 2), (3, 2)], mx.inner, np.inner)
self.assertCmpNumpy([(2, 3, 4), (4,)], mx.inner, np.inner)
def test_outer(self):
self.assertCmpNumpy([(3,), (3,)], mx.outer, np.outer)
self.assertCmpNumpy(
[
mx.ones(
5,
),
mx.linspace(-2, 2, 5),
],
mx.outer,
np.outer,
)
self.assertCmpNumpy(
[
1j * mx.linspace(2, -2, 5),
mx.ones(
5,
),
],
mx.outer,
np.outer,
)
if __name__ == "__main__":
unittest.main()