Skip to main content

mlx_rs/array/
mod.rs

1use crate::{
2    dtype::Dtype,
3    error::{AsSliceError, ConversionError},
4    sealed::Sealed,
5    utils::{guard::Guarded, SUCCESS},
6    Stream,
7};
8use element::FromSliceElement;
9use mlx_internal_macros::default_device;
10use mlx_sys::mlx_array;
11use num_complex::Complex;
12use std::{
13    ffi::{c_void, CStr},
14    iter::Sum,
15};
16
17mod element;
18mod operators;
19
20cfg_safetensors! {
21    mod safetensors;
22}
23
24pub use element::ArrayElement;
25
26// Not using Complex64 because `num_complex::Complex64` is actually Complex<f64>
27
28/// Type alias for `num_complex::Complex<f32>`.
29#[allow(non_camel_case_types)]
30pub type complex64 = Complex<f32>;
31
32/// An n-dimensional array.
33#[repr(transparent)]
34pub struct Array {
35    c_array: mlx_array,
36}
37
38impl Sealed for Array {}
39
40impl Sealed for &Array {}
41
42impl std::fmt::Debug for Array {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        write!(f, "{self}")
45    }
46}
47
48impl std::fmt::Display for Array {
49    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50        unsafe {
51            let mut mlx_str = mlx_sys::mlx_string_new();
52            let status = mlx_sys::mlx_array_tostring(&mut mlx_str as *mut _, self.as_ptr());
53            if status != SUCCESS {
54                return Err(std::fmt::Error);
55            }
56            let ptr = mlx_sys::mlx_string_data(mlx_str);
57            let c_str = CStr::from_ptr(ptr);
58            write!(f, "{}", c_str.to_str().map_err(|_| std::fmt::Error)?)?;
59            mlx_sys::mlx_string_free(mlx_str);
60            Ok(())
61        }
62    }
63}
64
65impl Drop for Array {
66    fn drop(&mut self) {
67        // TODO: check memory leak with some tool?
68
69        // Decrease the reference count
70        unsafe { mlx_sys::mlx_array_free(self.as_ptr()) };
71    }
72}
73
74// SAFETY: MLX 0.32.2 supports moving array handles while operations use per-thread default streams.
75unsafe impl Send for Array {}
76
77impl Array {
78    /// Create a new array from an existing mlx_array pointer.
79    ///
80    /// # Safety
81    ///
82    /// `c_array` must be a valid, independently owned MLX array handle. [`Array`] takes ownership
83    /// of that handle and frees it on drop. A borrowed handle, such as one returned by
84    /// [`Array::as_ptr`], must first be duplicated into a fresh handle with
85    /// [`mlx_sys::mlx_array_set`].
86    ///
87    /// ```no_run
88    /// use mlx_rs::Array;
89    ///
90    /// let source = Array::from_int(1);
91    /// let duplicate = unsafe {
92    ///     let mut handle = mlx_sys::mlx_array_new();
93    ///     assert_eq!(mlx_sys::mlx_array_set(&mut handle, source.as_ptr()), 0);
94    ///     Array::from_ptr(handle)
95    /// };
96    /// assert_eq!(duplicate.item_exact::<i32>(), 1);
97    /// ```
98    pub unsafe fn from_ptr(c_array: mlx_array) -> Array {
99        Self { c_array }
100    }
101
102    /// Get the underlying mlx_array pointer.
103    pub fn as_ptr(&self) -> mlx_array {
104        self.c_array
105    }
106
107    /// New array from a bool scalar.
108    pub fn from_bool(val: bool) -> Array {
109        let c_array = unsafe { mlx_sys::mlx_array_new_bool(val) };
110        Array { c_array }
111    }
112
113    /// New array from an int scalar.
114    pub fn from_int(val: i32) -> Array {
115        let c_array = unsafe { mlx_sys::mlx_array_new_int(val) };
116        Array { c_array }
117    }
118
119    /// New array from a f32 scalar.
120    pub fn from_f32(val: f32) -> Array {
121        let c_array = unsafe { mlx_sys::mlx_array_new_float32(val) };
122        Array { c_array }
123    }
124
125    /// New array from a f64 scalar.
126    pub fn from_f64(val: f64) -> Array {
127        let c_array = unsafe { mlx_sys::mlx_array_new_float64(val) };
128        Array { c_array }
129    }
130
131    /// New array from a complex scalar.
132    pub fn from_complex(val: complex64) -> Array {
133        let c_array = unsafe { mlx_sys::mlx_array_new_complex(val.re, val.im) };
134        Array { c_array }
135    }
136
137    /// New array from existing buffer.
138    ///
139    /// Please note that floating point literals are treated as f32 instead of
140    /// f64. Use [`Array::from_slice_f64`] for f64.
141    ///
142    /// # Parameters
143    ///
144    /// - `data`: A buffer which will be copied.
145    /// - `shape`: Shape of the array.
146    ///
147    /// # Panic
148    ///
149    /// - Panics if the product of the shape is not equal to the length of the
150    ///   data.
151    /// - Panics if the shape is too large.
152    pub fn from_slice<T: FromSliceElement>(data: &[T], shape: &[i32]) -> Self {
153        // Validate data size and shape
154        assert_eq!(data.len(), shape.iter().product::<i32>() as usize);
155
156        unsafe { Self::from_raw_data(data.as_ptr() as *const c_void, shape, T::DTYPE) }
157    }
158
159    /// New array from a slice of f64.
160    ///
161    /// A separate method is provided for f64 because f64 is not supported on GPU
162    /// and rust defaults to f64 for floating point literals
163    pub fn from_slice_f64(data: &[f64], shape: &[i32]) -> Self {
164        // Validate data size and shape
165        assert_eq!(data.len(), shape.iter().product::<i32>() as usize);
166
167        unsafe { Self::from_raw_data(data.as_ptr() as *const c_void, shape, Dtype::Float64) }
168    }
169
170    /// Create a new array from raw data buffer.
171    ///
172    /// This is a convenience wrapper around [`mlx_sy::mlx_array_new_data`].
173    ///
174    /// # Safety
175    ///
176    /// This is unsafe because the caller must ensure that the data buffer is valid and that the
177    /// shape is correct.
178    #[inline]
179    pub unsafe fn from_raw_data(data: *const c_void, shape: &[i32], dtype: Dtype) -> Self {
180        let dim = if shape.len() > i32::MAX as usize {
181            panic!("Shape is too large")
182        } else {
183            shape.len() as i32
184        };
185
186        let c_array = mlx_sys::mlx_array_new_data(data, shape.as_ptr(), dim, dtype.into());
187        Array { c_array }
188    }
189
190    /// New array from an iterator.
191    ///
192    /// Please note that floating point literals are treated as f32 instead of
193    /// f64. Use [`Array::from_iter_f64`] for f64.
194    ///
195    /// This is a convenience method that is equivalent to
196    ///
197    /// ```rust, ignore
198    /// let data: Vec<T> = iter.collect();
199    /// Array::from_slice(&data, shape)
200    /// ```
201    ///
202    /// # Example
203    ///
204    /// ```rust
205    /// use mlx_rs::Array;
206    ///
207    /// let data = vec![1i32, 2, 3, 4, 5];
208    /// let mut array = Array::from_iter(data.clone(), &[5]);
209    /// assert_eq!(array.as_slice::<i32>(), &data[..]);
210    /// ```
211    pub fn from_iter<I: IntoIterator<Item = T>, T: FromSliceElement>(
212        iter: I,
213        shape: &[i32],
214    ) -> Self {
215        let data: Vec<T> = iter.into_iter().collect();
216        Self::from_slice(&data, shape)
217    }
218
219    /// New array from an iterator of f64.
220    ///
221    /// A separate method is provided for f64 because f64 is not supported on GPU
222    /// and rust defaults to f64 for floating point literals
223    pub fn from_iter_f64<I: IntoIterator<Item = f64>>(iter: I, shape: &[i32]) -> Self {
224        let data: Vec<f64> = iter.into_iter().collect();
225        Self::from_slice_f64(&data, shape)
226    }
227
228    /// The size of the array’s datatype in bytes.
229    pub fn item_size(&self) -> usize {
230        unsafe { mlx_sys::mlx_array_itemsize(self.as_ptr()) }
231    }
232
233    /// Number of elements in the array.
234    pub fn size(&self) -> usize {
235        unsafe { mlx_sys::mlx_array_size(self.as_ptr()) }
236    }
237
238    /// The strides of the array.
239    pub fn strides(&self) -> &[usize] {
240        let ndim = self.ndim();
241        if ndim == 0 {
242            // The data pointer may be null which would panic even if len is 0
243            return &[];
244        }
245
246        unsafe {
247            let data = mlx_sys::mlx_array_strides(self.as_ptr());
248            std::slice::from_raw_parts(data, ndim)
249        }
250    }
251
252    /// The number of bytes in the array.
253    pub fn nbytes(&self) -> usize {
254        unsafe { mlx_sys::mlx_array_nbytes(self.as_ptr()) }
255    }
256
257    /// The array’s dimension.
258    pub fn ndim(&self) -> usize {
259        unsafe { mlx_sys::mlx_array_ndim(self.as_ptr()) }
260    }
261
262    /// The shape of the array.
263    ///
264    /// Returns: a pointer to the sizes of each dimension.
265    pub fn shape(&self) -> &[i32] {
266        let ndim = self.ndim();
267        if ndim == 0 {
268            // The data pointer may be null which would panic even if len is 0
269            return &[];
270        }
271
272        unsafe {
273            let data = mlx_sys::mlx_array_shape(self.as_ptr());
274            std::slice::from_raw_parts(data, ndim)
275        }
276    }
277
278    /// The shape of the array in a particular dimension.
279    ///
280    /// # Panic
281    ///
282    /// - Panics if the array is scalar.
283    /// - Panics if `dim` is negative and `dim + ndim` overflows
284    /// - Panics if the dimension is out of bounds.
285    pub fn dim(&self, dim: i32) -> i32 {
286        let dim = if dim.is_negative() {
287            (self.ndim() as i32).checked_add(dim).unwrap()
288        } else {
289            dim
290        };
291
292        // This will panic on a scalar array
293        unsafe { mlx_sys::mlx_array_dim(self.as_ptr(), dim) }
294    }
295
296    /// The array element type.
297    pub fn dtype(&self) -> Dtype {
298        let dtype = unsafe { mlx_sys::mlx_array_dtype(self.as_ptr()) };
299        Dtype::try_from(dtype).unwrap()
300    }
301
302    /// Evaluate the array.
303    pub fn eval(&self) -> crate::error::Result<()> {
304        <() as Guarded>::try_from_op(|_| unsafe { mlx_sys::mlx_array_eval(self.as_ptr()) })
305    }
306
307    /// Access the value of a scalar array without dtype conversion.
308    ///
309    /// This evaluates the array and panics if evaluation fails, the array is not scalar, or `T`
310    /// does not exactly match the array dtype.
311    pub fn item_exact<T: ArrayElement>(&self) -> T {
312        self.try_item_exact().unwrap()
313    }
314
315    /// Access the value of a scalar array without dtype conversion.
316    ///
317    /// This evaluates the array and returns an error if evaluation fails, the array is not scalar,
318    /// or `T` does not exactly match the array dtype.
319    pub fn try_item_exact<T: ArrayElement>(&self) -> Result<T, ConversionError> {
320        if self.size() != 1 {
321            return Err(ConversionError::NotScalar {
322                actual: self.size(),
323            });
324        }
325        if self.dtype() != T::DTYPE {
326            return Err(ConversionError::DtypeMismatch {
327                expected: T::DTYPE,
328                actual: self.dtype(),
329            });
330        }
331        self.eval()?;
332        Ok(T::array_item(self)?)
333    }
334
335    /// Access the value of a scalar array, converting it to `T` when necessary.
336    ///
337    /// This evaluates the array and panics if evaluation or conversion fails or the array is not
338    /// scalar.
339    pub fn item_cast<T: ArrayElement>(&self) -> T {
340        self.try_item_cast().unwrap()
341    }
342
343    /// Access the value of a scalar array, converting it to `T` when necessary.
344    ///
345    /// This evaluates the array and returns an error if evaluation or conversion fails or the
346    /// array is not scalar.
347    pub fn try_item_cast<T: ArrayElement>(&self) -> Result<T, ConversionError> {
348        if self.size() != 1 {
349            return Err(ConversionError::NotScalar {
350                actual: self.size(),
351            });
352        }
353        self.eval()?;
354
355        if self.dtype() != T::DTYPE {
356            return self.as_type::<T>()?.try_item_exact();
357        }
358
359        Ok(T::array_item(self)?)
360    }
361
362    /// Compatibility alias for [`Array::item_cast`].
363    #[deprecated(since = "0.26.0", note = "use `item_cast` or `item_exact`")]
364    pub fn item<T: ArrayElement>(&self) -> T {
365        self.item_cast()
366    }
367
368    /// Compatibility alias for [`Array::try_item_cast`].
369    #[deprecated(since = "0.26.0", note = "use `try_item_cast` or `try_item_exact`")]
370    pub fn try_item<T: ArrayElement>(&self) -> crate::error::Result<T> {
371        self.try_item_cast().map_err(|error| match error {
372            ConversionError::Exception(error) => error,
373            error => crate::error::Exception::custom(error.to_string()),
374        })
375    }
376
377    /// Copy contiguous row-major array values without dtype conversion.
378    ///
379    /// This evaluates the array and allocates a `Vec`. It returns an error if `T` does not exactly
380    /// match the array dtype or if the array is not contiguous row-major. Call
381    /// [`Array::contiguous`] first to materialize a row-major array.
382    pub fn to_vec_exact<T: ArrayElement + Clone>(&self) -> Result<Vec<T>, ConversionError> {
383        if self.dtype() != T::DTYPE {
384            return Err(ConversionError::DtypeMismatch {
385                expected: T::DTYPE,
386                actual: self.dtype(),
387            });
388        }
389        Ok(self.try_as_slice::<T>()?.to_vec())
390    }
391
392    /// Copy contiguous row-major array values, converting them to `T` when necessary.
393    ///
394    /// This evaluates the array, may allocate a converted MLX array, and allocates a `Vec`. It
395    /// returns an error if evaluation or conversion fails or if the converted array is not
396    /// contiguous row-major. Call [`Array::contiguous`] first to materialize a row-major array.
397    pub fn to_vec_cast<T: ArrayElement + Clone>(&self) -> Result<Vec<T>, ConversionError> {
398        if self.dtype() == T::DTYPE {
399            return self.to_vec_exact();
400        }
401        let converted = self.as_type::<T>()?;
402        Ok(converted.try_as_slice::<T>()?.to_vec())
403    }
404
405    /// Returns a slice of the array data without validating the dtype.
406    ///
407    /// # Safety
408    ///
409    /// This is unsafe because the underlying data ptr is not checked for null or if the desired
410    /// dtype matches the actual dtype of the array.
411    ///
412    /// # Example
413    ///
414    /// ```rust
415    /// use mlx_rs::Array;
416    ///
417    /// let data = [1i32, 2, 3, 4, 5];
418    /// let mut array = Array::from_slice(&data[..], &[5]);
419    ///
420    /// unsafe {
421    ///    let slice = array.as_slice_unchecked::<i32>();
422    ///    assert_eq!(slice, &[1, 2, 3, 4, 5]);
423    /// }
424    /// ```
425    pub unsafe fn as_slice_unchecked<T: ArrayElement>(&self) -> &[T] {
426        self.eval().unwrap();
427
428        unsafe {
429            let data = T::array_data(self);
430            let size = self.size();
431            std::slice::from_raw_parts(data, size)
432        }
433    }
434
435    /// Returns a slice of contiguous row-major array data.
436    ///
437    /// Returns an error if the dtype does not match or the array is a non-contiguous view. Call
438    /// [`Array::contiguous`] first to materialize a row-major array.
439    ///
440    /// # Example
441    ///
442    /// ```rust
443    /// use mlx_rs::Array;
444    ///
445    /// let data = [1i32, 2, 3, 4, 5];
446    /// let mut array = Array::from_slice(&data[..], &[5]);
447    ///
448    /// let slice = array.try_as_slice::<i32>();
449    /// assert_eq!(slice, Ok(&data[..]));
450    /// ```
451    pub fn try_as_slice<T: ArrayElement>(&self) -> Result<&[T], AsSliceError> {
452        if self.dtype() != T::DTYPE {
453            return Err(AsSliceError::DtypeMismatch {
454                expecting: T::DTYPE,
455                found: self.dtype(),
456            });
457        }
458
459        self.eval()?;
460
461        let row_contiguous = bool::try_from_op(|res| unsafe {
462            mlx_sys::_mlx_array_is_row_contiguous(res, self.as_ptr())
463        })?;
464        if !row_contiguous {
465            return Err(AsSliceError::NotContiguous);
466        }
467
468        unsafe {
469            let size = self.size();
470            let data = T::array_data(self);
471            if data.is_null() || size == 0 {
472                return Err(AsSliceError::Null);
473            }
474
475            Ok(std::slice::from_raw_parts(data, size))
476        }
477    }
478
479    /// Returns a slice of contiguous row-major array data.
480    ///
481    /// # Panics
482    ///
483    /// Panics if evaluation fails, the desired dtype does not match the actual dtype, or the array
484    /// is not contiguous row-major. Call [`Array::contiguous`] first for non-contiguous views.
485    ///
486    /// # Example
487    ///
488    /// ```rust
489    /// use mlx_rs::Array;
490    ///
491    /// let data = [1i32, 2, 3, 4, 5];
492    /// let mut array = Array::from_slice(&data[..], &[5]);
493    ///
494    /// let slice = array.as_slice::<i32>();
495    /// assert_eq!(slice, &data[..]);
496    /// ```
497    pub fn as_slice<T: ArrayElement>(&self) -> &[T] {
498        self.try_as_slice().unwrap()
499    }
500
501    /// Clone the array by copying the data.
502    ///
503    /// This is named `deep_clone` to avoid confusion with the `Clone` trait.
504    pub fn deep_clone(&self) -> Self {
505        unsafe {
506            let dtype = self.dtype();
507            let shape = self.shape();
508            let data = match dtype {
509                Dtype::Bool => mlx_sys::mlx_array_data_bool(self.as_ptr()) as *const c_void,
510                Dtype::Uint8 => mlx_sys::mlx_array_data_uint8(self.as_ptr()) as *const c_void,
511                Dtype::Uint16 => mlx_sys::mlx_array_data_uint16(self.as_ptr()) as *const c_void,
512                Dtype::Uint32 => mlx_sys::mlx_array_data_uint32(self.as_ptr()) as *const c_void,
513                Dtype::Uint64 => mlx_sys::mlx_array_data_uint64(self.as_ptr()) as *const c_void,
514                Dtype::Int8 => mlx_sys::mlx_array_data_int8(self.as_ptr()) as *const c_void,
515                Dtype::Int16 => mlx_sys::mlx_array_data_int16(self.as_ptr()) as *const c_void,
516                Dtype::Int32 => mlx_sys::mlx_array_data_int32(self.as_ptr()) as *const c_void,
517                Dtype::Int64 => mlx_sys::mlx_array_data_int64(self.as_ptr()) as *const c_void,
518                Dtype::Float16 => mlx_sys::mlx_array_data_float16(self.as_ptr()) as *const c_void,
519                Dtype::Float32 => mlx_sys::mlx_array_data_float32(self.as_ptr()) as *const c_void,
520                Dtype::Float64 => mlx_sys::mlx_array_data_float64(self.as_ptr()) as *const c_void,
521                Dtype::Bfloat16 => mlx_sys::mlx_array_data_bfloat16(self.as_ptr()) as *const c_void,
522                Dtype::Complex64 => {
523                    mlx_sys::mlx_array_data_complex64(self.as_ptr()) as *const c_void
524                }
525            };
526
527            let new_c_array =
528                mlx_sys::mlx_array_new_data(data, shape.as_ptr(), shape.len() as i32, dtype.into());
529
530            Array::from_ptr(new_c_array)
531        }
532    }
533}
534
535impl Clone for Array {
536    fn clone(&self) -> Self {
537        Array::try_from_op(|res| unsafe { mlx_sys::mlx_array_set(res, self.as_ptr()) })
538            // Exception may be thrown when calling `new` in cpp.
539            .expect("Failed to clone array")
540    }
541}
542
543impl Sum for Array {
544    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
545        iter.fold(Array::from_int(0), |acc, x| acc.add(&x).unwrap())
546    }
547}
548
549/// Stop gradients from being computed.
550///
551/// The operation is the identity but it prevents gradients from flowing
552/// through the array.
553#[default_device]
554pub fn stop_gradient_device(
555    a: impl AsRef<Array>,
556    stream: impl AsRef<Stream>,
557) -> crate::error::Result<Array> {
558    Array::try_from_op(|res| unsafe {
559        mlx_sys::mlx_stop_gradient(res, a.as_ref().as_ptr(), stream.as_ref().as_ptr())
560    })
561}
562
563impl From<bool> for Array {
564    fn from(value: bool) -> Self {
565        Array::from_bool(value)
566    }
567}
568
569impl From<i32> for Array {
570    fn from(value: i32) -> Self {
571        Array::from_int(value)
572    }
573}
574
575impl From<f32> for Array {
576    fn from(value: f32) -> Self {
577        Array::from_f32(value)
578    }
579}
580
581impl From<complex64> for Array {
582    fn from(value: complex64) -> Self {
583        Array::from_complex(value)
584    }
585}
586
587impl<T> From<T> for Array
588where
589    Array: FromNested<T>,
590{
591    fn from(value: T) -> Self {
592        Array::from_nested(value)
593    }
594}
595
596impl AsRef<Array> for Array {
597    fn as_ref(&self) -> &Array {
598        self
599    }
600}
601
602/// A helper trait to construct `Array` from scalar values.
603///
604/// This trait is intended to be used with the macro [`array!`] but can be used directly if needed.
605pub trait FromScalar<T>
606where
607    T: ArrayElement,
608{
609    /// Create an array from a scalar value.
610    fn from_scalar(val: T) -> Array;
611}
612
613impl FromScalar<bool> for Array {
614    fn from_scalar(val: bool) -> Array {
615        Array::from_bool(val)
616    }
617}
618
619impl FromScalar<i32> for Array {
620    fn from_scalar(val: i32) -> Array {
621        Array::from_int(val)
622    }
623}
624
625impl FromScalar<f32> for Array {
626    fn from_scalar(val: f32) -> Array {
627        Array::from_f32(val)
628    }
629}
630
631impl FromScalar<complex64> for Array {
632    fn from_scalar(val: complex64) -> Array {
633        Array::from_complex(val)
634    }
635}
636
637/// A helper trait to construct `Array` from nested arrays or slices.
638///
639/// Given that this is not intended for use other than the macro [`array!`], this trait is added
640/// instead of directly implementing `From` for `Array` to avoid conflicts with other `From`
641/// implementations.
642///
643/// Beware that this is subject to change in the future should we find a better way to implement
644/// the macro without creating conflicts.
645pub trait FromNested<T> {
646    /// Create an array from nested arrays or slices.
647    fn from_nested(data: T) -> Array;
648}
649
650impl<T: FromSliceElement> FromNested<&[T]> for Array {
651    fn from_nested(data: &[T]) -> Self {
652        Array::from_slice(data, &[data.len() as i32])
653    }
654}
655
656impl<T: FromSliceElement, const N: usize> FromNested<[T; N]> for Array {
657    fn from_nested(data: [T; N]) -> Self {
658        Array::from_slice(&data, &[N as i32])
659    }
660}
661
662impl<T: FromSliceElement, const N: usize> FromNested<&[T; N]> for Array {
663    fn from_nested(data: &[T; N]) -> Self {
664        Array::from_slice(data, &[N as i32])
665    }
666}
667
668impl<T: FromSliceElement + Copy> FromNested<&[&[T]]> for Array {
669    fn from_nested(data: &[&[T]]) -> Self {
670        // check that all rows have the same length
671        let row_len = data[0].len();
672        assert!(
673            data.iter().all(|row| row.len() == row_len),
674            "Rows must have the same length"
675        );
676
677        let shape = [data.len() as i32, row_len as i32];
678        let data = data
679            .iter()
680            .flat_map(|x| x.iter())
681            .copied()
682            .collect::<Vec<T>>();
683        Array::from_slice(&data, &shape)
684    }
685}
686
687impl<T: FromSliceElement + Copy, const N: usize> FromNested<[&[T]; N]> for Array {
688    fn from_nested(data: [&[T]; N]) -> Self {
689        // check that all rows have the same length
690        let row_len = data[0].len();
691        assert!(
692            data.iter().all(|row| row.len() == row_len),
693            "Rows must have the same length"
694        );
695
696        let shape = [N as i32, row_len as i32];
697        let data = data
698            .iter()
699            .flat_map(|x| x.iter())
700            .copied()
701            .collect::<Vec<T>>();
702        Array::from_slice(&data, &shape)
703    }
704}
705
706impl<T: FromSliceElement + Copy, const N: usize> FromNested<&[[T; N]]> for Array {
707    fn from_nested(data: &[[T; N]]) -> Self {
708        let shape = [data.len() as i32, N as i32];
709        let data = data
710            .iter()
711            .flat_map(|x| x.iter().copied())
712            .collect::<Vec<T>>();
713        Array::from_slice(&data, &shape)
714    }
715}
716
717impl<T: FromSliceElement + Copy, const N: usize> FromNested<&[&[T; N]]> for Array {
718    fn from_nested(data: &[&[T; N]]) -> Self {
719        let shape = [data.len() as i32, N as i32];
720        let data = data
721            .iter()
722            .flat_map(|x| x.iter().copied())
723            .collect::<Vec<T>>();
724        Array::from_slice(&data, &shape)
725    }
726}
727
728impl<T: FromSliceElement + Copy, const N: usize, const M: usize> FromNested<[[T; N]; M]> for Array {
729    fn from_nested(data: [[T; N]; M]) -> Self {
730        let shape = [M as i32, N as i32];
731        let data = data
732            .iter()
733            .flat_map(|x| x.iter().copied())
734            .collect::<Vec<T>>();
735        Array::from_slice(&data, &shape)
736    }
737}
738
739impl<T: FromSliceElement + Copy, const N: usize, const M: usize> FromNested<&[[T; N]; M]>
740    for Array
741{
742    fn from_nested(data: &[[T; N]; M]) -> Self {
743        let shape = [M as i32, N as i32];
744        let data = data
745            .iter()
746            .flat_map(|x| x.iter().copied())
747            .collect::<Vec<T>>();
748        Array::from_slice(&data, &shape)
749    }
750}
751
752impl<T: FromSliceElement + Copy, const N: usize, const M: usize> FromNested<&[&[T; N]; M]>
753    for Array
754{
755    fn from_nested(data: &[&[T; N]; M]) -> Self {
756        let shape = [M as i32, N as i32];
757        let data = data
758            .iter()
759            .flat_map(|x| x.iter().copied())
760            .collect::<Vec<T>>();
761        Array::from_slice(&data, &shape)
762    }
763}
764
765impl<T: FromSliceElement + Copy> FromNested<&[&[&[T]]]> for Array {
766    fn from_nested(data: &[&[&[T]]]) -> Self {
767        // check that 2nd dimension has the same length
768        let len_2d = data[0].len();
769        assert!(
770            data.iter().all(|x| x.len() == len_2d),
771            "2nd dimension must have the same length"
772        );
773
774        // check that 3rd dimension has the same length
775        let len_3d = data[0][0].len();
776        assert!(
777            data.iter().all(|x| x.iter().all(|y| y.len() == len_3d)),
778            "3rd dimension must have the same length"
779        );
780
781        let shape = [data.len() as i32, len_2d as i32, len_3d as i32];
782        let data = data
783            .iter()
784            .flat_map(|x| x.iter().flat_map(|y| y.iter().copied()))
785            .collect::<Vec<T>>();
786        Array::from_slice(&data, &shape)
787    }
788}
789
790impl<T: FromSliceElement + Copy, const N: usize> FromNested<[&[&[T]]; N]> for Array {
791    fn from_nested(data: [&[&[T]]; N]) -> Self {
792        // check that 2nd dimension has the same length
793        let len_2d = data[0].len();
794        assert!(
795            data.iter().all(|x| x.len() == len_2d),
796            "2nd dimension must have the same length"
797        );
798
799        // check that 3rd dimension has the same length
800        let len_3d = data[0][0].len();
801        assert!(
802            data.iter().all(|x| x.iter().all(|y| y.len() == len_3d)),
803            "3rd dimension must have the same length"
804        );
805
806        let shape = [N as i32, len_2d as i32, len_3d as i32];
807        let data = data
808            .iter()
809            .flat_map(|x| x.iter().flat_map(|y| y.iter().copied()))
810            .collect::<Vec<T>>();
811        Array::from_slice(&data, &shape)
812    }
813}
814
815impl<T: FromSliceElement + Copy, const N: usize> FromNested<&[[&[T]; N]]> for Array {
816    fn from_nested(data: &[[&[T]; N]]) -> Self {
817        // check that 3rd dimension has the same length
818        let len_3d = data[0][0].len();
819        assert!(
820            data.iter().all(|x| x.iter().all(|y| y.len() == len_3d)),
821            "3rd dimension must have the same length"
822        );
823
824        let shape = [data.len() as i32, N as i32, len_3d as i32];
825        let data = data
826            .iter()
827            .flat_map(|x| x.iter().flat_map(|y| y.iter().copied()))
828            .collect::<Vec<T>>();
829        Array::from_slice(&data, &shape)
830    }
831}
832
833impl<T: FromSliceElement + Copy, const N: usize> FromNested<&[&[[T; N]]]> for Array {
834    fn from_nested(data: &[&[[T; N]]]) -> Self {
835        // check that 2nd dimension has the same length
836        let len_2d = data[0].len();
837        assert!(
838            data.iter().all(|x| x.len() == len_2d),
839            "2nd dimension must have the same length"
840        );
841
842        let shape = [data.len() as i32, len_2d as i32, N as i32];
843        let data = data
844            .iter()
845            .flat_map(|x| x.iter().flat_map(|y| y.iter().copied()))
846            .collect::<Vec<T>>();
847        Array::from_slice(&data, &shape)
848    }
849}
850
851impl<T: FromSliceElement + Copy, const N: usize, const M: usize> FromNested<[[&[T]; N]; M]>
852    for Array
853{
854    fn from_nested(data: [[&[T]; N]; M]) -> Self {
855        // check that 3rd dimension has the same length
856        let len_3d = data[0][0].len();
857        assert!(
858            data.iter().all(|x| x.iter().all(|y| y.len() == len_3d)),
859            "3rd dimension must have the same length"
860        );
861
862        let shape = [M as i32, N as i32, len_3d as i32];
863        let data = data
864            .iter()
865            .flat_map(|x| x.iter().flat_map(|y| y.iter().copied()))
866            .collect::<Vec<T>>();
867        Array::from_slice(&data, &shape)
868    }
869}
870
871impl<T: FromSliceElement + Copy, const N: usize, const M: usize> FromNested<&[[&[T]; N]; M]>
872    for Array
873{
874    fn from_nested(data: &[[&[T]; N]; M]) -> Self {
875        // check that 3rd dimension has the same length
876        let len_3d = data[0][0].len();
877        assert!(
878            data.iter().all(|x| x.iter().all(|y| y.len() == len_3d)),
879            "3rd dimension must have the same length"
880        );
881
882        let shape = [M as i32, N as i32, len_3d as i32];
883        let data = data
884            .iter()
885            .flat_map(|x| x.iter().flat_map(|y| y.iter().copied()))
886            .collect::<Vec<T>>();
887        Array::from_slice(&data, &shape)
888    }
889}
890
891impl<T: FromSliceElement + Copy, const N: usize, const M: usize> FromNested<&[&[[T; N]]; M]>
892    for Array
893{
894    fn from_nested(data: &[&[[T; N]]; M]) -> Self {
895        // check that 2nd dimension has the same length
896        let len_2d = data[0].len();
897        assert!(
898            data.iter().all(|x| x.len() == len_2d),
899            "2nd dimension must have the same length"
900        );
901
902        let shape = [M as i32, len_2d as i32, N as i32];
903        let data = data
904            .iter()
905            .flat_map(|x| x.iter().flat_map(|y| y.iter().copied()))
906            .collect::<Vec<T>>();
907        Array::from_slice(&data, &shape)
908    }
909}
910
911impl<T: FromSliceElement + Copy, const N: usize, const M: usize, const O: usize>
912    FromNested<[[[T; N]; M]; O]> for Array
913{
914    fn from_nested(data: [[[T; N]; M]; O]) -> Self {
915        let shape = [O as i32, M as i32, N as i32];
916        let data = data
917            .iter()
918            .flat_map(|x| x.iter().flat_map(|y| y.iter().copied()))
919            .collect::<Vec<T>>();
920        Array::from_slice(&data, &shape)
921    }
922}
923
924impl<T: FromSliceElement + Copy, const N: usize, const M: usize, const O: usize>
925    FromNested<&[[[T; N]; M]; O]> for Array
926{
927    fn from_nested(data: &[[[T; N]; M]; O]) -> Self {
928        let shape = [O as i32, M as i32, N as i32];
929        let data = data
930            .iter()
931            .flat_map(|x| x.iter().flat_map(|y| y.iter().copied()))
932            .collect::<Vec<T>>();
933        Array::from_slice(&data, &shape)
934    }
935}
936
937impl<T: FromSliceElement + Copy, const N: usize, const M: usize, const O: usize>
938    FromNested<&[&[[T; N]; M]; O]> for Array
939{
940    fn from_nested(data: &[&[[T; N]; M]; O]) -> Self {
941        let shape = [O as i32, M as i32, N as i32];
942        let data = data
943            .iter()
944            .flat_map(|x| x.iter().flat_map(|y| y.iter().copied()))
945            .collect::<Vec<T>>();
946        Array::from_slice(&data, &shape)
947    }
948}
949
950impl<T: FromSliceElement + Copy, const N: usize, const M: usize, const O: usize>
951    FromNested<&[[&[T; N]; M]; O]> for Array
952{
953    fn from_nested(data: &[[&[T; N]; M]; O]) -> Self {
954        let shape = [O as i32, M as i32, N as i32];
955        let data = data
956            .iter()
957            .flat_map(|x| x.iter().flat_map(|y| y.iter().copied()))
958            .collect::<Vec<T>>();
959        Array::from_slice(&data, &shape)
960    }
961}
962
963impl<T: FromSliceElement + Copy, const N: usize, const M: usize, const O: usize>
964    FromNested<&[&[&[T; N]; M]; O]> for Array
965{
966    fn from_nested(data: &[&[&[T; N]; M]; O]) -> Self {
967        let shape = [O as i32, M as i32, N as i32];
968        let data = data
969            .iter()
970            .flat_map(|x| x.iter().flat_map(|y| y.iter().copied()))
971            .collect::<Vec<T>>();
972        Array::from_slice(&data, &shape)
973    }
974}
975
976#[cfg(test)]
977mod tests {
978    use super::*;
979    use crate::{array, ops::broadcast_to};
980
981    #[test]
982    fn broadcast_view_cannot_be_borrowed_as_slice() {
983        let broadcast = broadcast_to(&array!([1, 2]), &[3, 2]).unwrap();
984
985        assert_eq!(
986            broadcast.try_as_slice::<i32>(),
987            Err(AsSliceError::NotContiguous)
988        );
989    }
990
991    #[test]
992    fn new_scalar_array_from_bool() {
993        let array = Array::from_bool(true);
994        assert!(array.item_exact::<bool>());
995        assert_eq!(array.item_size(), 1);
996        assert_eq!(array.size(), 1);
997        assert!(array.strides().is_empty());
998        assert_eq!(array.nbytes(), 1);
999        assert_eq!(array.ndim(), 0);
1000        assert!(array.shape().is_empty());
1001        assert_eq!(array.dtype(), Dtype::Bool);
1002    }
1003
1004    #[test]
1005    fn new_scalar_array_from_int() {
1006        let array = Array::from_int(42);
1007        assert_eq!(array.item_exact::<i32>(), 42);
1008        assert_eq!(array.item_size(), 4);
1009        assert_eq!(array.size(), 1);
1010        assert!(array.strides().is_empty());
1011        assert_eq!(array.nbytes(), 4);
1012        assert_eq!(array.ndim(), 0);
1013        assert!(array.shape().is_empty());
1014        assert_eq!(array.dtype(), Dtype::Int32);
1015    }
1016
1017    #[test]
1018    fn new_scalar_array_from_f32() {
1019        let array = Array::from_f32(3.14);
1020        assert_eq!(array.item_exact::<f32>(), 3.14);
1021        assert_eq!(array.item_size(), 4);
1022        assert_eq!(array.size(), 1);
1023        assert!(array.strides().is_empty());
1024        assert_eq!(array.nbytes(), 4);
1025        assert_eq!(array.ndim(), 0);
1026        assert!(array.shape().is_empty());
1027        assert_eq!(array.dtype(), Dtype::Float32);
1028    }
1029
1030    #[test]
1031    fn new_scalar_array_from_f64() {
1032        let array = Array::from_f64(3.14).as_dtype(Dtype::Float64).unwrap();
1033        float_eq::assert_float_eq!(array.item_exact::<f64>(), 3.14, abs <= 1e-5);
1034        assert_eq!(array.item_size(), 8);
1035        assert_eq!(array.size(), 1);
1036        assert!(array.strides().is_empty());
1037        assert_eq!(array.nbytes(), 8);
1038        assert_eq!(array.ndim(), 0);
1039        assert!(array.shape().is_empty());
1040        assert_eq!(array.dtype(), Dtype::Float64);
1041    }
1042
1043    #[test]
1044    fn new_array_from_slice_f64() {
1045        let array = Array::from_slice_f64(&[1.0, 2.0, 3.0], &[3]);
1046        assert_eq!(array.item_size(), 8);
1047        assert_eq!(array.size(), 3);
1048        assert_eq!(array.strides(), &[1]);
1049        assert_eq!(array.nbytes(), 24);
1050        assert_eq!(array.ndim(), 1);
1051        assert_eq!(array.dim(0), 3);
1052        assert_eq!(array.shape(), &[3]);
1053        assert_eq!(array.dtype(), Dtype::Float64);
1054    }
1055
1056    #[test]
1057    fn new_scalar_array_from_complex() {
1058        let val = complex64::new(1.0, 2.0);
1059        let array = Array::from_complex(val);
1060        assert_eq!(array.item_exact::<complex64>(), val);
1061        assert_eq!(array.item_size(), 8);
1062        assert_eq!(array.size(), 1);
1063        assert!(array.strides().is_empty());
1064        assert_eq!(array.nbytes(), 8);
1065        assert_eq!(array.ndim(), 0);
1066        assert!(array.shape().is_empty());
1067        assert_eq!(array.dtype(), Dtype::Complex64);
1068    }
1069
1070    #[test]
1071    fn new_array_from_single_element_slice() {
1072        let data = [1i32];
1073        let array = Array::from_slice(&data, &[1]);
1074        assert_eq!(array.as_slice::<i32>(), &data[..]);
1075        assert_eq!(array.item_exact::<i32>(), 1);
1076        assert_eq!(array.item_size(), 4);
1077        assert_eq!(array.size(), 1);
1078        assert_eq!(array.strides(), &[1]);
1079        assert_eq!(array.nbytes(), 4);
1080        assert_eq!(array.ndim(), 1);
1081        assert_eq!(array.dim(0), 1);
1082        assert_eq!(array.shape(), &[1]);
1083        assert_eq!(array.dtype(), Dtype::Int32);
1084    }
1085
1086    #[test]
1087    fn new_array_from_multi_element_slice() {
1088        let data = [1i32, 2, 3, 4, 5];
1089        let array = Array::from_slice(&data, &[5]);
1090        assert_eq!(array.as_slice::<i32>(), &data[..]);
1091        assert_eq!(array.item_size(), 4);
1092        assert_eq!(array.size(), 5);
1093        assert_eq!(array.strides(), &[1]);
1094        assert_eq!(array.nbytes(), 20);
1095        assert_eq!(array.ndim(), 1);
1096        assert_eq!(array.dim(0), 5);
1097        assert_eq!(array.shape(), &[5]);
1098        assert_eq!(array.dtype(), Dtype::Int32);
1099    }
1100
1101    #[test]
1102    fn new_2d_array_from_slice() {
1103        let data = [1i32, 2, 3, 4, 5, 6];
1104        let array = Array::from_slice(&data, &[2, 3]);
1105        assert_eq!(array.as_slice::<i32>(), &data[..]);
1106        assert_eq!(array.item_size(), 4);
1107        assert_eq!(array.size(), 6);
1108        assert_eq!(array.strides(), &[3, 1]);
1109        assert_eq!(array.nbytes(), 24);
1110        assert_eq!(array.ndim(), 2);
1111        assert_eq!(array.dim(0), 2);
1112        assert_eq!(array.dim(1), 3);
1113        assert_eq!(array.dim(-1), 3); // negative index
1114        assert_eq!(array.dim(-2), 2); // negative index
1115        assert_eq!(array.shape(), &[2, 3]);
1116        assert_eq!(array.dtype(), Dtype::Int32);
1117    }
1118
1119    #[test]
1120    fn deep_cloned_array_has_different_ptr() {
1121        let data = [1i32, 2, 3, 4, 5];
1122        let orig = Array::from_slice(&data, &[5]);
1123        let clone = orig.deep_clone();
1124
1125        // Data should be the same
1126        assert_eq!(orig.as_slice::<i32>(), clone.as_slice::<i32>());
1127
1128        // Addr of `mlx_array` should be different
1129        assert_ne!(orig.as_ptr().ctx, clone.as_ptr().ctx);
1130
1131        // Addr of data should be different
1132        assert_ne!(
1133            orig.as_slice::<i32>().as_ptr(),
1134            clone.as_slice::<i32>().as_ptr()
1135        );
1136    }
1137
1138    #[test]
1139    fn test_array_eq() {
1140        let data = [1i32, 2, 3, 4, 5];
1141        let array1 = Array::from_slice(&data, &[5]);
1142        let array2 = Array::from_slice(&data, &[5]);
1143        let array3 = Array::from_slice(&[1i32, 2, 3, 4, 6], &[5]);
1144
1145        assert!(array1.eq_exact(&array2).unwrap());
1146        assert!(!array1.eq_exact(&array3).unwrap());
1147    }
1148
1149    #[test]
1150    fn test_array_item_non_scalar() {
1151        let data = [1i32, 2, 3, 4, 5];
1152        let array = Array::from_slice(&data, &[5]);
1153        assert!(array.try_item_exact::<i32>().is_err());
1154    }
1155
1156    #[test]
1157    fn test_item_type_conversion() {
1158        let array = Array::from_f32(1.0);
1159        assert_eq!(array.item_cast::<i32>(), 1);
1160        assert_eq!(array.item_cast::<complex64>(), complex64::new(1.0, 0.0));
1161        assert_eq!(array.item_cast::<u8>(), 1);
1162
1163        assert_eq!(array.as_slice::<f32>(), &[1.0]);
1164    }
1165
1166    #[test]
1167    fn exact_observers_reject_dtype_conversion() {
1168        crate::with_device(crate::Device::cpu(), || {
1169            let array = Array::from_slice(&[1_i32, 2, 3], &[3]);
1170            let scalar = Array::from_int(1);
1171
1172            let vector_error = array.to_vec_exact::<f32>().unwrap_err();
1173            assert!(
1174                matches!(
1175                    vector_error,
1176                    crate::error::ConversionError::DtypeMismatch {
1177                        expected: Dtype::Float32,
1178                        actual: Dtype::Int32,
1179                    }
1180                ),
1181                "{vector_error:?}; dtype={:?}",
1182                array.dtype()
1183            );
1184            assert!(matches!(
1185                scalar.try_item_exact::<f32>(),
1186                Err(crate::error::ConversionError::DtypeMismatch {
1187                    expected: Dtype::Float32,
1188                    actual: Dtype::Int32,
1189                })
1190            ));
1191        });
1192    }
1193
1194    #[test]
1195    fn casting_observers_convert_values() {
1196        crate::with_device(crate::Device::cpu(), || {
1197            let vector = Array::from_slice(&[1_i32, 2, 3], &[3]);
1198            let scalar = Array::from_int(7);
1199
1200            assert_eq!(vector.to_vec_cast::<f32>().unwrap(), vec![1.0, 2.0, 3.0]);
1201            assert_eq!(scalar.try_item_cast::<f32>().unwrap(), 7.0);
1202        });
1203    }
1204
1205    #[test]
1206    fn explicit_array_comparisons_distinguish_dtype_and_values() {
1207        crate::with_device(crate::Device::cpu(), || {
1208            let integers = Array::from_slice(&[1_i32, 2, 3], &[3]);
1209            let same_integers = Array::from_slice(&[1_i32, 2, 3], &[3]);
1210            let floats = Array::from_slice(&[1.0_f32, 2.0, 3.0], &[3]);
1211            let nearby = Array::from_slice(&[1.0_f32, 2.0, 3.000_001], &[3]);
1212
1213            assert!(integers.eq_exact(&same_integers).unwrap());
1214            assert!(!integers.eq_exact(&floats).unwrap());
1215            assert!(integers.eq_values(&floats).unwrap());
1216            assert!(floats
1217                .all_close(&nearby, Some(1e-5), Some(1e-8), Some(false))
1218                .unwrap());
1219        });
1220    }
1221}