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
//! `Array` core: RAII handle around `mlxrs_sys::mlx_array`.
//!
//! Design rationale: Drop must not touch TLS; the only duplication is the
//! fallible refcount-sharing [`Array::try_clone`]; M1 is single-thread only.
use assert_not_impl_any;
use crate;
/// MLX N-dimensional array — RAII handle around an mlx-c `mlx_array`.
// `pub(super)` (= `pub(crate)` from this location): the raw handle stays
// crate-visible so the FFI wrappers in crate-sibling modules can construct
// and consume `Array`s without going through accessors. Tightening further
// is a separate refactor (introduce explicit `Array::from_raw` /
// `into_raw` / handle-borrow accessors crate-wide); not in scope here.
mlx_array);
// Compile-time guarantees colocated with the type definition.
//
// `Array` is intentionally `!Send` and `!Sync` in M1.
//
// `Array` also intentionally does **not** implement `Clone`. The only
// supported duplication is `Array::try_clone() -> Result<Self>`: a
// refcount-sharing handle dup (a fresh `mlx::core::array` over the same
// underlying `array_desc`, no data copy), fallible because the mlx-c handle
// alloc/`set` can fail. An infallible `Clone` would have to panic on that
// failure, so it is not provided.
//
// `!Send`/`!Sync` is required by the underlying mlx-c array/backend, NOT to
// keep any `Clone` cheap. `array_desc_` is
// `std::shared_ptr<array_desc>` (atomic refcount) but `set_status const →
// array_desc_->status = s` is a non-atomic mutation through `const` — so a
// shared `&Array` across threads (`Sync`) would race on `array_desc->status`.
// The same non-atomic lazy/eval state also makes the handle unsound to move
// across threads alongside another handle to the same `array_desc`: a
// `try_clone`d pair on two threads would each call `eval`/`to_vec`/`item`
// (`&mut self`, so `!Sync` doesn't catch it) and race that `status` write.
// mlx's `eval` is itself not concurrency-safe. There is no shared-array
// wrapper: MLX's C++/Python/Swift APIs deliberately don't share arrays across
// threads. To cross threads, extract owned data via `to_vec`/`item`
// (`Send`). The `assert_not_impl_any!` below is the actual enforced contract.
assert_not_impl_any!;