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
// Architecture and the f64 dot/reduction kernel adapted from the `dia`
// project (github — MIT/Apache-2.0), src/ops/.
//! Hand-written `core::arch` SIMD kernels for the host-CPU numeric
//! loops mlxrs runs *itself* (not through MLX FFI).
//!
//! The overwhelming majority of mlxrs tensor math is delegated to MLX
//! and runs on MLX's own SIMD/Metal kernels — those are out of scope
//! here. This module covers the small set of Rust-side `&[f64]` /
//! `&[f32]` loops that run on the CPU regardless (audio DSP,
//! preprocessing), where a `core::arch` kernel is a genuine win.
//!
//! ## Layered architecture
//!
//! Mirrors the `dia` project's `src/ops/` four-layer shape:
//!
//! - [`scalar`](crate::simd::scalar) — bit-exact scalar reference
//! kernels. **Always compiled**, independent of `target_arch`. The
//! math contract is anchored here; it is also the differential-test
//! oracle and the fallback path.
//! - `arch` — architecture-specific SIMD backends, gated behind
//! `#[cfg(target_arch = "aarch64")]` (so not linkable from these
//! always-rendered docs). `arch::neon` holds
//! `#[target_feature(enable = "neon")] unsafe fn` kernels.
//! - `dispatch` — runtime-detection routers. Each public dispatcher
//! asserts its slice-length preconditions **unconditionally**, then
//! picks NEON (if available) or the scalar fallback.
//! - this module (`simd`) — module doc + the public dispatcher
//! re-exports + the [`neon_available`](crate::simd::neon_available)
//! detector.
//!
//! ## Public surface
//!
//! - [`dot`](crate::simd::dot) — `Σ a[i] * b[i]`, f64.
//! - [`sum_of_squares`](crate::simd::sum_of_squares) — `Σ v[i]²`,
//! f64. Used by [`crate::audio`]'s `integrated_loudness` for the
//! per-block K-weighted mean-square.
//!
//! ## Always on — no cargo feature
//!
//! SIMD is **unconditional**: there is no `simd` cargo feature. Whether
//! the NEON backend runs is gated purely on `#[cfg(target_arch =
//! "aarch64")]` plus runtime CPU detection
//! ([`neon_available`](crate::simd::neon_available)); on every other
//! target the dispatchers route to [`scalar`](crate::simd::scalar)
//! automatically. The [`scalar`](crate::simd::scalar) and `dispatch`
//! layers therefore compile on **all** targets — only the `arch`
//! module is `aarch64`-gated (the
//! [`neon_available`](crate::simd::neon_available) detector is a
//! `const false` stub elsewhere).
//! This matches the `dia` reference (no simd feature). A pure-scalar
//! build for bisecting a numeric regression — even on a NEON-capable
//! host — is available via the `--cfg mlxrs_force_scalar` build escape
//! (see [`neon_available`](crate::simd::neon_available)).
//!
//! ## Cross-path determinism
//!
//! On `aarch64`, [`scalar`](crate::simd::scalar) and the
//! `arch::neon` kernels produce **bit-identical** results. This is
//! deliberate:
//!
//! 1. both use `f64::mul_add` for each per-element FMA — one IEEE 754
//! rounding, identical to `vfmaq_f64`;
//! 2. [`scalar`](crate::simd::scalar)'s reduction tree mirrors NEON's
//! — 4 partial sums over modulo-4 indices, combined
//! `((s00 + s10) + (s01 + s11))`.
//!
//! Verified by the `differential_tests` module below
//! (`assert_eq!` on `f64::to_bits()`).
//!
//! ## Adding a new kernel — the per-kernel triple
//!
//! Every new kernel ships as **three pieces** that follow the in-tree
//! [`dot`](crate::simd::dot) worked example exactly:
//!
//! 1. **Scalar reference** — `pub fn foo_scalar(x: &[T]) -> R` under
//! [`scalar`](crate::simd::scalar). Always compiled, independent of
//! `target_arch`. Anchors the math contract, is the
//! differential-test oracle, and is the fallback path. See
//! [`scalar::dot`](crate::simd::scalar::dot) for the worked
//! example.
//! 2. **NEON kernel** — `#[target_feature(enable = "neon")] unsafe fn
//! foo(x: &[T]) -> R` under `arch::neon` (the whole module is
//! `#[cfg(target_arch = "aarch64")]`-gated). See `arch::neon::dot`
//! for the worked example — note the `pub(crate)` visibility and
//! the `# Safety` doc-comment that names every caller obligation
//! (NEON availability + every input precondition).
//! 3. **Dispatcher** — `pub fn foo(x: &[T]) -> R` under `dispatch::`,
//! re-exported from this module. Asserts its slice-length
//! preconditions **unconditionally** (release-too — the NEON
//! kernel's `debug_assert!` is a no-op in release and would
//! OOB-read), then
//! `if neon_available() { unsafe { neon::foo(x) } } else { scalar::foo(x) }`.
//! See the re-exported [`dot`](crate::simd::dot) for the worked
//! example.
//!
//! ## Picking a differential-test class — `Exact` vs `Tolerance`
//!
//! Every new kernel also ships a scalar-vs-dispatcher differential
//! test using the helpers in [`diff`](crate::simd::diff):
//!
//! - **`Exact`** — call
//! [`diff::assert_eq_over_lane_sweep`](crate::simd::diff::assert_eq_over_lane_sweep).
//! Use for data-movement / lossless-widening kernels (integer-widen
//! arms) — the SIMD output **must be bit-identical**
//! to scalar. For fp outputs that are deliberately bit-identical
//! (the in-tree `dot` is one — matched reduction tree), the
//! `differential_tests` module below compares on `f64::to_bits()`
//! instead.
//! - **`Tolerance { abs, rel }` — scalar output** — call
//! [`diff::assert_close_over_lane_sweep`](crate::simd::diff::assert_close_over_lane_sweep).
//! Use for fp-reduction / FMA-rounding kernels that fold the input
//! to a single `f64` (loudness sum-of-squares; any future fp
//! reduction without a matched scalar reduction tree).
//! - **`Tolerance { abs, rel }` — vector output** — call
//! [`diff::assert_close_slice_over_lane_sweep`](crate::simd::diff::assert_close_slice_over_lane_sweep).
//! Use for fp kernels that return a `Vec<f64>` (`rotate_buf`
//! permutation, `mel_filter_bank` triangle construction, window
//! generation — the vector-producing fp candidates
//! documented under `simd::audio` / `simd::vlm`). Asserts
//! dispatcher and scalar outputs have the same length **and** every
//! element pair satisfies the same `abs.max(rel * |s|)` tolerance
//! as the scalar twin.
//!
//! All three helpers share the same length sweep
//! ([`diff::lane_sweep_lengths`](crate::simd::diff::lane_sweep_lengths)
//! — 9 lengths covering every boundary class: empty / singleton /
//! single-block-just-below / single-block-clean / single-block-plus-tail /
//! post-body large-tail / multi-block-clean ×2 / multi-block-clean ×3 /
//! multi-block-plus-tail), so coverage is uniform across `Exact` and
//! both `Tolerance` flavours.
//!
//! See the [`diff`](crate::simd::diff) module doc for the full class
//! catalog and the length-sweep rationale.
// `simd::audio` is **not** `aarch64`-gated (same rationale as `simd::vlm`
// below): the scalar reference inside each kernel triple must compile on
// every target so the dispatcher's scalar-fallback branch is a real,
// linkable function (the scalar fallback compiles on all targets,
// only the `arch` module is
// `aarch64`-gated). The NEON kernels inside each kernel triple are
// individually `#[cfg(target_arch = "aarch64")]`-gated at the
// function level. The module is `audio`-feature-gated so the
// `--no-default-features` / per-feature CI builds don't compile a
// dead-code dispatcher (the only call sites are
// [`crate::audio::*`], itself behind the same feature).
//
// `pub` (rather than `pub(crate)`) so the in-tree
// `benches/simd_*.rs` micro-benchmarks — separate binaries that
// only see the public API — can drive the dispatchers and scalar
// references directly. Per-kernel items inside are individually
// `pub`/`pub(crate)` (only the dispatcher + the scalar reference
// are exposed; the `unsafe` NEON kernel stays `pub(crate)`).
// `simd::vlm` is **not** `aarch64`-gated: the scalar reference inside
// each kernel triple (e.g. `pad_canvas_fill_scalar`) must compile on
// every target so the dispatcher's scalar-fallback branch is a real,
// linkable function (the scalar fallback compiles on all targets,
// only the `arch` module is
// `aarch64`-gated). The NEON kernels inside each kernel triple are
// individually `#[cfg(target_arch = "aarch64")]`-gated at the
// function level. The module is `vlm`-feature-gated so the
// `--no-default-features` / per-feature CI builds don't compile a
// dead-code dispatcher (the only call site is
// [`crate::vlm::image::pad_to_square`], itself behind the same
// feature).
//
// `pub` (rather than `pub(crate)`) so the in-tree
// `benches/simd_pad_canvas_fill.rs` micro-benchmark — a separate
// binary that only sees the public API — can drive the dispatcher
// and scalar reference directly. Per-kernel items inside are individually
// `pub`/`pub(crate)` (only the dispatcher + the scalar reference
// are exposed; the `unsafe` NEON kernel stays `pub(crate)`).
pub use ;
// ─── runtime CPU-feature detection ───────────────────────────────────
//
// `--cfg mlxrs_force_scalar` overrides detection so the scalar path
// can be exercised even on a NEON-capable host — set it via
// `RUSTFLAGS="--cfg mlxrs_force_scalar"`.
/// Whether the NEON SIMD backend is usable on the executing CPU.
///
/// `true` when NEON is reported by the CPU **and** `--cfg
/// mlxrs_force_scalar` is not set. NEON is part of the AArch64
/// baseline, so on a normal `aarch64` host this is effectively always
/// `true`; the explicit check keeps the scalar fallback a real,
/// reachable branch and honours the force-scalar escape.
///
/// On every non-`aarch64` target there is no NEON backend to gate, so
/// this is a `const false` stub: every dispatcher then routes to
/// [`scalar`]. The stub keeps the symbol present on all targets so
/// intra-doc links resolve in a non-`aarch64` rustdoc build.
/// Whether the NEON SIMD backend is usable on the executing CPU.
///
/// `true` when NEON is reported by the CPU **and** `--cfg
/// mlxrs_force_scalar` is not set. NEON is part of the AArch64
/// baseline, so on a normal `aarch64` host this is effectively always
/// `true`; the explicit check keeps the scalar fallback a real,
/// reachable branch and honours the force-scalar escape.
///
/// On every non-`aarch64` target there is no NEON backend to gate, so
/// this is a `const false` stub: every dispatcher then routes to
/// [`scalar`]. The stub keeps the symbol present on all targets so
/// intra-doc links resolve in a non-`aarch64` rustdoc build.
/// Whether the NEON SIMD backend is usable on the executing CPU.
///
/// Canonical name matching the [`std::arch::is_aarch64_feature_detected`]
/// idiom — wraps `is_aarch64_feature_detected!("neon")` on `aarch64`
/// and is a `const false` stub on every other target. New per-kernel
/// dispatchers (the follow-ups landing under `simd::audio` /
/// `simd::vlm`) call this directly so the runtime-detection branch
/// has a uniform shape across the crate.
///
/// Functionally identical to [`neon_available`] (which the in-tree
/// [`dot`] dispatcher uses); the duplicate name exists so callers can
/// pick the idiom that reads best at the call site
/// (`if is_neon_available()` mirrors `is_aarch64_feature_detected!`;
/// `if neon_available()` reads naturally as a noun-style query). Both
/// honour the `--cfg mlxrs_force_scalar` build escape.