Skip to content

Commit b50b1e7

Browse files
kerthcetCopilot
andauthored
feat: support more ops (#5)
* support more ops Signed-off-by: kerthcet <kerthcet@gmail.com> * add axis-specific reductions Signed-off-by: kerthcet <kerthcet@gmail.com> * Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> * address comments Signed-off-by: kerthcet <kerthcet@gmail.com> * address comments Signed-off-by: kerthcet <kerthcet@gmail.com> * address comments Signed-off-by: kerthcet <kerthcet@gmail.com> --------- Signed-off-by: kerthcet <kerthcet@gmail.com> Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
1 parent 4351624 commit b50b1e7

1 file changed

Lines changed: 214 additions & 0 deletions

File tree

‎crates/mlxcore/src/array.rs‎

Lines changed: 214 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,46 @@ impl Array {
181181
self.unary_op(stream, sys::mlx_negative)
182182
}
183183

184+
/// Elementwise natural logarithm.
185+
pub fn log(&self, stream: &Stream) -> Result<Array> {
186+
self.unary_op(stream, sys::mlx_log)
187+
}
188+
189+
/// Elementwise sine.
190+
pub fn sin(&self, stream: &Stream) -> Result<Array> {
191+
self.unary_op(stream, sys::mlx_sin)
192+
}
193+
194+
/// Elementwise cosine.
195+
pub fn cos(&self, stream: &Stream) -> Result<Array> {
196+
self.unary_op(stream, sys::mlx_cos)
197+
}
198+
199+
/// Elementwise square.
200+
pub fn square(&self, stream: &Stream) -> Result<Array> {
201+
self.unary_op(stream, sys::mlx_square)
202+
}
203+
204+
/// Elementwise hyperbolic tangent.
205+
pub fn tanh(&self, stream: &Stream) -> Result<Array> {
206+
self.unary_op(stream, sys::mlx_tanh)
207+
}
208+
209+
/// Elementwise power: `self ** other`.
210+
pub fn power(&self, other: &Array, stream: &Stream) -> Result<Array> {
211+
self.binary_op(other, stream, sys::mlx_power)
212+
}
213+
214+
/// Elementwise maximum of two arrays.
215+
pub fn maximum(&self, other: &Array, stream: &Stream) -> Result<Array> {
216+
self.binary_op(other, stream, sys::mlx_maximum)
217+
}
218+
219+
/// Elementwise minimum of two arrays.
220+
pub fn minimum(&self, other: &Array, stream: &Stream) -> Result<Array> {
221+
self.binary_op(other, stream, sys::mlx_minimum)
222+
}
223+
184224
/// Sum of all elements, returning a scalar array.
185225
///
186226
/// With `keepdims == false` the result is 0-dimensional.
@@ -195,6 +235,46 @@ impl Array {
195235
self.reduce_op(keepdims, stream, sys::mlx_mean)
196236
}
197237

238+
/// Sum over the given axes.
239+
///
240+
/// With `keepdims == false` the reduced axes are removed; otherwise they
241+
/// are kept with size 1.
242+
pub fn sum_axes(&self, axes: &[i32], keepdims: bool, stream: &Stream) -> Result<Array> {
243+
self.reduce_axes_op(axes, keepdims, stream, sys::mlx_sum_axes)
244+
}
245+
246+
/// Mean over the given axes.
247+
///
248+
/// With `keepdims == false` the reduced axes are removed; otherwise they
249+
/// are kept with size 1.
250+
pub fn mean_axes(&self, axes: &[i32], keepdims: bool, stream: &Stream) -> Result<Array> {
251+
self.reduce_axes_op(axes, keepdims, stream, sys::mlx_mean_axes)
252+
}
253+
254+
/// Maximum over the given axes.
255+
///
256+
/// With `keepdims == false` the reduced axes are removed; otherwise they
257+
/// are kept with size 1.
258+
pub fn max_axes(&self, axes: &[i32], keepdims: bool, stream: &Stream) -> Result<Array> {
259+
self.reduce_axes_op(axes, keepdims, stream, sys::mlx_max_axes)
260+
}
261+
262+
/// Minimum over the given axes.
263+
///
264+
/// With `keepdims == false` the reduced axes are removed; otherwise they
265+
/// are kept with size 1.
266+
pub fn min_axes(&self, axes: &[i32], keepdims: bool, stream: &Stream) -> Result<Array> {
267+
self.reduce_axes_op(axes, keepdims, stream, sys::mlx_min_axes)
268+
}
269+
270+
/// Product over the given axes.
271+
///
272+
/// With `keepdims == false` the reduced axes are removed; otherwise they
273+
/// are kept with size 1.
274+
pub fn prod_axes(&self, axes: &[i32], keepdims: bool, stream: &Stream) -> Result<Array> {
275+
self.reduce_axes_op(axes, keepdims, stream, sys::mlx_prod_axes)
276+
}
277+
198278
/// Shared plumbing for `res = op(a, b, stream)` binary ops.
199279
fn binary_op(
200280
&self,
@@ -241,6 +321,48 @@ impl Array {
241321
Self::from_op(out, status)
242322
}
243323

324+
/// Shared plumbing for `res = op(a, axes, axes_num, keepdims, stream)`
325+
/// reductions over specific axes.
326+
fn reduce_axes_op(
327+
&self,
328+
axes: &[i32],
329+
keepdims: bool,
330+
stream: &Stream,
331+
op: unsafe extern "C" fn(
332+
*mut sys::mlx_array,
333+
sys::mlx_array,
334+
*const i32,
335+
usize,
336+
bool,
337+
sys::mlx_stream,
338+
) -> i32,
339+
) -> Result<Array> {
340+
error::install();
341+
// For an empty slice `as_ptr()` is non-null but dangling; pass an
342+
// explicit null pointer so the FFI call never hands C a bogus pointer
343+
// even if it were to dereference it with `axes_num == 0`.
344+
let axes_ptr = if axes.is_empty() {
345+
std::ptr::null()
346+
} else {
347+
axes.as_ptr()
348+
};
349+
let mut out = unsafe { sys::mlx_array_new() };
350+
// SAFETY: `axes_ptr`/`axes.len()` describe a valid slice (or null/0) for
351+
// the duration of the call; all handles are valid; `op` writes the
352+
// result into `out`.
353+
let status = unsafe {
354+
op(
355+
&mut out,
356+
self.handle,
357+
axes_ptr,
358+
axes.len(),
359+
keepdims,
360+
stream.as_raw(),
361+
)
362+
};
363+
Self::from_op(out, status)
364+
}
365+
244366
/// Wraps an op's `out` handle and status code into a `Result`.
245367
///
246368
/// On failure, frees the (unused) `out` handle and returns the captured
@@ -397,6 +519,48 @@ mod tests {
397519
);
398520
}
399521

522+
#[test]
523+
fn more_unary_ops() {
524+
let s = Stream::cpu();
525+
let a = Array::from_slice(&[1.0f32, 2.0, 3.0], &[3]);
526+
assert_eq!(a.square(&s).unwrap().to_vec::<f32>(), vec![1.0, 4.0, 9.0]);
527+
528+
// log(1) == 0, and log(e) ~= 1.
529+
let b = Array::from_slice(&[1.0f32, std::f32::consts::E], &[2]);
530+
let logged = b.log(&s).unwrap().to_vec::<f32>();
531+
assert!((logged[0]).abs() < 1e-6);
532+
assert!((logged[1] - 1.0).abs() < 1e-6);
533+
534+
// sin(0) == 0, cos(0) == 1, tanh(0) == 0.
535+
let z = Array::from_slice(&[0.0f32], &[1]);
536+
assert!(z.sin(&s).unwrap().item::<f32>().abs() < 1e-6);
537+
assert!((z.cos(&s).unwrap().item::<f32>() - 1.0).abs() < 1e-6);
538+
assert!(z.tanh(&s).unwrap().item::<f32>().abs() < 1e-6);
539+
}
540+
541+
#[test]
542+
fn more_binary_ops() {
543+
let s = Stream::cpu();
544+
let a = Array::from_slice(&[1.0f32, 2.0, 3.0], &[3]);
545+
let b = Array::from_slice(&[3.0f32, 2.0, 1.0], &[3]);
546+
547+
assert_eq!(
548+
a.maximum(&b, &s).unwrap().to_vec::<f32>(),
549+
vec![3.0, 2.0, 3.0]
550+
);
551+
assert_eq!(
552+
a.minimum(&b, &s).unwrap().to_vec::<f32>(),
553+
vec![1.0, 2.0, 1.0]
554+
);
555+
556+
let base = Array::from_slice(&[2.0f32, 3.0], &[2]);
557+
let exp = Array::from_slice(&[3.0f32, 2.0], &[2]);
558+
assert_eq!(
559+
base.power(&exp, &s).unwrap().to_vec::<f32>(),
560+
vec![8.0, 9.0]
561+
);
562+
}
563+
400564
#[test]
401565
fn reductions_produce_scalars() {
402566
let s = Stream::cpu();
@@ -418,6 +582,56 @@ mod tests {
418582
assert_eq!(sum.item::<f32>(), 10.0);
419583
}
420584

585+
#[test]
586+
fn axis_reductions() {
587+
let s = Stream::cpu();
588+
// [[1, 2, 3],
589+
// [4, 5, 6]]
590+
let a = Array::from_slice(&[1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
591+
592+
// Sum over axis 0 (rows) -> [5, 7, 9], shape [3].
593+
let col_sums = a.sum_axes(&[0], false, &s).unwrap();
594+
assert_eq!(col_sums.shape(), vec![3]);
595+
assert_eq!(col_sums.to_vec::<f32>(), vec![5.0, 7.0, 9.0]);
596+
597+
// Sum over axis 1 (cols) -> [6, 15], shape [2].
598+
let row_sums = a.sum_axes(&[1], false, &s).unwrap();
599+
assert_eq!(row_sums.to_vec::<f32>(), vec![6.0, 15.0]);
600+
601+
// keepdims keeps the reduced axis as size 1.
602+
let kept = a.sum_axes(&[1], true, &s).unwrap();
603+
assert_eq!(kept.shape(), vec![2, 1]);
604+
605+
// max / min over axis 0; mean / prod over axis 1.
606+
assert_eq!(
607+
a.max_axes(&[0], false, &s).unwrap().to_vec::<f32>(),
608+
vec![4.0, 5.0, 6.0]
609+
);
610+
assert_eq!(
611+
a.min_axes(&[0], false, &s).unwrap().to_vec::<f32>(),
612+
vec![1.0, 2.0, 3.0]
613+
);
614+
assert_eq!(
615+
a.mean_axes(&[1], false, &s).unwrap().to_vec::<f32>(),
616+
vec![2.0, 5.0]
617+
);
618+
assert_eq!(
619+
a.prod_axes(&[1], false, &s).unwrap().to_vec::<f32>(),
620+
vec![6.0, 120.0]
621+
);
622+
}
623+
624+
#[test]
625+
fn empty_axes_reduction_is_noop() {
626+
// Reducing over no axes must not pass a dangling pointer to C; MLX
627+
// treats it as an identity that leaves the values unchanged.
628+
let s = Stream::cpu();
629+
let a = Array::from_slice(&[1.0f32, 2.0, 3.0, 4.0], &[2, 2]);
630+
let r = a.sum_axes(&[], false, &s).unwrap();
631+
assert_eq!(r.shape(), vec![2, 2]);
632+
assert_eq!(r.to_vec::<f32>(), vec![1.0, 2.0, 3.0, 4.0]);
633+
}
634+
421635
#[test]
422636
fn incompatible_shapes_return_err() {
423637
let s = Stream::cpu();

0 commit comments

Comments
 (0)