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
//! Basic linalg ops: addmm (trinary+scalar template), matmul, inner, outer,
//! plus the gathered/batched matmul `gather_mm` (the mixture-of-experts primitive).
//!
//! The matrix-structure ops (#259) live alongside these:
//! `tensordot` (int-axis + axes-lists forms), `diagonal`, `trace`, `tril`, `triu`.
use crate::;
/// Reject an axis-list length that would overflow the signed `int i` loop the
/// core `tensordot` runs over `axes_a.size()` (mlx `ops.cpp` ~5398). The count
/// is a direct FFI argument, so per the #259 issue-266 decision (option A) it is
/// capped binding-side. Mirrors `ops/shape.rs`'s `check_count` (the shared
/// extraction is tracked in the #259 duplication cleanup); pulled into a helper
/// so the cap is unit-testable at the boundary without allocating a multi-GB
/// slice.
/// Reject `offset == i32::MIN` for `diagonal`/`trace`, whose core computes
/// `std::max(-offset, 0)` (mlx `ops.cpp` ~5973): negating `i32::MIN` is
/// signed-overflow UB, and `offset` is the wrapper's own direct scalar argument
/// (reachable on any normal 2-D-or-higher input), so it is rejected binding-side
/// (#259 issue-266 decision A). Every other offset only feeds bounds-checked
/// slice math C-side.
/// Reject `k` values that would drive the `arange(-k, m - k)` the core `tri`
/// builds for `tril`/`triu` (mlx `ops.cpp` ~372, where `m` is the last matrix
/// dimension of `x`) into signed-`int` overflow UB: the start `-k` overflows at
/// `i32::MIN`, and the stop `m - k` overflows `i32` for sufficiently negative
/// `k`. `k` is the wrapper's own direct scalar argument (reachable on any normal
/// 2-D-or-higher input), so per the #259 issue-266 decision (option A) it is guarded
/// binding-side. MLX validates `ndim >= 2` before this arithmetic, so when `x`
/// is < 2-D the guard is skipped and MLX emits the dimension error; the residual
/// shape-product overflows inside `arange`/`broadcast` remain mlx-core-internal
/// (upstream ml-explore/mlx#3601).
/// `alpha * (a @ b) + beta * c` — fused matmul + scaled add.
///
/// CANONICAL TRINARY+SCALAR TEMPLATE — pattern: 3 array inputs + 2 primitive
/// scalar inputs.
///
/// See [mlx docs](https://ml-explore.github.io/mlx/build/html/python/_autosummary/mlx.core.addmm.html).
/// Matrix multiplication: `a @ b`. Generalizes to batched matmul (last two
/// dims of each input are the matmul dims; leading dims broadcast).
///
/// See [mlx docs](https://ml-explore.github.io/mlx/build/html/python/_autosummary/mlx.core.matmul.html).
/// Ordinary inner product of two 1-D arrays. For higher-rank inputs, mlx
/// contracts over the last axis of each (matching numpy `inner`).
///
/// See [mlx docs](https://ml-explore.github.io/mlx/build/html/python/_autosummary/mlx.core.inner.html).
/// Outer product of two 1-D arrays. Higher-rank inputs are flattened first
/// (matching numpy `outer`).
///
/// See [mlx docs](https://ml-explore.github.io/mlx/build/html/python/_autosummary/mlx.core.outer.html).
/// Tensor contraction over the last `axis` dimensions of `a` and the first
/// `axis` dimensions of `b` (the integer-axis form).
///
/// Mirrors `mlx.core.tensordot(a, b, axes=axis)` with an integer `axes`
/// argument (python `python/src/ops.cpp`, the `int` branch of the `axes`
/// variant) / `mlx_tensordot_axis`. `axis = 2` is the python/numpy default.
/// For the explicit per-operand axis-list form, see [`tensordot_axes`].
///
/// # Soundness
/// `axis` is a single scalar forwarded straight to the C++ op, which
/// bounds-checks it (`axis < 0` and `axis > min(a.ndim(), b.ndim())` both throw
/// `std::invalid_argument`, surfaced here as [`Error::Backend`]) before any
/// arithmetic on it. There is no direct-argument overflow path, so no guard is
/// added (per the #266 decision A scalar-arg note).
///
/// # Errors
/// Returns an error if `axis` is out of range or the contracted shapes do not
/// match (surfaced from the underlying MLX call).
/// Tensor contraction over explicit, per-operand contraction axes (the
/// axis-list form).
///
/// Mirrors `mlx.core.tensordot(a, b, axes=[axes_a, axes_b])` (python
/// `python/src/ops.cpp`, the `list[list[int]]` branch, which requires exactly
/// two lists) / `mlx_tensordot`. The two axis lists must have equal length;
/// element `axes_a[i]` of `a` is contracted against `axes_b[i]` of `b`.
///
/// # Soundness
/// We pre-check `axes_a.len() == axes_b.len()` and surface a typed
/// [`Error::LengthMismatch`] (the C++ op throws the same mismatch, but a Rust
/// pre-check yields a precise typed error rather than an opaque backend string).
///
/// The axis-list length is itself a direct FFI count argument, and the core
/// `tensordot` loop iterates it with a signed `int i`
/// (`for (int i = 0; i < axes_a.size(); i++)`, mlx `ops.cpp` ~5398), so a slice
/// longer than [`i32::MAX`] drives that index into signed-overflow UB on
/// otherwise-valid inputs. Per the #266 decision (option A) this direct-argument
/// count is capped binding-side via `check_axis_count` (capping one list
/// suffices, the two lengths being already equal), returning a typed
/// [`Error::CapExceeded`].
///
/// The axis *values* (negative / out-of-range entries reaching the C++
/// `x.shape(axes_a.at(i))` indexing and the `cdims1[n + ndim]` normalization),
/// and any overflow inside the contraction-size product `csize *= x.shape(...)`
/// (`ops.cpp` ~5397-5407), are mlx-core-internal and reachable only via
/// malformed axes / degenerate shapes; per the #266 decision (option A) those
/// transitive paths are tracked upstream (ml-explore/mlx#3601) and are
/// intentionally NOT guarded here.
///
/// # Errors
/// Returns [`Error::LengthMismatch`] if the two axis lists differ in length,
/// [`Error::CapExceeded`] if a list is longer than [`i32::MAX`], or an MLX error
/// if the axes/shapes are otherwise invalid.
/// Extract diagonals along the plane spanned by `axis1` and `axis2`.
///
/// Mirrors `mlx.core.diagonal(a, offset, axis1, axis2)` / `mlx_diagonal`.
/// `offset` shifts the diagonal (positive = above the main diagonal). The
/// python defaults are `offset = 0`, `axis1 = 0`, `axis2 = 1`. `axis1`/`axis2`
/// may be negative (counted from the end).
///
/// # Soundness
/// `axis1`/`axis2` are normalized C-side as `axis + ndim` (only when `axis < 0`,
/// so the add cannot overflow) and bounds-checked before use. `offset`, however,
/// reaches `std::max(-offset, 0)` in the core (mlx `ops.cpp` ~5973): negating
/// `i32::MIN` is signed-overflow UB, and `offset` is this wrapper's own direct
/// scalar argument (reachable on any normal 2-D-or-higher input), so it is rejected via
/// `guard_offset` per the #266 decision (option A). The remaining slice math
/// is bounds-checked C-side.
///
/// # Errors
/// Returns [`Error::OutOfRange`] if `offset == i32::MIN`, or an MLX error if
/// `axis1`/`axis2` are out of range or equal.
/// Sum along the diagonals of an array.
///
/// Mirrors `mlx.core.trace(a, offset, axis1, axis2, dtype)` / `mlx_trace`.
/// Equivalent to summing [`diagonal`] along its last axis. The python defaults
/// are `offset = 0`, `axis1 = 0`, `axis2 = 1`, `dtype = None`; when `dtype` is
/// `None` the output dtype is inferred from the input array (matching the
/// python binding's `!dtype.has_value()` branch, which calls the C++
/// `trace(a, offset, axis1, axis2)` overload that defaults the accumulation
/// type to the input's).
///
/// # Soundness
/// `trace` delegates to `diagonal` C-side, so the same `std::max(-offset, 0)`
/// applies (mlx `ops.cpp` ~6050 -> ~5973): `offset == i32::MIN` is rejected via
/// `guard_offset` per the #266 decision (option A). `axis1`/`axis2` are
/// bounds-checked C-side and `dtype` is a plain enum value.
///
/// # Errors
/// Returns [`Error::OutOfRange`] if `offset == i32::MIN`, an MLX error if
/// `axis1`/`axis2` are invalid, or a dtype error if `self.dtype()` fails when
/// `dtype` is `None`.
/// Lower triangle of an array: zeros every entry strictly above the `k`-th
/// diagonal.
///
/// Mirrors `mlx.core.tril(x, k)` / `mlx_tril`. `k = 0` (the python default)
/// keeps the main diagonal and below; `k > 0` keeps additional super-diagonals;
/// `k < 0` drops sub-diagonals. The input must be at least 2-D.
///
/// # Soundness
/// `tril` passes `k` to the internal `tri`, whose `arange(-k, m - k, ...)`
/// (`ops.cpp` ~372, with `m == x.shape(-1)`) negates and subtracts `k`. Although
/// the `arange` runs inside a transitively-called op, the overflowing operand is
/// `k` itself — this wrapper's own direct scalar argument, reachable on any
/// normal 2-D-or-higher input — so per the #266 decision (option A) it is guarded
/// binding-side via `guard_tri_k` (rejecting a `-k` or `m - k` that escapes
/// `i32`). The residual per-shape overflows inside `arange`/`broadcast` stay
/// mlx-core-internal (upstream ml-explore/mlx#3601).
///
/// # Errors
/// Returns [`Error::ArithmeticOverflow`] if `-k` or `m - k` overflows `i32`, or
/// an MLX error if `x` is less than 2-D.
/// Upper triangle of an array: zeros every entry strictly below the `k`-th
/// diagonal.
///
/// Mirrors `mlx.core.triu(x, k)` / `mlx_triu`. `k = 0` (the python default)
/// keeps the main diagonal and above; `k > 0` drops super-diagonals; `k < 0`
/// keeps additional sub-diagonals. The input must be at least 2-D.
///
/// # Soundness
/// `triu` passes `k - 1` to the internal `tri` (`ops.cpp` ~388), so the core
/// computes `arange(-(k - 1), m - (k - 1), ...)`. The `k - 1` subtraction and
/// the inner `-(k - 1)` / `m - (k - 1)` are all on `k`, this wrapper's direct
/// scalar argument (reachable on any normal 2-D-or-higher input), so per the #266
/// decision (option A) they are guarded binding-side: `k - 1` via
/// [`i32::checked_sub`] and the `tri` endpoints via `guard_tri_k`. The
/// residual per-shape overflows stay mlx-core-internal
/// (upstream ml-explore/mlx#3601).
///
/// # Errors
/// Returns [`Error::ArithmeticOverflow`] if `k - 1`, `-(k - 1)`, or
/// `m - (k - 1)` overflows `i32`, or an MLX error if `x` is less than 2-D.
/// Batched/gathered matmul: like [`matmul`] but selects per-batch rows of `a` /
/// `b` via optional `lhs_indices` / `rhs_indices` flat batch indices. The
/// indices contain flat indices along the **batch** dimensions of each input
/// (all but the last two dims); the last two dims of each input are still the
/// matmul dims and contract normally.
///
/// This is the dense primitive behind mixture-of-experts (MoE) `SwitchLinear`:
/// `a` is `[N, 1, K]` per-token input, `b` is `[E, K, M]` per-expert weights,
/// and `rhs_indices` is the `[N]` per-token expert assignment — the result is
/// `[N, 1, M]`, with token `i` matmul'd against expert `rhs_indices[i]`.
///
/// `sorted_indices` promises `rhs_indices` is sorted, enabling a faster
/// kernel (mlx-lm's `SwitchGLU` sets this on the `_gather_sort` path).
///
/// Mirrors python `mx.gather_mm` and swift `gatherMM`. See
/// [mlx docs](https://ml-explore.github.io/mlx/build/html/python/_autosummary/mlx.core.gather_mm.html).