Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use custom c shim for fallible closure #116

Merged
merged 15 commits into from
Sep 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions mlx-rs/examples/tutorial.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,10 @@ fn automatic_differentiation() {

let x = Array::from(1.5);

let mut dfdx = calculate_grad(f, &x);
let dfdx = calculate_grad(f, &x);
assert_eq!(dfdx.item::<f32>(), 2.0 * 1.5);

let mut dfdx2 = calculate_grad(|args| calculate_grad(f, args), &x);
let dfdx2 = calculate_grad(|args| calculate_grad(f, args), &x);
assert_eq!(dfdx2.item::<f32>(), 2.0);
}

Expand Down
6 changes: 3 additions & 3 deletions mlx-rs/src/array/operators.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{prelude::ScalarOrArray, Array, StreamOrDevice};
use crate::{utils::ScalarOrArray, Array, StreamOrDevice};
use num_traits::Pow;
use std::ops::{
Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Not, Rem, RemAssign, Sub, SubAssign,
Expand All @@ -14,7 +14,7 @@ macro_rules! impl_binary_op {

fn $method(self, rhs: T) -> Self::Output {
paste::paste! {
self.[<$c_method _device>](rhs, StreamOrDevice::default()).unwrap()
self.[<$c_method _device>](rhs.into_owned_or_ref_array(), StreamOrDevice::default()).unwrap()
}
}
}
Expand All @@ -27,7 +27,7 @@ macro_rules! impl_binary_op {

fn $method(self, rhs: T) -> Self::Output {
paste::paste! {
self.[<$c_method _device>](rhs, StreamOrDevice::default()).unwrap()
self.[<$c_method _device>](rhs.into_owned_or_ref_array(), StreamOrDevice::default()).unwrap()
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions mlx-rs/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ impl Exception {
}

thread_local! {
pub static LAST_MLX_ERROR: Cell<*const c_char> = const { Cell::new(std::ptr::null()) };
pub static IS_HANDLER_SET: Cell<bool> = const { Cell::new(false) };
static LAST_MLX_ERROR: Cell<*const c_char> = const { Cell::new(std::ptr::null()) };
static IS_HANDLER_SET: Cell<bool> = const { Cell::new(false) };
}

#[no_mangle]
Expand Down
1 change: 0 additions & 1 deletion mlx-rs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ pub mod prelude {
dtype::Dtype,
ops::indexing::{Ellipsis, IndexMutOp, IndexOp, IntoStrideBy, NewAxis},
stream::StreamOrDevice,
utils::ScalarOrArray,
};

pub use num_traits::Pow;
Expand Down
22 changes: 22 additions & 0 deletions mlx-rs/src/macros/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,19 @@
/// [10, 11, 12]
/// ]
/// ]);
///
/// // Create a 2x2 array by specifying the shape
/// let a = array!([1, 2, 3, 4], shape=[2, 2]);
/// ```
#[macro_export]
macro_rules! array {
([$($x:expr),*], shape=[$($s:expr),*]) => {
{
let data = [$($x,)*];
let shape = [$($s,)*];
$crate::Array::from_slice(&data, &shape)
}
};
([$([$([$($x:expr),*]),*]),*]) => {
{
let arr = [$([$([$($x,)*],)*],)*];
Expand Down Expand Up @@ -133,4 +143,16 @@ mod tests {
assert_eq!(a.index((1, 1, 1)).item::<i32>(), 11);
assert_eq!(a.index((1, 1, 2)).item::<i32>(), 12);
}

#[test]
fn test_array_with_shape() {
let a = array!([1, 2, 3, 4], shape = [2, 2]);

assert!(a.ndim() == 2);
assert_eq!(a.shape(), &[2, 2]);
assert_eq!(a.index((0, 0)).item::<i32>(), 1);
assert_eq!(a.index((0, 1)).item::<i32>(), 2);
assert_eq!(a.index((1, 0)).item::<i32>(), 3);
assert_eq!(a.index((1, 1)).item::<i32>(), 4);
}
}
21 changes: 21 additions & 0 deletions mlx-rs/src/macros/internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,33 @@ macro_rules! try_catch_c_ptr_expr {
if c_ptr.is_null() {
// SAFETY: there must be an error if the pointer is null
return Err($crate::error::get_and_clear_last_mlx_error()
// .or($crate::error::take_last_mlx_closure_error())
.expect("A null pointer was returned, but no error was set."));
}
c_ptr
}};
}

macro_rules! try_catch_mlx_closure_error {
($expr:expr) => {{
if !$crate::error::is_mlx_error_handler_set() {
$crate::error::setup_mlx_error_handler();
}

let c_ptr = $expr;
// Always check for closure errors
if let Some(error) = $crate::error::get_and_clear_last_mlx_error()
// .or($crate::error::take_last_mlx_closure_error())
{
return Err(error);
}
if c_ptr.is_null() {
panic!("A null pointer was returned, but no error was set.");
}
c_ptr
}};
}

/// See `assertEqual` in the swift binding tests
#[allow(unused_macros)]
macro_rules! assert_array_all_close {
Expand Down
Loading