torobi 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/CHANGELOG.md +71 -0
- data/Cargo.lock +539 -0
- data/Cargo.toml +6 -0
- data/LICENSE +21 -0
- data/README.md +259 -0
- data/config/ops.yml +230 -0
- data/docs/plan.md +3982 -0
- data/docs/vendoring.md +656 -0
- data/engine/Cargo.toml +35 -0
- data/engine/build.rs +253 -0
- data/engine/src/checkpoint.rs +513 -0
- data/engine/src/executor.rs +257 -0
- data/engine/src/export.rs +431 -0
- data/engine/src/fixtures.rs +518 -0
- data/engine/src/graph.rs +115 -0
- data/engine/src/init.rs +65 -0
- data/engine/src/interp.rs +985 -0
- data/engine/src/lib.rs +62 -0
- data/engine/src/main.rs +97 -0
- data/engine/src/memory.rs +109 -0
- data/engine/src/mlxc/array.rs +454 -0
- data/engine/src/mlxc/error.rs +205 -0
- data/engine/src/mlxc/fast.rs +46 -0
- data/engine/src/mlxc/handle.rs +155 -0
- data/engine/src/mlxc/io.rs +268 -0
- data/engine/src/mlxc/memory.rs +56 -0
- data/engine/src/mlxc/metal.rs +24 -0
- data/engine/src/mlxc/mod.rs +55 -0
- data/engine/src/mlxc/nn.rs +38 -0
- data/engine/src/mlxc/ops.rs +477 -0
- data/engine/src/mlxc/quantized.rs +405 -0
- data/engine/src/mlxc/random.rs +161 -0
- data/engine/src/mlxc/transforms.rs +439 -0
- data/engine/src/op.rs +745 -0
- data/engine/src/optimizer.rs +650 -0
- data/engine/src/plan.rs +1638 -0
- data/engine/src/runtime.rs +377 -0
- data/engine/src/session.rs +1523 -0
- data/engine/src/state.rs +1007 -0
- data/engine/src/tensor.rs +331 -0
- data/ext/torobi/Cargo.toml +21 -0
- data/ext/torobi/extconf.rb +42 -0
- data/ext/torobi/src/gvl.rs +182 -0
- data/ext/torobi/src/lib.rs +1037 -0
- data/lib/torobi/adapter_file.rb +184 -0
- data/lib/torobi/batch.rb +55 -0
- data/lib/torobi/checkpoint.rb +60 -0
- data/lib/torobi/dsl/builder.rb +414 -0
- data/lib/torobi/dsl/handle.rb +156 -0
- data/lib/torobi/dsl/layers.rb +82 -0
- data/lib/torobi/dsl.rb +35 -0
- data/lib/torobi/errors.rb +88 -0
- data/lib/torobi/export.rb +534 -0
- data/lib/torobi/freeze.rb +24 -0
- data/lib/torobi/freshness.rb +57 -0
- data/lib/torobi/grad_cache.rb +143 -0
- data/lib/torobi/graph_config.rb +301 -0
- data/lib/torobi/hooks.rb +439 -0
- data/lib/torobi/ir/dimensions.rb +26 -0
- data/lib/torobi/ir/dtype.rb +28 -0
- data/lib/torobi/ir/graph/check.rb +116 -0
- data/lib/torobi/ir/graph.rb +52 -0
- data/lib/torobi/ir/input_spec.rb +39 -0
- data/lib/torobi/ir/json.rb +45 -0
- data/lib/torobi/ir/node_spec.rb +52 -0
- data/lib/torobi/ir/parameter_spec.rb +67 -0
- data/lib/torobi/ir/ref.rb +52 -0
- data/lib/torobi/ir/source.rb +65 -0
- data/lib/torobi/ir.rb +23 -0
- data/lib/torobi/journal.rb +310 -0
- data/lib/torobi/lora.rb +190 -0
- data/lib/torobi/memory.rb +50 -0
- data/lib/torobi/metallib.rb +50 -0
- data/lib/torobi/mlx_prebuilt.json +24 -0
- data/lib/torobi/mlx_prebuilt.rb +378 -0
- data/lib/torobi/models/build.rb +37 -0
- data/lib/torobi/models/description.rb +59 -0
- data/lib/torobi/models/gemma3.rb +273 -0
- data/lib/torobi/models/llama.rb +381 -0
- data/lib/torobi/models/modern_bert.rb +513 -0
- data/lib/torobi/models/padding.rb +27 -0
- data/lib/torobi/models/windows.rb +53 -0
- data/lib/torobi/ops.rb +81 -0
- data/lib/torobi/preflight.rb +136 -0
- data/lib/torobi/provenance.rb +75 -0
- data/lib/torobi/quantization.rb +151 -0
- data/lib/torobi/replay.rb +229 -0
- data/lib/torobi/runner.rb +419 -0
- data/lib/torobi/session.rb +855 -0
- data/lib/torobi/shape.rb +438 -0
- data/lib/torobi/tensor_data.rb +178 -0
- data/lib/torobi/version.rb +5 -0
- data/lib/torobi/weights.rb +108 -0
- data/lib/torobi.rb +67 -0
- data/licenses/MLX.txt +21 -0
- data/licenses/README.md +16 -0
- data/licenses/gguflib.txt +21 -0
- data/licenses/mlx-c.txt +21 -0
- data/licenses/mlx-rs.txt +27 -0
- metadata +229 -0
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
//! Differentiation, which is where a Rust closure crosses into C++.
|
|
2
|
+
//!
|
|
3
|
+
//! This is the riskiest part of the binding: every other call either links
|
|
4
|
+
//! or does not, and this one can compile and then misbehave. The closure
|
|
5
|
+
//! travels to mlx-c as a payload with a destructor, is called back through
|
|
6
|
+
//! [`trampoline`], and reports failure with the only thing the boundary
|
|
7
|
+
//! carries, an `int`. What actually went wrong waits on the Rust side
|
|
8
|
+
//! ([`park`]) and is picked up once control is back in Rust ([`settle`]).
|
|
9
|
+
|
|
10
|
+
use std::any::Any;
|
|
11
|
+
use std::cell::RefCell;
|
|
12
|
+
use std::ffi::{c_int, c_void};
|
|
13
|
+
use std::marker::PhantomData;
|
|
14
|
+
use std::panic::{catch_unwind, resume_unwind, AssertUnwindSafe};
|
|
15
|
+
|
|
16
|
+
use super::error::{self, check, failure, install, Exception, Result};
|
|
17
|
+
use super::handle::Vector;
|
|
18
|
+
use super::{sys, Array};
|
|
19
|
+
|
|
20
|
+
const SUCCESS: c_int = 0;
|
|
21
|
+
const FAILURE: c_int = 1;
|
|
22
|
+
|
|
23
|
+
/// Why a closure reported failure to mlx-c.
|
|
24
|
+
enum Parked {
|
|
25
|
+
Error(Exception),
|
|
26
|
+
Panic(Box<dyn Any + Send>),
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
thread_local! {
|
|
30
|
+
/// What a closure failed with, on its way back through C.
|
|
31
|
+
static PARKED: RefCell<Option<Parked>> = const { RefCell::new(None) };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
fn park(parked: Parked) {
|
|
35
|
+
PARKED.with(|slot| *slot.borrow_mut() = Some(parked));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/// The status of a call that ran a closure, with the closure's own failure
|
|
39
|
+
/// taking precedence over what MLX made of it.
|
|
40
|
+
///
|
|
41
|
+
/// When a closure fails, mlx-c turns the `1` it returned into a C++
|
|
42
|
+
/// exception and reports *that* ("mlx_closure returned a non-zero value"),
|
|
43
|
+
/// which says nothing. The parked error is the cause, so it wins, and MLX's
|
|
44
|
+
/// message is dropped rather than left to be blamed on a later call.
|
|
45
|
+
///
|
|
46
|
+
/// A panic resumes here, on the Rust side, with its own payload: the
|
|
47
|
+
/// engine's runtime relies on a panic unwinding through its gate to close
|
|
48
|
+
/// the process to further MLX work (`crate::runtime`), and turning it into
|
|
49
|
+
/// an error on the way through C would quietly undo that.
|
|
50
|
+
#[track_caller]
|
|
51
|
+
fn settle(status: c_int, operation: &str) -> Result<()> {
|
|
52
|
+
match PARKED.with(|slot| slot.borrow_mut().take()) {
|
|
53
|
+
Some(Parked::Panic(payload)) => {
|
|
54
|
+
error::forget_said();
|
|
55
|
+
resume_unwind(payload)
|
|
56
|
+
}
|
|
57
|
+
Some(Parked::Error(error)) if status != 0 => {
|
|
58
|
+
error::forget_said();
|
|
59
|
+
Err(error)
|
|
60
|
+
}
|
|
61
|
+
_ => check(status, operation),
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/// A Rust closure, owned by mlx-c as an `mlx_closure`.
|
|
66
|
+
///
|
|
67
|
+
/// `'a` is what the closure borrows. The closure (and every copy MLX takes
|
|
68
|
+
/// of it) is freed when this is dropped, which is why nothing that holds
|
|
69
|
+
/// one may outlive `'a`.
|
|
70
|
+
struct Closure<'a> {
|
|
71
|
+
raw: sys::mlx_closure,
|
|
72
|
+
_borrows: PhantomData<&'a ()>,
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
type Function<'a> = dyn FnMut(&[Array]) -> Result<Vec<Array>> + 'a;
|
|
76
|
+
|
|
77
|
+
impl<'a> Closure<'a> {
|
|
78
|
+
fn new<F>(f: F) -> Result<Self>
|
|
79
|
+
where
|
|
80
|
+
F: FnMut(&[Array]) -> Result<Vec<Array>> + 'a,
|
|
81
|
+
{
|
|
82
|
+
install();
|
|
83
|
+
let payload = Box::into_raw(Box::new(f)) as *mut c_void;
|
|
84
|
+
// From here the payload is mlx-c's: it wraps it with `release` as
|
|
85
|
+
// the deleter before anything else can fail, and runs that deleter
|
|
86
|
+
// when the last copy of the closure goes, or on its own failure.
|
|
87
|
+
let raw = unsafe {
|
|
88
|
+
sys::mlx_closure_new_func_payload(Some(trampoline::<F>), payload, Some(release::<F>))
|
|
89
|
+
};
|
|
90
|
+
if raw.ctx.is_null() {
|
|
91
|
+
return Err(failure("mlx_closure_new_func_payload"));
|
|
92
|
+
}
|
|
93
|
+
Ok(Self {
|
|
94
|
+
raw,
|
|
95
|
+
_borrows: PhantomData,
|
|
96
|
+
})
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
impl Drop for Closure<'_> {
|
|
101
|
+
fn drop(&mut self) {
|
|
102
|
+
unsafe { sys::mlx_closure_free(self.raw) };
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/// What mlx-c calls, and what calls the Rust closure behind `payload`.
|
|
107
|
+
///
|
|
108
|
+
/// Nothing may unwind out of here: this frame is called from C++, where a
|
|
109
|
+
/// Rust panic is undefined behaviour rather than an error. A panic is
|
|
110
|
+
/// caught and parked with its payload, and resumed once control is back
|
|
111
|
+
/// in Rust (`error::settle`).
|
|
112
|
+
///
|
|
113
|
+
/// `inputs` belongs to mlx-c, which frees it after this returns; `out` is
|
|
114
|
+
/// an empty vector mlx-c made, and what is written into it is copied, so
|
|
115
|
+
/// the vector built here is dropped afterwards like any other.
|
|
116
|
+
extern "C" fn trampoline<F>(
|
|
117
|
+
out: *mut sys::mlx_vector_array,
|
|
118
|
+
inputs: sys::mlx_vector_array,
|
|
119
|
+
payload: *mut c_void,
|
|
120
|
+
) -> c_int
|
|
121
|
+
where
|
|
122
|
+
F: FnMut(&[Array]) -> Result<Vec<Array>>,
|
|
123
|
+
{
|
|
124
|
+
let caught = catch_unwind(AssertUnwindSafe(|| {
|
|
125
|
+
let closure = unsafe { &mut *(payload as *mut F) };
|
|
126
|
+
let produced = unsafe { Vector::read(inputs) }
|
|
127
|
+
.and_then(|given| closure(&given))
|
|
128
|
+
.and_then(|produced| Vector::of(&produced))
|
|
129
|
+
.and_then(|vector| {
|
|
130
|
+
check(
|
|
131
|
+
unsafe { sys::mlx_vector_array_set(out, vector.as_raw()) },
|
|
132
|
+
"mlx_vector_array_set",
|
|
133
|
+
)
|
|
134
|
+
});
|
|
135
|
+
match produced {
|
|
136
|
+
Ok(()) => SUCCESS,
|
|
137
|
+
Err(error) => {
|
|
138
|
+
park(Parked::Error(error));
|
|
139
|
+
FAILURE
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}));
|
|
143
|
+
caught.unwrap_or_else(|payload| {
|
|
144
|
+
park(Parked::Panic(payload));
|
|
145
|
+
FAILURE
|
|
146
|
+
})
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
extern "C" fn release<F>(payload: *mut c_void) {
|
|
150
|
+
if payload.is_null() {
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
// A closure whose captures panic on drop would otherwise unwind into
|
|
154
|
+
// C++. Dropping the panic is the lesser harm.
|
|
155
|
+
let _ = catch_unwind(AssertUnwindSafe(|| unsafe {
|
|
156
|
+
drop(Box::from_raw(payload as *mut F));
|
|
157
|
+
}));
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/// A closure made differentiable: the function MLX returns for its value
|
|
161
|
+
/// and its gradient with respect to `argnums`.
|
|
162
|
+
///
|
|
163
|
+
/// Made once and applied as often as it is called, so "differentiate this"
|
|
164
|
+
/// and "at these arguments" are separate steps. Holds the closure it was
|
|
165
|
+
/// made from, since MLX's copy calls back into it, and so borrows what the
|
|
166
|
+
/// closure borrows.
|
|
167
|
+
struct Gradient<'a> {
|
|
168
|
+
raw: sys::mlx_closure_value_and_grad,
|
|
169
|
+
closure: Closure<'a>,
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
impl<'a> Gradient<'a> {
|
|
173
|
+
fn new(closure: Closure<'a>, argnums: &[i32]) -> Result<Self> {
|
|
174
|
+
let mut gradient = Gradient {
|
|
175
|
+
raw: unsafe { sys::mlx_closure_value_and_grad_new() },
|
|
176
|
+
closure,
|
|
177
|
+
};
|
|
178
|
+
check(
|
|
179
|
+
unsafe {
|
|
180
|
+
sys::mlx_value_and_grad(
|
|
181
|
+
&mut gradient.raw,
|
|
182
|
+
gradient.closure.raw,
|
|
183
|
+
argnums.as_ptr(),
|
|
184
|
+
argnums.len(),
|
|
185
|
+
)
|
|
186
|
+
},
|
|
187
|
+
"mlx_value_and_grad",
|
|
188
|
+
)?;
|
|
189
|
+
Ok(gradient)
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/// The values and the gradients at `arrays`.
|
|
193
|
+
fn apply(&mut self, arrays: &[Array]) -> Result<(Vec<Array>, Vec<Array>)> {
|
|
194
|
+
let given = Vector::of(arrays)?;
|
|
195
|
+
let mut values = Vector::new();
|
|
196
|
+
let mut grads = Vector::new();
|
|
197
|
+
let status = unsafe {
|
|
198
|
+
sys::mlx_closure_value_and_grad_apply(values.as_out(), grads.as_out(), self.raw, given.as_raw())
|
|
199
|
+
};
|
|
200
|
+
settle(status, "mlx_closure_value_and_grad_apply")?;
|
|
201
|
+
Ok((values.arrays()?, grads.arrays()?))
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
impl Drop for Gradient<'_> {
|
|
206
|
+
fn drop(&mut self) {
|
|
207
|
+
unsafe { sys::mlx_closure_value_and_grad_free(self.raw) };
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/// Evaluates every array given, together: one graph, one submission.
|
|
212
|
+
pub fn eval<'a>(outputs: impl IntoIterator<Item = &'a Array>) -> Result<()> {
|
|
213
|
+
let vector = Vector::of(outputs)?;
|
|
214
|
+
check(unsafe { sys::mlx_eval(vector.as_raw()) }, "mlx_eval")
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/// The closures `value_and_grad_with_argnums` accepts: one that can fail
|
|
218
|
+
/// and one that cannot, as mlx-rs takes both.
|
|
219
|
+
pub trait IntoValueAndGrad<'a, Err> {
|
|
220
|
+
#[doc(hidden)]
|
|
221
|
+
fn into_function(self) -> Box<Function<'a>>;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
impl<'a, F> IntoValueAndGrad<'a, ()> for F
|
|
225
|
+
where
|
|
226
|
+
F: FnMut(&[Array]) -> Vec<Array> + 'a,
|
|
227
|
+
{
|
|
228
|
+
fn into_function(mut self) -> Box<Function<'a>> {
|
|
229
|
+
Box::new(move |inputs| Ok(self(inputs)))
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
impl<'a, F> IntoValueAndGrad<'a, Exception> for F
|
|
234
|
+
where
|
|
235
|
+
F: FnMut(&[Array]) -> Result<Vec<Array>> + 'a,
|
|
236
|
+
{
|
|
237
|
+
fn into_function(self) -> Box<Function<'a>> {
|
|
238
|
+
Box::new(self)
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/// `f` and its gradient with respect to the arguments `argnums` names, as
|
|
243
|
+
/// a function of the arguments: mlx-rs's `value_and_grad_with_argnums`.
|
|
244
|
+
///
|
|
245
|
+
/// Every handle a call makes is owned as soon as it exists, so a failure
|
|
246
|
+
/// at any point (MLX refusing the closure, the closure failing, a vector
|
|
247
|
+
/// that cannot be read back) frees them on the way out.
|
|
248
|
+
pub fn value_and_grad_with_argnums<'a, F, Err>(
|
|
249
|
+
f: F,
|
|
250
|
+
argnums: &'a [i32],
|
|
251
|
+
) -> impl FnMut(&[Array]) -> Result<(Vec<Array>, Vec<Array>)> + 'a
|
|
252
|
+
where
|
|
253
|
+
F: IntoValueAndGrad<'a, Err> + 'a,
|
|
254
|
+
{
|
|
255
|
+
// The signature returns the function rather than a `Result`, as mlx-rs's
|
|
256
|
+
// did, so a closure MLX would not take is reported on each call, as the
|
|
257
|
+
// error it was.
|
|
258
|
+
let mut gradient = Closure::new(f.into_function()).and_then(|closure| Gradient::new(closure, argnums));
|
|
259
|
+
move |arrays: &[Array]| match &mut gradient {
|
|
260
|
+
Ok(gradient) => gradient.apply(arrays),
|
|
261
|
+
Err(refused) => Err(refused.clone()),
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
#[cfg(test)]
|
|
266
|
+
mod tests {
|
|
267
|
+
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
268
|
+
use std::sync::Arc;
|
|
269
|
+
|
|
270
|
+
use super::*;
|
|
271
|
+
use crate::runtime;
|
|
272
|
+
|
|
273
|
+
fn run<R>(f: impl FnOnce() -> Result<R>) -> R {
|
|
274
|
+
runtime::runtime()
|
|
275
|
+
.execute(|| Ok(f()?))
|
|
276
|
+
.expect("the runtime should let this through")
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
fn square(x: &Array) -> Result<Array> {
|
|
280
|
+
Array::on_stream("mlx_multiply", |res, s| unsafe {
|
|
281
|
+
sys::mlx_multiply(res, x.as_raw(), x.as_raw(), s)
|
|
282
|
+
})
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/// Counts the drops of whatever it is captured by, so a test can see
|
|
286
|
+
/// that the payload mlx-c was handed went exactly once.
|
|
287
|
+
#[derive(Clone)]
|
|
288
|
+
struct Dropped(Arc<AtomicUsize>);
|
|
289
|
+
|
|
290
|
+
impl Drop for Dropped {
|
|
291
|
+
fn drop(&mut self) {
|
|
292
|
+
self.0.fetch_add(1, Ordering::SeqCst);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/// A counter, and a token whose clones each count one drop.
|
|
297
|
+
fn counter() -> (Arc<AtomicUsize>, Dropped) {
|
|
298
|
+
let count = Arc::new(AtomicUsize::new(0));
|
|
299
|
+
(count.clone(), Dropped(count))
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/// d/dx of x^2 at x = 3 is 6, and the value is 9.
|
|
303
|
+
///
|
|
304
|
+
/// Trivial arithmetic on purpose: what is under test is the closure
|
|
305
|
+
/// crossing into C++ and the arrays coming back, not the maths.
|
|
306
|
+
#[test]
|
|
307
|
+
fn a_closure_crosses_into_mlx_and_its_gradient_comes_back() {
|
|
308
|
+
let answer = run(|| {
|
|
309
|
+
let f = |inputs: &[Array]| -> Result<Vec<Array>> { Ok(vec![square(&inputs[0])?]) };
|
|
310
|
+
let (values, grads) = value_and_grad_with_argnums(f, &[0])(&[Array::from_f32(3.0)?])?;
|
|
311
|
+
Ok((values[0].item::<f32>()?, grads[0].item::<f32>()?))
|
|
312
|
+
});
|
|
313
|
+
assert_eq!(answer, (9.0, 6.0));
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/// The infallible form is the same function.
|
|
317
|
+
#[test]
|
|
318
|
+
fn a_closure_that_cannot_fail_is_taken_as_well() {
|
|
319
|
+
let answer = run(|| {
|
|
320
|
+
let f = |inputs: &[Array]| -> Vec<Array> { vec![square(&inputs[0]).unwrap()] };
|
|
321
|
+
let (_, grads) = value_and_grad_with_argnums(f, &[0])(&[Array::from_f32(2.0)?])?;
|
|
322
|
+
grads[0].item::<f32>()
|
|
323
|
+
});
|
|
324
|
+
assert_eq!(answer, 4.0);
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/// A closure that fails reports its own error rather than MLX's
|
|
328
|
+
/// "mlx_closure returned a non-zero value", which is the whole reason
|
|
329
|
+
/// the parking slot exists.
|
|
330
|
+
#[test]
|
|
331
|
+
fn a_closure_that_fails_says_what_it_was() {
|
|
332
|
+
let said = run(|| {
|
|
333
|
+
let refuses = |_: &[Array]| -> Result<Vec<Array>> {
|
|
334
|
+
Err(Exception::custom("the objective gave up"))
|
|
335
|
+
};
|
|
336
|
+
Ok(value_and_grad_with_argnums(refuses, &[0])(&[Array::from_f32(1.0)?])
|
|
337
|
+
.unwrap_err()
|
|
338
|
+
.to_string())
|
|
339
|
+
});
|
|
340
|
+
assert!(said.contains("the objective gave up"), "{said}");
|
|
341
|
+
assert!(!said.contains("non-zero"), "{said}");
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/// A panic does not cross C++, and comes out the other side as the
|
|
345
|
+
/// same panic, which is what lets the runtime's gate be poisoned by it.
|
|
346
|
+
#[test]
|
|
347
|
+
fn a_closure_that_panics_resumes_its_panic_on_the_rust_side() {
|
|
348
|
+
// Outside the runtime's gate on purpose: a panic through the gate
|
|
349
|
+
// would poison it for every later test.
|
|
350
|
+
let caught = std::panic::catch_unwind(|| {
|
|
351
|
+
let panics = |_: &[Array]| -> Result<Vec<Array>> { panic!("inside the closure") };
|
|
352
|
+
let _ = value_and_grad_with_argnums(panics, &[0])(&[Array::from_f32(1.0).unwrap()]);
|
|
353
|
+
});
|
|
354
|
+
let payload = caught.expect_err("the panic should come back");
|
|
355
|
+
let said = payload
|
|
356
|
+
.downcast_ref::<&str>()
|
|
357
|
+
.map(|s| s.to_string())
|
|
358
|
+
.or_else(|| payload.downcast_ref::<String>().cloned())
|
|
359
|
+
.unwrap_or_default();
|
|
360
|
+
assert_eq!(said, "inside the closure");
|
|
361
|
+
|
|
362
|
+
// And nothing is left parked to be blamed on the next call.
|
|
363
|
+
let next = run(|| {
|
|
364
|
+
let f = |inputs: &[Array]| -> Result<Vec<Array>> { Ok(vec![square(&inputs[0])?]) };
|
|
365
|
+
let (values, _) = value_and_grad_with_argnums(f, &[0])(&[Array::from_f32(2.0)?])?;
|
|
366
|
+
values[0].item::<f32>()
|
|
367
|
+
});
|
|
368
|
+
assert_eq!(next, 4.0);
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/// The payload mlx-c was handed is dropped exactly once, however the
|
|
372
|
+
/// call ended: a double drop would be a double free, and none would be
|
|
373
|
+
/// whatever the closure captured, leaked.
|
|
374
|
+
#[test]
|
|
375
|
+
fn the_closure_is_released_once_whatever_happened() {
|
|
376
|
+
type Outcome = fn(&[Array]) -> Result<Vec<Array>>;
|
|
377
|
+
let outcomes: [(&str, Outcome); 3] = [
|
|
378
|
+
("succeeded", |inputs| Ok(vec![square(&inputs[0])?])),
|
|
379
|
+
("failed", |_| Err(Exception::custom("no"))),
|
|
380
|
+
// Not a scalar, so MLX refuses to differentiate it after the
|
|
381
|
+
// closure has run and produced arrays.
|
|
382
|
+
("MLX refused", |_| Ok(vec![Array::from_slice(&[1.0f32, 2.0], &[2])?])),
|
|
383
|
+
];
|
|
384
|
+
for (what, outcome) in outcomes {
|
|
385
|
+
let (count, token) = counter();
|
|
386
|
+
run(|| {
|
|
387
|
+
let f = move |inputs: &[Array]| {
|
|
388
|
+
let _held = &token;
|
|
389
|
+
outcome(inputs)
|
|
390
|
+
};
|
|
391
|
+
let mut vg = value_and_grad_with_argnums(f, &[0]);
|
|
392
|
+
let _ = vg(&[Array::from_f32(3.0)?]);
|
|
393
|
+
let _ = vg(&[Array::from_f32(4.0)?]);
|
|
394
|
+
drop(vg);
|
|
395
|
+
Ok(())
|
|
396
|
+
});
|
|
397
|
+
assert_eq!(count.load(Ordering::SeqCst), 1, "released after it {what}");
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
let (count, token) = counter();
|
|
401
|
+
let _ = std::panic::catch_unwind(AssertUnwindSafe(|| {
|
|
402
|
+
let f = move |_: &[Array]| -> Result<Vec<Array>> {
|
|
403
|
+
let _held = &token;
|
|
404
|
+
panic!("mid-trace")
|
|
405
|
+
};
|
|
406
|
+
let _ = value_and_grad_with_argnums(f, &[0])(&[Array::from_f32(1.0).unwrap()]);
|
|
407
|
+
}));
|
|
408
|
+
assert_eq!(count.load(Ordering::SeqCst), 1, "released after it panicked");
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/// What MLX is still holding after a failed call is what it held
|
|
412
|
+
/// before: nothing the call made, or was handed, is left referenced.
|
|
413
|
+
///
|
|
414
|
+
/// The input is large and evaluated, so a single leaked reference to
|
|
415
|
+
/// it (in the vector handed to MLX, in the closure's inputs, in the
|
|
416
|
+
/// values that never came back) keeps megabytes active.
|
|
417
|
+
#[test]
|
|
418
|
+
fn a_failed_call_leaves_nothing_behind() {
|
|
419
|
+
let active = || {
|
|
420
|
+
let mut bytes = 0usize;
|
|
421
|
+
check(unsafe { sys::mlx_get_active_memory(&mut bytes) }, "active memory").unwrap();
|
|
422
|
+
bytes
|
|
423
|
+
};
|
|
424
|
+
let (before, after) = run(|| {
|
|
425
|
+
let before = active();
|
|
426
|
+
for _ in 0..3 {
|
|
427
|
+
let input = Array::from_slice(&vec![1.0f32; 1 << 20], &[1 << 20])?;
|
|
428
|
+
input.eval()?;
|
|
429
|
+
let not_a_scalar = |inputs: &[Array]| -> Result<Vec<Array>> {
|
|
430
|
+
Ok(vec![square(&inputs[0])?])
|
|
431
|
+
};
|
|
432
|
+
let refused = value_and_grad_with_argnums(not_a_scalar, &[0])(&[input]);
|
|
433
|
+
assert!(refused.is_err(), "a vector has no gradient");
|
|
434
|
+
}
|
|
435
|
+
Ok((before, active()))
|
|
436
|
+
});
|
|
437
|
+
assert_eq!(after, before, "{} bytes are still held", after.saturating_sub(before));
|
|
438
|
+
}
|
|
439
|
+
}
|