From fe11ea08c03b33bd8d40e4257742655b3b2716ff Mon Sep 17 00:00:00 2001 From: blanky Date: Fri, 31 Jul 2026 12:10:29 +0530 Subject: [PATCH] added eye(0) support and tests --- mlx/ops.cpp | 7 ++++++- python/tests/test_ops.py | 4 ++++ tests/ops_tests.cpp | 5 +++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/mlx/ops.cpp b/mlx/ops.cpp index da1901678d..a5dc03ec66 100644 --- a/mlx/ops.cpp +++ b/mlx/ops.cpp @@ -360,10 +360,15 @@ array ones_like(const array& a, StreamOrDevice s /* = {} */) { } array eye(int n, int m, int k, Dtype dtype, StreamOrDevice s /* = {} */) { - if (n <= 0 || m <= 0) { + if (n < 0 || m < 0) { throw std::invalid_argument("[eye] N and M must be positive integers."); } array result = zeros({n, m}, dtype, s); + + if (n == 0 || m == 0) { + return result; + } + if (k >= m || -k >= n) { return result; } diff --git a/python/tests/test_ops.py b/python/tests/test_ops.py index 5d16c6e96b..86d92039f0 100644 --- a/python/tests/test_ops.py +++ b/python/tests/test_ops.py @@ -2513,8 +2513,12 @@ def test_large_binary(self): def test_eye(self): self.assertCmpNumpy([3], mx.eye, np.eye) + # Test for zero rows and columns + self.assertCmpNumpy([0], mx.eye, np.eye) # Test for non-square matrix self.assertCmpNumpy([3, 4], mx.eye, np.eye) + # Test for zero rows + self.assertCmpNumpy([0, 4], mx.eye, np.eye) # Test with positive k parameter self.assertCmpNumpy([3, 4], mx.eye, np.eye, k=1) # Test with negative k parameter diff --git a/tests/ops_tests.cpp b/tests/ops_tests.cpp index 987ee4df9b..741530aaf7 100644 --- a/tests/ops_tests.cpp +++ b/tests/ops_tests.cpp @@ -3140,6 +3140,11 @@ TEST_CASE("test eye") { CHECK_EQ(eye_3x2.shape(), Shape{3, 2}); auto expected_eye_3x2 = array({1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, {3, 2}); CHECK(array_equal(eye_3x2, expected_eye_3x2).item()); + + auto eye_0x0 = eye(0, 0); + CHECK_EQ(eye_0x0.shape(), Shape{0, 0}); + CHECK_EQ(eye_0x0.size(), 0); + CHECK_EQ(eye_0x0.dtype(), float32); } TEST_CASE("test tri") {