From d35e375f4fdca0b9ec6010c69c9dbd4e358384ec Mon Sep 17 00:00:00 2001 From: Isaac Hernandez Date: Tue, 1 Sep 2026 17:24:18 -0400 Subject: [PATCH 1/2] python: fix bytes() on non-contiguous arrays --- python/src/array.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/python/src/array.cpp b/python/src/array.cpp index ebc0a5d8f6..04b4f9fdbb 100644 --- a/python/src/array.cpp +++ b/python/src/array.cpp @@ -1046,9 +1046,10 @@ void init_array(nb::module_& m) { .def( "__bytes__", [](mx::array& a) { - a.eval(); + auto c = mx::contiguous(a); + c.eval(); return nb::bytes( - reinterpret_cast(a.data()), a.nbytes()); + reinterpret_cast(c.data()), c.nbytes()); }) .def( "__format__", From ea4bccda7b5a42811d8fc0dff28f9390f6343f09 Mon Sep 17 00:00:00 2001 From: Isaac Hernandez Date: Thu, 10 Sep 2026 19:12:50 -0300 Subject: [PATCH 2/2] tests: add test for bytes() on non-contiguous arrays --- python/tests/test_array.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/python/tests/test_array.py b/python/tests/test_array.py index 17e49eae1d..405838087d 100644 --- a/python/tests/test_array.py +++ b/python/tests/test_array.py @@ -2042,6 +2042,15 @@ def test_buffer_protocol(self): self.assertEqual(b"aaaaaaaaaa", ab[::2]) self.assertEqual(b"abcdefghij", ab[1::2]) + # Test bytes on non-contiguous arrays + a = mx.arange(10, dtype=mx.uint8) + self.assertEqual(bytes(a[::2]), b"\x00\x02\x04\x06\x08") + self.assertEqual(bytes(a[::-1]), b"\x09\x08\x07\x06\x05\x04\x03\x02\x01\x00") + b = mx.arange(6, dtype=mx.int32).reshape(2, 3).T + self.assertEqual(bytes(b), np.array(b).tobytes()) + c = mx.broadcast_to(mx.array([1, 2], dtype=mx.uint8), (3, 2)) + self.assertEqual(bytes(c), np.array(c).tobytes()) + def test_buffer_protocol_ref_counting(self): a = mx.arange(3) wr = weakref.ref(a)