1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
//! Graph compilation: [`compile`] + the global [`set_compile_mode`] /
//! [`enable_compile`] / [`disable_compile`] controls.
//!
//! Mirrors `mlx.core.compile` (Python) and `mlx-swift`'s `compile(...)`
//! ([`Transforms+Compile.swift`](https://github.com/ml-explore/mlx-swift/blob/main/Source/MLX/Transforms%2BCompile.swift)),
//! both thin wrappers over the mlx-c `mlx_compile` entry point.
//!
//! ## What compilation does
//!
//! [`compile`] takes a function over arrays (`Fn(&[Array]) ->
//! Result<Vec<Array>>`) and returns a [`Compiled`] callable that, on first
//! application, *traces* the function once to build its operation graph,
//! then *caches* that graph (simplifying/fusing per the active [`CompileMode`]) in the mlx backend keyed by the
//! function's identity. Subsequent applications with matching input shapes
//! and dtypes reuse the cached graph rather than re-tracing — the win that
//! makes a per-token decode forward stop re-tracing every step (see the
//! crate-level note on the per-leaf compiled functions the mlx-lm / mlx-vlm
//! references apply to RoPE, norms, and the sampler stages).
//!
//! This trace/cache/fusion behavior — and the cache-hit elision of `f`'s
//! Rust-level side effects — applies to a [`Compiled`] built while compilation
//! is **enabled** (the default). If [`compile`] is called while compilation is
//! disabled ([`CompileMode::Disabled`] / [`disable_compile`]), mlx returns `f`
//! unchanged at construction: the [`Compiled`] calls `f` directly on every
//! application (no trace, cache, or fusion; side effects run every call), and a
//! later [`enable_compile`] does not convert it — the choice is fixed when the
//! wrapper is built.
//!
//! `shapeless`: when `true`, the cached graph is *not* re-traced when an
//! input's shape changes (only a change in the number of dimensions or in a
//! dtype forces a re-trace). Not every function can be compiled shapeless —
//! one that branches on a concrete dimension will surface the backend's
//! error from [`Compiled::call`]. Defaults to `false` (mlx parity).
//!
//! ## Ownership over FFI
//!
//! `mlx_compile(res, fun, shapeless)` calls `mlx_closure_set_(*res,
//! compile(get_(fun), shapeless))` (vendored `mlx-c/mlx/c/compile.cpp`):
//! `*res` enters as the `{ctx: NULL}` sentinel from `mlx_closure_new()`, and
//! `mlx_closure_set_` on a NULL ctx *allocates* a fresh `std::function` and
//! writes the pointer into `res->ctx` (vendored `private/closure.h`
//! `mlx_closure_set_`, line 30). [`Compiled`] therefore wraps the populated
//! handle (the local slot *after* the `mlx_compile` call) and frees it once
//! on [`Drop`] — the same "guard the post-set handle, not the NULL sentinel"
//! discipline as [`crate::transforms::autograd`]'s `build_value_and_grad`.
//!
//! The *source* closure passed to `mlx_compile` is dropped right after the
//! call returns (mirroring mlx-swift's `defer { mlx_closure_free(innerClosure)
//! }`). This is sound because the source closure's captured payload — the
//! boxed Rust callable — is held by a `std::shared_ptr<void>` *captured by
//! value* in the `std::function` lambda (vendored `closure.cpp`
//! `mlx_closure_new_func_payload`, line 76: `[fun, cpp_payload]`).
//! `mlx::core::compile` copies that `std::function` into the compiled graph's
//! own capture, incrementing the `shared_ptr` refcount, so the compiled
//! closure independently keeps the Rust callable alive for its whole lifetime
//! (it can re-invoke the trampoline on a shape/dtype-driven re-trace). The
//! boxed callable is reclaimed by `destroy_payload` only when the *last*
//! `shared_ptr` drops — i.e. after both the source closure and the
//! [`Compiled`] handle are freed.
//!
//! ## Concurrency / thread-safety
//!
//! MLX records "am I tracing?" in a single **process-global** stack
//! (`detail::InTracing::trace_stack_`) that is *not* `thread_local`. That one
//! stack is shared across **all** of mlx's transforms — [`compile`] as well as
//! [`grad`](crate::transforms::grad) /
//! [`vjp`](crate::transforms::vjp) / [`jvp`](crate::transforms::jvp) /
//! [`value_and_grad`](crate::transforms::value_and_grad) / `vmap` (each of which
//! constructs an `InTracing` guard) — and it is also *read* by ordinary ops
//! (mlx's `in_tracing()` / `in_dynamic_tracing()` checks).
//!
//! This crate serializes **compile-vs-compile** tracing internally: a
//! [`Compiled::call`] first-trace (or a shape/dtype re-trace) holds a private
//! process-wide lock, so two independent compiled closures cannot push/pop that
//! shared stack at the same time. That lock is *compile-private*, however — it
//! is not taken by `grad`/`vjp`/`jvp`/`value_and_grad`/`vmap` or by ordinary
//! ops. Tracing operations therefore should **not** be run concurrently across
//! threads with *other* tracing transforms or with ops, because the underlying
//! mlx tracing stack is process-global rather than thread-local: a
//! [`Compiled::call`] first-trace on one thread can still race a `grad` (or an
//! op) on another thread.
//!
//! This matches the crate's existing contract for the autograd transforms,
//! which are likewise *not* runtime-serialized against one another (see the
//! [`transforms`](crate::transforms) "Threading" note); tracing-sensitive tests
//! run in isolated processes. Fully closing the residual would require either a
//! global lock around every tracing-touching op (abandoning the thin-forward
//! design) or an upstream change making mlx's `trace_stack_` thread-local. The
//! upstream tracking issue is ml-explore/mlx#3620.
use ;
use crate::;
/// Process-wide lock serializing every entry into the mlx backend's *tracing*
/// path from this module.
///
/// MLX records "am I tracing?" in `detail::InTracing::trace_stack_`, a
/// **function-local `static std::vector`** — i.e. *process-global*, NOT
/// `thread_local` (see `mlxrs-sys/vendor/mlx/mlx/transforms.cpp::trace_stack()`
/// and the `InTracing` ctor in `transforms_impl.h`, which `push_back`s onto
/// it). Compilation pushes a frame onto that vector for the duration of a
/// trace. `mlx::core::detail::compile_trace` constructs an `InTracing` guard
/// (`compile.cpp:404`), and that trace runs lazily *inside the compiled
/// closure* on a cache-miss or shape/dtype re-trace (`compile.cpp:1126-1133`),
/// which is exactly what [`Compiled::call`] drives through
/// `mlx_closure_apply`.
///
/// Because safe Rust can build independent [`Compiled`] values and [`Array`]s
/// on several threads (`!Send` only blocks *moving one* closure across
/// threads, never two *independent* closures tracing at once), two first-calls
/// or re-traces could otherwise `push_back`/`pop_back` that one C++ vector
/// concurrently — a data race / UB. A safe function must never permit UB, so we
/// serialize the trace path here. `Mutex::new` is const (MSRV ≫ 1.63), so a
/// plain `static` suffices — the same idiom as `device.rs`'s default-device
/// lock.
///
/// **Scope of this lock — what it does and does NOT cover.** This lock closes
/// the *compile-vs-compile* race only: it is held across every entry into the
/// tracing path *from this module*, so two compiled-closure traces (a first
/// call or a shape/dtype re-trace) can never touch `trace_stack_` at once. It
/// does **not** cover the same process-global stack being touched by mlx's
/// *other* transforms (`grad`/`vjp`/`jvp`/`value_and_grad`/`vmap`, which build
/// their own `InTracing` guards) or *read* by ordinary ops (`in_tracing()` /
/// `in_dynamic_tracing()`) — none of those take this compile-private lock. A
/// compile first-trace on one thread can therefore still race a concurrent
/// `grad` or op on another thread; that residual is a process-global mlx-core
/// limitation (tracked upstream at ml-explore/mlx#3620), consistent with the
/// crate's existing contract that the autograd transforms are likewise not
/// runtime-serialized (see the module-level "Concurrency / thread-safety"
/// note). Do not over-trust this guard as a general cross-transform tracing
/// lock — it is scoped to this module's tracing entries by design.
static TRACE_LOCK: = new;
thread_local!
/// RAII guard that serializes the mlx tracing path process-wide while tolerating
/// same-thread re-entrancy (nested compile).
///
/// At the outermost entry on a thread it holds [`TRACE_LOCK`]; nested entries
/// hold nothing but keep the depth raised. The lock is released on [`Drop`] —
/// including on unwind — so a closure that returns `Err` or panics (the
/// trampoline catches panics, converting them to a non-zero rc; see
/// `transforms::closure`) can never leave the lock held. Poison is recovered
/// via `into_inner()` so a panic that *did* poison the lock never wedges the
/// process permanently (matching `device.rs` / the compile-mode test guard).
/// Compilation mode for the global [`set_compile_mode`] control, mirroring
/// mlx-c's `mlx_compile_mode` enum (`mlx/c/compile.h`).
///
/// Controls which graph transformations the backend applies when compiling.
/// The default is [`CompileMode::Enabled`] (full simplification + fusion).
///
/// The variants act at two different times. [`Disabled`](Self::Disabled) is a
/// **construction-time** skip — it only governs whether [`compile`] builds a
/// compiled wrapper at all. The fusion levels [`NoSimplify`](Self::NoSimplify) /
/// [`NoFuse`](Self::NoFuse) / [`Enabled`](Self::Enabled) are instead sampled by
/// mlx when it fills a compiled closure's cache entry on the first call or a
/// shape/dtype re-trace.
/// Process-global mirror of whether mlx will *skip* compilation — read at
/// construction by [`build_compiled`] to record if a [`Compiled`] is cache-backed
/// (a real compiled graph) or a direct passthrough to `f`.
///
/// mlx decides this once, when [`compile`] runs, via its `skip_compile()`
/// (`mlxrs-sys/vendor/mlx/mlx/compile.cpp:1093-1095`):
/// `compile_mode() == disabled || !compile_available_for_device(default_device())`.
/// The device half is always `true` in mlxrs's build — the CPU backend's
/// `compile_available_for_device` returns `true` unconditionally
/// (`backend/cpu/compiled.cpp:52`); only the no-CPU GPU-only backend can return
/// `false` (`backend/no_cpu/compiled.cpp:12`), a configuration mlxrs does not
/// build. So in mlxrs `skip_compile()` reduces to the mode being `Disabled`.
///
/// mlx-c exposes **no getter** for the mode, so we mirror it. The seed matches
/// how mlx itself seeds `compile_mode()` (compile.cpp:217-226: `Disabled` iff the
/// `MLX_DISABLE_COMPILE` env var is set at first read, else `Enabled`), and the
/// only functions that can subsequently change mlx's mode — [`enable_compile`] /
/// [`disable_compile`] / [`set_compile_mode`] — update this flag in lockstep on
/// success. (A consumer reaching past the safe API to flip the mode via raw
/// `mlxrs-sys` FFI would desync the mirror; that unsafe path is out of contract.)
///
/// `Relaxed`: the only shared datum is this flag's own value (the derived
/// cache-backed bool is stored per-[`Compiled`]), so no cross-flag happens-before
/// is needed; a mode change that must affect a later compile on another thread
/// has to be externally ordered before it regardless — exactly mlx's own
/// process-global-mode contract.
static COMPILE_DISABLED: =
new;
/// Serializes a compile-mode change against a [`compile`] construction so the
/// [`COMPILE_DISABLED`] mirror and MLX's own mode stay an **atomic pair**.
///
/// Without this, [`build_compiled`] samples the mirror and then calls
/// `mlx_compile` (which makes the real passthrough-vs-compile decision *inside*,
/// via its `skip_compile`) as two separate steps; a concurrent
/// [`disable_compile`] / [`enable_compile`] / [`set_compile_mode`] landing
/// between them could change MLX's mode after our sample, so the recorded
/// `cache_backed` would disagree with what `mlx_compile` actually did — either
/// over-poisoning a passthrough or, worse, failing to poison a real cache (the
/// stale-empty-success hazard the flag exists to prevent). The mutators hold
/// this lock across their MLX update + mirror store, and [`build_compiled`]
/// holds it across the mirror load + `mlx_compile`, so MLX's mode cannot change
/// between our sample and the compile that consults it.
///
/// Lock order is total and deadlock-free: [`build_compiled`] takes
/// [`TRACE_LOCK`] (via [`TraceGuard`]) *then* `MODE_LOCK`. [`TRACE_LOCK`] must be
/// the OUTER lock because a traced closure body may nest-call [`compile`] while
/// [`Compiled::call`] already holds the *reentrant* [`TRACE_LOCK`], so a nested
/// construction re-takes `TRACE_LOCK` (reentrantly) before it takes `MODE_LOCK`;
/// making `MODE_LOCK` the outer lock would invert that order against this nested
/// path and risk a deadlock. The mutators take only `MODE_LOCK`; a cache-backed
/// [`Compiled::call`] takes only [`TRACE_LOCK`] (a passthrough call takes neither
/// lock — it never traces). No thread ever holds `MODE_LOCK`
/// while waiting on [`TRACE_LOCK`], so there is no cycle, and `MODE_LOCK` is
/// never re-entered on one thread (a construction takes it exactly once;
/// `mlx_compile` builds the caching lambda without running — hence without
/// re-entering — the closure), so a plain non-reentrant `Mutex` is sound. (A
/// consumer flipping the mode through raw `mlxrs-sys` FFI, bypassing the safe
/// mutators, would still desync — that unsafe path is out of contract, as for
/// [`COMPILE_DISABLED`].)
static MODE_LOCK: = new;
/// Globally enable graph compilation (mlx-c `mlx_enable_compile`; mlx-swift's
/// `compile(enable: true)`). Compilation is enabled by default; call this to
/// re-enable after [`disable_compile`].
///
/// This is a process-global mlx backend toggle. The **disabled-vs-compiled**
/// decision is made at construction time: [`compile`] calls `mlx_compile` once
/// when it builds a [`Compiled`], so a [`Compiled`] built while compilation is
/// disabled runs `f` uncompiled (no graph caching or fusion) on every call, and
/// a later `enable`/`disable` does **not** flip an existing [`Compiled`] between
/// compiled and uncompiled. The specific simplify/fuse *mode* ([`CompileMode`]),
/// in contrast, is sampled by mlx when it fills the cache entry on the first
/// call or a shape/dtype re-trace — so changing the mode (see
/// [`set_compile_mode`]) before a compiled function's first call can still
/// affect that trace's fusion (the first-trace-sampled modes are
/// [`NoSimplify`](CompileMode::NoSimplify), [`NoFuse`](CompileMode::NoFuse), and
/// [`Enabled`](CompileMode::Enabled) — *not* [`Disabled`](CompileMode::Disabled),
/// which is the construction-time skip above). It is a performance switch,
/// never a correctness one.
/// Globally disable graph compilation (mlx-c `mlx_disable_compile`;
/// mlx-swift's `compile(enable: false)`). See [`enable_compile`] for the
/// construction-time semantics — a [`Compiled`] built while disabled runs `f`
/// uncompiled on every call (correct, just un-fused); [`Compiled`]s that already
/// exist are unaffected.
/// Set the global compilation mode (mlx-c `mlx_set_compile_mode`).
///
/// Selects which graph transformations the backend applies — see
/// [`CompileMode`]. The default is [`CompileMode::Enabled`]. The fusion levels
/// ([`NoSimplify`](CompileMode::NoSimplify) / [`NoFuse`](CompileMode::NoFuse) /
/// [`Enabled`](CompileMode::Enabled)) are sampled by mlx when it fills a
/// [`Compiled`]'s cache entry on the first call or a shape/dtype re-trace — not
/// when [`compile`] builds the wrapper — so changing one before a compiled
/// function's first call still affects that trace, while one whose graph is
/// already cached is unaffected. [`CompileMode::Disabled`] is different: like
/// [`disable_compile`] it acts only at construction and does not un-compile an
/// existing [`Compiled`].
/// A compiled function over arrays — the result of [`compile`].
///
/// Owns one reference to the backend-compiled `mlx_closure`. [`Compiled::call`]
/// applies the cached graph to a fresh input slice; the first call traces +
/// caches, later calls with matching shapes/dtypes reuse the cached graph.
/// (This holds for a `Compiled` built while compilation was enabled; one built
/// while [`CompileMode::Disabled`] is active wraps `f` directly — every call
/// runs `f` with no caching or fusion, and a later [`enable_compile`] does not
/// change that.)
///
/// `Compiled` is intentionally `!Send` + `!Sync`: the captured Rust callable
/// may reference [`Array`] handles (themselves `!Send`), and the backend's
/// evaluator is single-threaded (the same rationale as
/// [`crate::transforms::closure::Closure`]).
/// Compile `f` into a cached [`Compiled`] graph — its simplification and
/// operation fusion governed by the active [`CompileMode`] (mlx-c `mlx_compile`;
/// `mlx.core.compile`; mlx-swift's `compile(...)`).
///
/// `f`'s contract is the same as every other transform's:
/// `Fn(&[Array]) -> Result<Vec<Array>>`, required `+ 'static` so the backend
/// can re-invoke it on a shape/dtype-driven re-trace. The returned
/// [`Compiled`] is callable repeatedly via [`Compiled::call`].
///
/// `shapeless` (mlx parity, default `false` at the call site): when `true`,
/// the cached graph is not re-traced on an input *shape* change — only a
/// change in the number of dimensions or a dtype forces a re-trace. Functions
/// that branch on a concrete dimension cannot be compiled shapeless and will
/// surface the backend's error from [`Compiled::call`].
///
/// For a **pure** array function the returned [`Compiled`] produces results
/// identical to calling `f` directly — compilation is a performance
/// optimization, never a numeric change. Note, however, that `f`'s *Rust-level*
/// side effects (a captured `Cell`/`RefCell`, an RNG, a counter, logging, or a
/// read of external mutable state) execute only while the graph is being traced
/// — the first call plus any shape/dtype-driven re-trace — and are **not** re-run
/// on a cache hit. Compile pure, traceable array functions; an impure `f` will
/// diverge from a direct call.
///
/// All of the above — the cached graph and the cache-hit elision of `f`'s
/// Rust-level side effects — assumes compilation is **enabled** (the default)
/// when `compile` runs. Called while disabled ([`CompileMode::Disabled`] /
/// [`disable_compile`]), the returned [`Compiled`] is a direct passthrough to
/// `f` (no caching, fusion, or side-effect elision), permanently — a later
/// [`enable_compile`] does not convert it.
///
/// ```no_run
/// # fn run() -> mlxrs::Result<()> {
/// use mlxrs::{Array, transforms::compile};
/// // f(x) = x*x + x
/// let compiled = compile(
/// |xs| {
/// let sq = mlxrs::ops::arithmetic::square(&xs[0])?;
/// Ok(vec![mlxrs::ops::arithmetic::add(&sq, &xs[0])?])
/// },
/// false,
/// )?;
/// let x = Array::from_slice(&[1.0f32, 2.0, 3.0], &[3])?;
/// let mut out = compiled.call(&[x])?;
/// assert_eq!(out[0].to_vec::<f32>()?, vec![2.0, 6.0, 12.0]);
/// # Ok(()) }
/// ```
/// Compile `f` and adapt it to the ergonomic `Fn(&[Array]) ->
/// Result<Vec<Array>>` shape (matching [`crate::transforms::value_and_grad`]'s
/// returned-closure surface).
///
/// Convenience over [`compile`] + [`Compiled::call`]: the returned closure owns
/// the [`Compiled`] wrapper and forwards each call to it, inheriting
/// [`compile`]'s construction-time mode semantics — including the
/// [`CompileMode::Disabled`] case, where the wrapper is a direct passthrough to
/// `f` rather than a cached compiled graph.
///
/// ```no_run
/// # fn run() -> mlxrs::Result<()> {
/// use mlxrs::{Array, transforms::compile_fn};
/// let g = compile_fn(|xs| Ok(vec![mlxrs::ops::arithmetic::square(&xs[0])?]), false)?;
/// let x = Array::from_slice(&[2.0f32, 3.0], &[2])?;
/// let mut out = g(&[x])?;
/// assert_eq!(out[0].to_vec::<f32>()?, vec![4.0, 9.0]);
/// # Ok(()) }
/// ```
// ─────────────────────────── internal helper ───────────────────────────
/// Build the compiled `mlx_closure` from a source [`Closure`] + `shapeless`.
///
/// `mlx_closure_new()` returns the `{ctx: NULL}` sentinel; `mlx_compile`
/// internally calls `mlx_closure_set_(*res, …)` which (on NULL ctx) ALLOCATES
/// a fresh `std::function` and writes the pointer into `res->ctx`. So — exactly
/// like `build_value_and_grad` — the RAII-owning [`Compiled`] must wrap the
/// LOCAL `res` slot *after* the populating call, not the NULL sentinel from
/// `_new()` (which would leak the populated handle and free nothing).