@@ -78,6 +78,36 @@ impl Array {
7878 ( 0 ..ndim) . map ( |i| unsafe { * ptr. add ( i) } ) . collect ( )
7979 }
8080
81+ /// Strides of the array, in elements (not bytes), one per dimension.
82+ pub fn strides ( & self ) -> Vec < usize > {
83+ let ndim = self . ndim ( ) ;
84+ // SAFETY: mlx guarantees the returned pointer is valid for `ndim`
85+ // `size_t`s.
86+ let ptr = unsafe { sys:: mlx_array_strides ( self . handle ) } ;
87+ ( 0 ..ndim) . map ( |i| unsafe { * ptr. add ( i) } ) . collect ( )
88+ }
89+
90+ /// Whether the array is laid out row-major (C-order) contiguously.
91+ ///
92+ /// Computed from the public shape + strides, so a raw read of the storage
93+ /// buffer yields elements in logical row-major order iff this is true.
94+ fn is_row_contiguous ( & self ) -> bool {
95+ let shape = self . shape ( ) ;
96+ let strides = self . strides ( ) ;
97+ // Expected row-major stride for axis i is the product of all later
98+ // dimensions. Walk from the last axis, tracking that running product.
99+ // Size-1 axes impose no constraint (any stride works), so skip them.
100+ let mut expected: usize = 1 ;
101+ for i in ( 0 ..shape. len ( ) ) . rev ( ) {
102+ let dim = shape[ i] as usize ;
103+ if dim != 1 && strides[ i] != expected {
104+ return false ;
105+ }
106+ expected *= dim;
107+ }
108+ true
109+ }
110+
81111 /// Forces evaluation of this array.
82112 ///
83113 /// MLX is lazy: ops build a graph and only compute when the result is
@@ -115,10 +145,43 @@ impl Array {
115145 /// The element type `T` selects the accessor at compile time, e.g.
116146 /// `a.to_vec::<f32>()`. Evaluates the array first.
117147 ///
148+ /// Row-contiguous arrays are read directly from their storage buffer.
149+ /// Non-contiguous ones (e.g. from [`transpose`](Self::transpose) or
150+ /// [`broadcast_to`](Self::broadcast_to)) are first materialized into a
151+ /// row-contiguous copy, so the result always reflects the logical
152+ /// (row-major) element order rather than the raw storage buffer.
153+ ///
118154 /// # Panics
119- /// Panics if `T::DTYPE` does not match the array's dtype.
155+ /// Panics if `T::DTYPE` does not match the array's dtype, or if
156+ /// making the array contiguous fails.
120157 pub fn to_vec < T : ArrayElement > ( & self ) -> Vec < T > {
121158 self . eval ( ) ;
159+ // Fast path: already row-major, so the storage buffer is already in
160+ // logical order — read it directly, no copy.
161+ if self . is_row_contiguous ( ) {
162+ return self . read_buffer :: < T > ( ) ;
163+ }
164+ // Slow path: strided views (transpose) and stride-0 views (broadcast)
165+ // don't lay their logical elements out contiguously, so reading the raw
166+ // pointer would return storage order (or read past real data). Only
167+ // these pay for a materialized copy.
168+ //
169+ // Run it on the CPU stream: this is a host-side data-marshalling step
170+ // (we're about to read the buffer from Rust), and it keeps `to_vec` off
171+ // the GPU stream so concurrent callers don't contend on Metal.
172+ let contiguous = self . contiguous ( & Stream :: cpu ( ) ) . unwrap_or_else ( |e| {
173+ panic ! ( "to_vec: failed to make array contiguous: {e}" ) ;
174+ } ) ;
175+ contiguous. eval ( ) ;
176+ contiguous. read_buffer :: < T > ( )
177+ }
178+
179+ /// Bulk-copies a **row-contiguous** array's storage buffer into a `Vec<T>`.
180+ ///
181+ /// # Panics
182+ /// Panics if `T::DTYPE` does not match the array's dtype. Assumes the array
183+ /// is already evaluated and row-contiguous.
184+ fn read_buffer < T : ArrayElement > ( & self ) -> Vec < T > {
122185 // SAFETY: mlx_array_dtype reads a valid handle.
123186 let dtype = unsafe { sys:: mlx_array_dtype ( self . handle ) } ;
124187 assert_eq ! (
@@ -132,15 +195,24 @@ impl Array {
132195 if len == 0 {
133196 return Vec :: new ( ) ;
134197 }
135- // SAFETY: dtype matches `T` (checked above), so mlx guarantees `len`
136- // contiguous, aligned `T` at `ptr`, valid until the array is mutated or
137- // freed. We only read (and copy out of) the slice within this call, so
138- // the borrow cannot outlive the buffer. `T: Copy`, so `to_vec` is a
139- // single bulk copy rather than `len` individual derefs.
198+ // SAFETY: dtype matches `T` (checked above) and the array is dense, so
199+ // mlx guarantees `len` contiguous, aligned `T` at `ptr`, valid until the
200+ // array is mutated or freed. We copy out of the slice within this call.
201+ // `T: Copy`, so this is a single bulk copy.
140202 let ptr = unsafe { T :: data_ptr ( self . handle ) } ;
141203 unsafe { std:: slice:: from_raw_parts ( ptr, len) } . to_vec ( )
142204 }
143205
206+ /// Returns a row-contiguous copy (or the same array if already dense).
207+ pub fn contiguous ( & self , stream : & Stream ) -> Result < Array > {
208+ error:: install ( ) ;
209+ let mut out = unsafe { sys:: mlx_array_new ( ) } ;
210+ // SAFETY: handle/stream valid; `allow_col_major = false` forces
211+ // row-major; result written into `out`.
212+ let status = unsafe { sys:: mlx_contiguous ( & mut out, self . handle , false , stream. as_raw ( ) ) } ;
213+ Self :: from_op ( out, status)
214+ }
215+
144216 /// Elementwise addition: `self + other`.
145217 pub fn add ( & self , other : & Array , stream : & Stream ) -> Result < Array > {
146218 self . binary_op ( other, stream, sys:: mlx_add)
@@ -275,6 +347,73 @@ impl Array {
275347 self . reduce_axes_op ( axes, keepdims, stream, sys:: mlx_prod_axes)
276348 }
277349
350+ /// Returns a new array with the same data reinterpreted as `shape`.
351+ ///
352+ /// The product of `shape` must equal [`size`](Self::size).
353+ pub fn reshape ( & self , shape : & [ i32 ] , stream : & Stream ) -> Result < Array > {
354+ self . shape_op ( shape, stream, sys:: mlx_reshape)
355+ }
356+
357+ /// Broadcasts the array to `shape`.
358+ pub fn broadcast_to ( & self , shape : & [ i32 ] , stream : & Stream ) -> Result < Array > {
359+ self . shape_op ( shape, stream, sys:: mlx_broadcast_to)
360+ }
361+
362+ /// Reverses the order of all axes (a full transpose).
363+ pub fn transpose ( & self , stream : & Stream ) -> Result < Array > {
364+ self . unary_op ( stream, sys:: mlx_transpose)
365+ }
366+
367+ /// Removes all axes of length 1.
368+ pub fn squeeze ( & self , stream : & Stream ) -> Result < Array > {
369+ self . unary_op ( stream, sys:: mlx_squeeze)
370+ }
371+
372+ /// Inserts a new axis of length 1 at position `axis`.
373+ pub fn expand_dims ( & self , axis : i32 , stream : & Stream ) -> Result < Array > {
374+ error:: install ( ) ;
375+ let mut out = unsafe { sys:: mlx_array_new ( ) } ;
376+ // SAFETY: handle/stream are valid; `mlx_expand_dims` writes the result into `out`.
377+ let status = unsafe { sys:: mlx_expand_dims ( & mut out, self . handle , axis, stream. as_raw ( ) ) } ;
378+ Self :: from_op ( out, status)
379+ }
380+
381+ /// Shared plumbing for `res = op(a, shape, shape_num, stream)` shape ops.
382+ fn shape_op (
383+ & self ,
384+ shape : & [ i32 ] ,
385+ stream : & Stream ,
386+ op : unsafe extern "C" fn (
387+ * mut sys:: mlx_array ,
388+ sys:: mlx_array ,
389+ * const i32 ,
390+ usize ,
391+ sys:: mlx_stream ,
392+ ) -> i32 ,
393+ ) -> Result < Array > {
394+ error:: install ( ) ;
395+ // For an empty slice `as_ptr()` is non-null but dangling; pass an
396+ // explicit null pointer so C never receives a bogus pointer.
397+ let shape_ptr = if shape. is_empty ( ) {
398+ std:: ptr:: null ( )
399+ } else {
400+ shape. as_ptr ( )
401+ } ;
402+ let mut out = unsafe { sys:: mlx_array_new ( ) } ;
403+ // SAFETY: `shape_ptr`/`shape.len()` describe a valid slice (or null/0)
404+ // for the call; all handles are valid; `op` writes into `out`.
405+ let status = unsafe {
406+ op (
407+ & mut out,
408+ self . handle ,
409+ shape_ptr,
410+ shape. len ( ) ,
411+ stream. as_raw ( ) ,
412+ )
413+ } ;
414+ Self :: from_op ( out, status)
415+ }
416+
278417 /// Shared plumbing for `res = op(a, b, stream)` binary ops.
279418 fn binary_op (
280419 & self ,
@@ -632,6 +771,59 @@ mod tests {
632771 assert_eq ! ( r. to_vec:: <f32 >( ) , vec![ 1.0 , 2.0 , 3.0 , 4.0 ] ) ;
633772 }
634773
774+ #[ test]
775+ fn reshape_changes_shape_not_data ( ) {
776+ let s = Stream :: cpu ( ) ;
777+ let a = Array :: from_slice ( & [ 1.0f32 , 2.0 , 3.0 , 4.0 , 5.0 , 6.0 ] , & [ 2 , 3 ] ) ;
778+ let r = a. reshape ( & [ 3 , 2 ] , & s) . unwrap ( ) ;
779+ assert_eq ! ( r. shape( ) , vec![ 3 , 2 ] ) ;
780+ assert_eq ! ( r. to_vec:: <f32 >( ) , vec![ 1.0 , 2.0 , 3.0 , 4.0 , 5.0 , 6.0 ] ) ;
781+ }
782+
783+ #[ test]
784+ fn row_contiguity_detection ( ) {
785+ let s = Stream :: cpu ( ) ;
786+ let a = Array :: from_slice ( & [ 1.0f32 , 2.0 , 3.0 , 4.0 , 5.0 , 6.0 ] , & [ 2 , 3 ] ) ;
787+ // Freshly built arrays are row-contiguous (fast path in to_vec).
788+ assert ! ( a. is_row_contiguous( ) ) ;
789+ // A transpose is a strided view. Strides only reflect the real layout
790+ // after evaluation (MLX is lazy), which is exactly when to_vec checks.
791+ let t = a. transpose ( & s) . unwrap ( ) ;
792+ t. eval ( ) ;
793+ assert ! ( !t. is_row_contiguous( ) ) ;
794+ }
795+
796+ #[ test]
797+ fn transpose_reverses_axes ( ) {
798+ let s = Stream :: cpu ( ) ;
799+ // [[1, 2, 3],
800+ // [4, 5, 6]] -> [[1, 4], [2, 5], [3, 6]]
801+ let a = Array :: from_slice ( & [ 1.0f32 , 2.0 , 3.0 , 4.0 , 5.0 , 6.0 ] , & [ 2 , 3 ] ) ;
802+ let t = a. transpose ( & s) . unwrap ( ) ;
803+ assert_eq ! ( t. shape( ) , vec![ 3 , 2 ] ) ;
804+ assert_eq ! ( t. to_vec:: <f32 >( ) , vec![ 1.0 , 4.0 , 2.0 , 5.0 , 3.0 , 6.0 ] ) ;
805+ }
806+
807+ #[ test]
808+ fn broadcast_to_expands ( ) {
809+ let s = Stream :: cpu ( ) ;
810+ let a = Array :: from_slice ( & [ 1.0f32 , 2.0 , 3.0 ] , & [ 3 ] ) ;
811+ let b = a. broadcast_to ( & [ 2 , 3 ] , & s) . unwrap ( ) ;
812+ assert_eq ! ( b. shape( ) , vec![ 2 , 3 ] ) ;
813+ assert_eq ! ( b. to_vec:: <f32 >( ) , vec![ 1.0 , 2.0 , 3.0 , 1.0 , 2.0 , 3.0 ] ) ;
814+ }
815+
816+ #[ test]
817+ fn squeeze_and_expand_dims ( ) {
818+ let s = Stream :: cpu ( ) ;
819+ let a = Array :: from_slice ( & [ 1.0f32 , 2.0 , 3.0 ] , & [ 1 , 3 , 1 ] ) ;
820+ let sq = a. squeeze ( & s) . unwrap ( ) ;
821+ assert_eq ! ( sq. shape( ) , vec![ 3 ] ) ;
822+
823+ let ex = sq. expand_dims ( 0 , & s) . unwrap ( ) ;
824+ assert_eq ! ( ex. shape( ) , vec![ 1 , 3 ] ) ;
825+ }
826+
635827 #[ test]
636828 fn incompatible_shapes_return_err ( ) {
637829 let s = Stream :: cpu ( ) ;
0 commit comments