@@ -277,6 +277,28 @@ impl Array {
277277 unsafe { std:: slice:: from_raw_parts ( ptr, len) } . to_vec ( )
278278 }
279279
280+ /// Converts the elements to the dtype chosen by `T`.
281+ ///
282+ /// Call as `a.astype::<f32>(&stream)`. This is the only way to change an
283+ /// array's dtype — it is otherwise fixed by whichever constructor built the
284+ /// array. Note that binary ops already promote mixed dtypes on their own
285+ /// (`int32 + float32` yields `float32`), so this is for *explicit* control.
286+ ///
287+ /// Conversions follow C++ cast semantics rather than Rust's, and never
288+ /// error: float-to-integer truncates toward zero (`2.7` becomes `2`),
289+ /// `bool` becomes 0 or 1, and numeric-to-`bool` tests `!= 0`. Converting a
290+ /// float that is out of the target integer's range is *unspecified*.
291+ ///
292+ /// Only dtypes with an [`ArrayElement`] impl can be targeted, so MLX's
293+ /// `float16`, `bfloat16`, and `complex64` are out of reach for now.
294+ pub fn astype < T : ArrayElement > ( & self , stream : & Stream ) -> Result < Array > {
295+ error:: install ( ) ;
296+ let mut out = unsafe { sys:: mlx_array_new ( ) } ;
297+ // SAFETY: handle/stream are valid; the result is written into `out`.
298+ let status = unsafe { sys:: mlx_astype ( & mut out, self . handle , T :: DTYPE , stream. as_raw ( ) ) } ;
299+ Self :: from_op ( out, status)
300+ }
301+
280302 /// Returns a row-contiguous copy (or the same array if already dense).
281303 pub fn contiguous ( & self , stream : & Stream ) -> Result < Array > {
282304 error:: install ( ) ;
@@ -367,6 +389,28 @@ impl Array {
367389 self . binary_op ( other, stream, sys:: mlx_minimum)
368390 }
369391
392+ /// Matrix multiplication: `self @ other`.
393+ ///
394+ /// Unlike the elementwise ops, this contracts the last axis of `self`
395+ /// against the second-to-last of `other`: `(n, k) @ (k, m)` gives
396+ /// `(n, m)`. Mismatched inner dimensions return an error rather than
397+ /// panicking.
398+ ///
399+ /// Following NumPy, a 1-dimensional operand is treated as a matrix for the
400+ /// duration of the product and then collapsed again: a leading axis is
401+ /// prepended to a 1-D `self`, a trailing axis appended to a 1-D `other`,
402+ /// and the corresponding axis is removed from the result. So `(3,) @ (3,)`
403+ /// is a 0-dimensional dot product, and `(2, 3) @ (3,)` is `(2,)`.
404+ ///
405+ /// Leading axes beyond the last two are batch dimensions and broadcast:
406+ /// `(2, 3, 4) @ (2, 4, 5)` gives `(2, 3, 5)`.
407+ ///
408+ /// There is deliberately no operator for this. `*` is already elementwise
409+ /// [`multiply`](Self::multiply), and Rust has no `@`.
410+ pub fn matmul ( & self , other : & Array , stream : & Stream ) -> Result < Array > {
411+ self . binary_op ( other, stream, sys:: mlx_matmul)
412+ }
413+
370414 /// Sum of all elements, returning a scalar array.
371415 ///
372416 /// With `keepdims == false` the result is 0-dimensional.
@@ -765,6 +809,135 @@ mod tests {
765809 ) ;
766810 }
767811
812+ #[ test]
813+ fn astype_converts_dtype ( ) {
814+ let s = Stream :: cpu ( ) ;
815+ let ints = Array :: from_slice ( & [ 1i32 , 2 , 3 ] , & [ 3 ] ) ;
816+
817+ // Reading as f32 is only possible after converting.
818+ let floats = ints. astype :: < f32 > ( & s) . unwrap ( ) ;
819+ assert_eq ! ( floats. to_vec:: <f32 >( ) , vec![ 1.0 , 2.0 , 3.0 ] ) ;
820+ // The original is untouched: astype returns a new array.
821+ assert_eq ! ( ints. to_vec:: <i32 >( ) , vec![ 1 , 2 , 3 ] ) ;
822+ // Shape is preserved; only the dtype changes.
823+ assert_eq ! ( floats. shape( ) , ints. shape( ) ) ;
824+ }
825+
826+ #[ test]
827+ fn astype_narrowing_truncates_toward_zero ( ) {
828+ let s = Stream :: cpu ( ) ;
829+ // C++ cast semantics: truncation, not rounding, and no error.
830+ let a = Array :: from_slice ( & [ 2.7f32 , -2.7 , 0.9 ] , & [ 3 ] ) ;
831+ assert_eq ! ( a. astype:: <i32 >( & s) . unwrap( ) . to_vec:: <i32 >( ) , vec![ 2 , -2 , 0 ] ) ;
832+ }
833+
834+ #[ test]
835+ fn astype_bool_round_trip ( ) {
836+ let s = Stream :: cpu ( ) ;
837+ // numeric -> bool is `!= 0`; bool -> numeric is 0/1.
838+ let a = Array :: from_slice ( & [ 0.0f32 , 1.0 , 2.0 , -3.0 ] , & [ 4 ] ) ;
839+ let flags = a. astype :: < bool > ( & s) . unwrap ( ) ;
840+ assert_eq ! ( flags. to_vec:: <bool >( ) , vec![ false , true , true , true ] ) ;
841+ assert_eq ! (
842+ flags. astype:: <i32 >( & s) . unwrap( ) . to_vec:: <i32 >( ) ,
843+ vec![ 0 , 1 , 1 , 1 ]
844+ ) ;
845+ }
846+
847+ #[ test]
848+ fn astype_to_same_dtype_is_a_noop ( ) {
849+ let s = Stream :: cpu ( ) ;
850+ let a = Array :: from_slice ( & [ 1.5f32 , 2.5 ] , & [ 2 ] ) ;
851+ assert_eq ! ( a. astype:: <f32 >( & s) . unwrap( ) . to_vec:: <f32 >( ) , vec![ 1.5 , 2.5 ] ) ;
852+ }
853+
854+ #[ test]
855+ fn matmul_contracts_inner_dimension ( ) {
856+ let s = Stream :: cpu ( ) ;
857+ // (2,3) @ (3,2) -> (2,2)
858+ let a = Array :: from_slice ( & [ 1.0f32 , 2.0 , 3.0 , 4.0 , 5.0 , 6.0 ] , & [ 2 , 3 ] ) ;
859+ let b = Array :: from_slice ( & [ 7.0f32 , 8.0 , 9.0 , 10.0 , 11.0 , 12.0 ] , & [ 3 , 2 ] ) ;
860+ let c = a. matmul ( & b, & s) . unwrap ( ) ;
861+ assert_eq ! ( c. shape( ) , vec![ 2 , 2 ] ) ;
862+ // [1,2,3]·[7,9,11] = 58, [1,2,3]·[8,10,12] = 64,
863+ // [4,5,6]·[7,9,11] = 139, [4,5,6]·[8,10,12] = 154.
864+ assert_eq ! ( c. to_vec:: <f32 >( ) , vec![ 58.0 , 64.0 , 139.0 , 154.0 ] ) ;
865+ }
866+
867+ #[ test]
868+ fn matmul_is_not_elementwise_multiply ( ) {
869+ let s = Stream :: cpu ( ) ;
870+ // Same square operands: matmul and `*` must disagree.
871+ let a = Array :: from_slice ( & [ 1.0f32 , 2.0 , 3.0 , 4.0 ] , & [ 2 , 2 ] ) ;
872+ assert_eq ! (
873+ a. matmul( & a, & s) . unwrap( ) . to_vec:: <f32 >( ) ,
874+ vec![ 7.0 , 10.0 , 15.0 , 22.0 ]
875+ ) ;
876+ assert_eq ! (
877+ a. multiply( & a, & s) . unwrap( ) . to_vec:: <f32 >( ) ,
878+ vec![ 1.0 , 4.0 , 9.0 , 16.0 ]
879+ ) ;
880+ }
881+
882+ #[ test]
883+ fn matmul_collapses_one_dim_operands ( ) {
884+ let s = Stream :: cpu ( ) ;
885+ let v = Array :: from_slice ( & [ 1.0f32 , 2.0 , 3.0 ] , & [ 3 ] ) ;
886+
887+ // (3,) @ (3,) is a dot product, and the result is 0-dimensional.
888+ let dot = v. matmul ( & v, & s) . unwrap ( ) ;
889+ assert_eq ! ( dot. ndim( ) , 0 ) ;
890+ assert_eq ! ( dot. item:: <f32 >( ) , 14.0 ) ; // 1 + 4 + 9
891+
892+ // (2,3) @ (3,) -> (2,), the appended axis is dropped again.
893+ let m = Array :: from_slice ( & [ 1.0f32 , 2.0 , 3.0 , 4.0 , 5.0 , 6.0 ] , & [ 2 , 3 ] ) ;
894+ let mv = m. matmul ( & v, & s) . unwrap ( ) ;
895+ assert_eq ! ( mv. shape( ) , vec![ 2 ] ) ;
896+ assert_eq ! ( mv. to_vec:: <f32 >( ) , vec![ 14.0 , 32.0 ] ) ;
897+ }
898+
899+ #[ test]
900+ fn matmul_broadcasts_batch_dimensions ( ) {
901+ let s = Stream :: cpu ( ) ;
902+ // Leading axes are batch dims: (2,2,3) @ (2,3,2) -> (2,2,2).
903+ let a = Array :: arange :: < f32 > ( 0.0 , 12.0 , 1.0 , & s)
904+ . unwrap ( )
905+ . reshape ( & [ 2 , 2 , 3 ] , & s)
906+ . unwrap ( ) ;
907+ let b = Array :: ones :: < f32 > ( & [ 2 , 3 , 2 ] , & s) . unwrap ( ) ;
908+ let c = a. matmul ( & b, & s) . unwrap ( ) ;
909+ assert_eq ! ( c. shape( ) , vec![ 2 , 2 , 2 ] ) ;
910+ // With a ones matrix each output is the row sum, duplicated per column.
911+ assert_eq ! (
912+ c. to_vec:: <f32 >( ) ,
913+ vec![ 3.0 , 3.0 , 12.0 , 12.0 , 21.0 , 21.0 , 30.0 , 30.0 ]
914+ ) ;
915+ }
916+
917+ #[ test]
918+ fn matmul_with_transpose ( ) {
919+ let s = Stream :: cpu ( ) ;
920+ // The shape a linear layer uses: x @ w.T, (2,3) @ (2,3).T -> (2,2).
921+ let x = Array :: from_slice ( & [ 1.0f32 , 2.0 , 3.0 , 4.0 , 5.0 , 6.0 ] , & [ 2 , 3 ] ) ;
922+ let w = Array :: from_slice ( & [ 1.0f32 , 0.0 , 0.0 , 0.0 , 1.0 , 0.0 ] , & [ 2 , 3 ] ) ;
923+ let out = x. matmul ( & w. transpose ( & s) . unwrap ( ) , & s) . unwrap ( ) ;
924+ assert_eq ! ( out. shape( ) , vec![ 2 , 2 ] ) ;
925+ // Rows of w select element 0 and element 1 of each row of x.
926+ assert_eq ! ( out. to_vec:: <f32 >( ) , vec![ 1.0 , 2.0 , 4.0 , 5.0 ] ) ;
927+ }
928+
929+ #[ test]
930+ fn matmul_shape_mismatch_returns_err ( ) {
931+ let s = Stream :: cpu ( ) ;
932+ // (2,3) @ (2,3) has inner dims 3 and 2 — not an error we should panic on.
933+ let a = Array :: from_slice ( & [ 1.0f32 , 2.0 , 3.0 , 4.0 , 5.0 , 6.0 ] , & [ 2 , 3 ] ) ;
934+ let err = a. matmul ( & a, & s) . unwrap_err ( ) ;
935+ assert ! (
936+ !err. message( ) . is_empty( ) ,
937+ "expected a message from mlx, got {err:?}"
938+ ) ;
939+ }
940+
768941 #[ test]
769942 #[ should_panic( expected = "does not match shape product" ) ]
770943 fn mismatched_len_and_shape_panics ( ) {
0 commit comments