Repository navigation
Expand file tree
/
Copy pathsimd.rs
More file actions
2826 lines (2642 loc) · 126 KB
/
Copy pathsimd.rs
File metadata and controls
2826 lines (2642 loc) · 126 KB
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
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! SIMD polyfill — `crate::simd::F32x16` dispatches via `LazyLock<Tier>`.
//!
//! Same pattern as `backend/native.rs`: detect once, dispatch forever.
//! AVX-512 → AVX2 → Scalar. Consumer writes `crate::simd::F32x16`. Period.
//!
//! When `std::simd` stabilizes: swap this file. Zero consumer changes.
//!
//! The `Tier` above is runtime detection. The SIMD *types* are chosen at
//! compile time, one realization per build, from the target features:
//!
//! * x86_64 `avx512f`: `simd_avx512.rs`.
//! * x86_64 `avx2`, no `avx512f`: `simd_avx2.rs`. This arm is also what a
//! baseline x86-64 build compiles, and `cpu_guard` refuses to start such a
//! build on a CPU without AVX2.
//! * x86_64 `avx`, no `avx2`: `simd_avx.rs` (`.cargo/config-avx.toml`).
//! * x86_64 `sse4.2`, no `avx` (x86-64-v2, `.cargo/config-v2.toml`):
//! `simd_scalar.rs`. The AVX2/AVX-512 types wrap 256/512-bit registers, so
//! this arm uses plain arrays that LLVM compiles to SSE.
//! * aarch64: NEON; wasm32 with `simd128`: `simd_wasm.rs`; any other target:
//! `simd_scalar.rs`. The `nightly-simd` feature replaces all of these with
//! `core::simd` for validation only.
//!
//! The module `crate::simd_avx2` stays public on every x86_64 build,
//! including v2. Calling it directly on a CPU without AVX2 faults with
//! SIGILL, and on the v2 arm no startup check catches it. Use the types
//! re-exported from `crate::simd`.
#[cfg(feature = "std")]
use std::sync::LazyLock;
// On i686 / wasm32 / etc. only the `Scalar` variant is constructed —
// `detect_tier()`'s feature-detection blocks are `target_arch = "x86_64"`
// or `"aarch64"` gated, both false on i686. Without `dead_code` allowance
// the `-D warnings` build fails with `variants ... are never constructed`.
// Note: this `Tier` enum is *runtime* dispatch only. On `wasm32 +
// target_feature = "simd128"` the SIMD *types* are NOT scalar — they come
// from the compile-time `simd_wasm::wasm32_simd` v128 backend (re-exported
// below); `detect_tier()` simply has no wasm arm, so the runtime tier stays
// `Scalar`.
#[allow(dead_code)]
#[derive(Clone, Copy, PartialEq, Debug)]
#[repr(u8)]
enum Tier {
Avx512 = 1,
Avx2 = 2,
/// ARM NEON 128-bit + dotprod (Pi 5 / A76+). 4× int8 throughput.
NeonDotProd = 3,
/// ARM NEON 128-bit baseline (Pi 3/4 / A53/A72). Pure float SIMD.
Neon = 4,
Scalar = 5,
}
impl Tier {
/// Inverse of `as u8` — used by the no_std `critical_section`
/// polyfill below so we can stash a `Tier` into an `AtomicU8`.
#[allow(dead_code)]
#[inline(always)]
fn from_u8(v: u8) -> Self {
match v {
1 => Tier::Avx512,
2 => Tier::Avx2,
3 => Tier::NeonDotProd,
4 => Tier::Neon,
_ => Tier::Scalar,
}
}
}
/// Detect the best SIMD tier the current CPU supports.
///
/// Pulled out of the original `LazyLock::new` closure so it can be
/// reused by both the `std` and `no_std` cache implementations below.
#[allow(dead_code)]
fn detect_tier() -> Tier {
#[cfg(all(feature = "std", target_arch = "x86_64"))]
{
if is_x86_feature_detected!("avx512f") {
return Tier::Avx512;
}
if is_x86_feature_detected!("avx2") {
return Tier::Avx2;
}
}
#[cfg(all(feature = "std", target_arch = "aarch64"))]
{
// NEON is mandatory on aarch64 — always available.
// dotprod (ARMv8.2+) distinguishes Pi 5 from Pi 3/4.
if std::arch::is_aarch64_feature_detected!("dotprod") {
return Tier::NeonDotProd;
}
return Tier::Neon;
}
#[cfg(all(not(feature = "std"), target_arch = "aarch64"))]
{
// No runtime feature detection available without std — fall back
// to whatever the compile-time target features advertise.
#[cfg(target_feature = "dotprod")]
return Tier::NeonDotProd;
#[cfg(not(target_feature = "dotprod"))]
return Tier::Neon;
}
#[cfg(all(not(feature = "std"), target_arch = "x86_64"))]
{
// No `is_x86_feature_detected!` without std — pick the highest
// tier whose features were enabled at compile time.
#[cfg(target_feature = "avx512f")]
return Tier::Avx512;
#[cfg(all(not(target_feature = "avx512f"), target_feature = "avx2"))]
return Tier::Avx2;
}
#[allow(unreachable_code)]
Tier::Scalar
}
// ── std path: original `LazyLock`-backed cache ───────────────────────
#[cfg(feature = "std")]
static TIER: LazyLock<Tier> = LazyLock::new(detect_tier);
#[cfg(feature = "std")]
#[inline(always)]
#[allow(dead_code)]
fn tier() -> Tier {
*TIER
}
// ── no_std path: portable-atomic + critical-section polyfill ────────
#[cfg(all(not(feature = "std"), feature = "portable-atomic-critical-section"))]
use portable_atomic::{AtomicU8, Ordering};
#[cfg(all(not(feature = "std"), feature = "portable-atomic-critical-section"))]
static TIER_INIT: AtomicU8 = AtomicU8::new(0);
#[cfg(all(not(feature = "std"), feature = "portable-atomic-critical-section"))]
#[inline]
#[allow(dead_code)]
fn tier() -> Tier {
let cached = TIER_INIT.load(Ordering::Relaxed);
if cached != 0 {
return Tier::from_u8(cached);
}
critical_section::with(|_| {
let detected = detect_tier();
TIER_INIT.store(detected as u8, Ordering::Relaxed);
detected
})
}
// ── no_std path with no polyfill: compile-time fallback ──────────────
#[cfg(all(not(feature = "std"), not(feature = "portable-atomic-critical-section")))]
#[inline(always)]
#[allow(dead_code)]
fn tier() -> Tier {
detect_tier()
}
// BF16 tier detection happens inline in bf16_to_f32_batch() via
// is_x86_feature_detected!("avx512bf16") — no LazyLock needed.
// The check is cheap (reads a cached cpuid result) and the batch
// function uses as_chunks::<16>() + as_chunks::<8>() for SIMD widths.
// ============================================================================
// Preferred SIMD lane widths — compile-time constants for array_windows
// ============================================================================
//
// Consumer code uses these to select array_windows size at compile time:
//
// for window in data.array_windows::<{crate::simd::PREFERRED_F64_LANES}>() {
// let v = F64x8::from_array(*window); // AVX-512: native 8-wide
// // or
// let v = F64x4::from_array(*window); // AVX2: native 4-wide
// }
//
// generic_const_exprs is nightly, so consumers must #[cfg] branch on window size.
// These constants document the preferred width per tier.
/// Preferred f64 SIMD width (elements per register).
/// AVX-512: 8 lanes (__m512d). AVX2: 4 lanes (__m256d). NEON: 2 lanes (float64x2_t).
#[cfg(target_feature = "avx512f")]
pub const PREFERRED_F64_LANES: usize = 8;
#[cfg(all(target_arch = "x86_64", not(target_feature = "avx512f")))]
pub const PREFERRED_F64_LANES: usize = 4;
#[cfg(target_arch = "aarch64")]
pub const PREFERRED_F64_LANES: usize = 2; // NEON: float64x2_t = 2 × f64
#[cfg(target_arch = "wasm32")]
pub const PREFERRED_F64_LANES: usize = 2; // WASM SIMD128: f64x2 = 2 × f64
#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "wasm32")))]
pub const PREFERRED_F64_LANES: usize = 4; // scalar fallback: same as AVX2 shape
/// Preferred f32 SIMD width.
/// AVX-512: 16 lanes (__m512). AVX2: 8 lanes (__m256). NEON: 4 lanes (float32x4_t).
#[cfg(target_feature = "avx512f")]
pub const PREFERRED_F32_LANES: usize = 16;
#[cfg(all(target_arch = "x86_64", not(target_feature = "avx512f")))]
pub const PREFERRED_F32_LANES: usize = 8;
#[cfg(target_arch = "aarch64")]
pub const PREFERRED_F32_LANES: usize = 4; // NEON: float32x4_t = 4 × f32
#[cfg(target_arch = "wasm32")]
pub const PREFERRED_F32_LANES: usize = 4; // WASM SIMD128: f32x4 = 4 × f32
#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "wasm32")))]
pub const PREFERRED_F32_LANES: usize = 8;
/// Preferred u64 SIMD width.
/// AVX-512: 8 lanes. AVX2: 4 lanes. NEON: 2 lanes (uint64x2_t).
#[cfg(target_feature = "avx512f")]
pub const PREFERRED_U64_LANES: usize = 8;
#[cfg(all(target_arch = "x86_64", not(target_feature = "avx512f")))]
pub const PREFERRED_U64_LANES: usize = 4;
#[cfg(target_arch = "aarch64")]
pub const PREFERRED_U64_LANES: usize = 2; // NEON: uint64x2_t
#[cfg(target_arch = "wasm32")]
pub const PREFERRED_U64_LANES: usize = 2; // WASM SIMD128: i64x2 = 2 × u64
#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "wasm32")))]
pub const PREFERRED_U64_LANES: usize = 4;
/// Preferred i16 SIMD width (for Base17 L1 on i16\[17\]).
/// AVX-512: 32 lanes (__m512i via epi16). AVX2: 16 lanes (__m256i).
/// NEON: 8 lanes (int16x8_t). Base17 has 17 dims — NEON needs 3 loads
/// (8+8+1), A72 dual pipeline hides latency on the third.
#[cfg(target_feature = "avx512f")]
pub const PREFERRED_I16_LANES: usize = 32;
#[cfg(all(target_arch = "x86_64", not(target_feature = "avx512f")))]
pub const PREFERRED_I16_LANES: usize = 16;
#[cfg(target_arch = "aarch64")]
pub const PREFERRED_I16_LANES: usize = 8; // NEON: int16x8_t
#[cfg(target_arch = "wasm32")]
pub const PREFERRED_I16_LANES: usize = 8; // WASM SIMD128: i16x8 = 8 × i16
#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "wasm32")))]
pub const PREFERRED_I16_LANES: usize = 16;
// ============================================================================
// x86_64: re-export based on tier
// ============================================================================
// Compile-time SIMD dispatch via target_feature. The cargo config
// chosen at build (.cargo/config.toml = v3 default / config-avx512.toml
// = v4 / config-native.toml = native) sets the `target_feature` flags
// that select exactly one arm below.
// * v3 / GitHub-CI default → `target_feature = "avx2"` only →
// simd_avx2 backend (F32x16 = two-half (f32x8, f32x8), int wrappers
// are scalar polyfills via the `avx2_int_type!` macro).
// * AVX without AVX2 (`.cargo/config-avx.toml`, or native on a Sandy
// Bridge-class host) → the SAME types and exports as the AVX2 arm, but
// every method that would need AVX2 is realized in `simd_avx.rs` (two
// SSE halves / AVX1 forms); `simd_avx2.rs` and `simd_avx512.rs` gate
// those methods on `not(all(avx, not(avx2)))`.
// * v4 (or native on AVX-512 host) → `target_feature = "avx512f"` →
// simd_avx512 backend with native __m512 / __m512d / __m512i.
// * aarch64 → simd_neon backend.
// * everything else (wasm32, riscv, etc.) → scalar fallback.
// Nightly-simd dispatch — when `feature = "nightly-simd"` is on, the
// `crate::simd_nightly` portable backend (wrapping `core::simd::*`)
// REPLACES the intrinsics arms below. This is a compile-time-dispatch
// choice: opt in via `cargo +nightly --features nightly-simd ...` and
// the same `use crate::simd::F32x16` call sites become miri-runnable.
// No target_arch constraint — `core::simd` is portable, so this arm
// is the one true backend on wasm32 / riscv / aarch64 / x86_64 alike
// as soon as `nightly-simd` is on.
#[cfg(feature = "nightly-simd")]
pub use crate::simd_nightly::{
batch_packed_i4_16, f32x16, f32x8, f64x4, f64x8, i16x16, i16x32, i32x16, i32x8, i64x4, i64x8, i8x16, i8x32, i8x64,
palette_lookup_u8x8, prefetch_read_t0, prefetch_read_t1, prefetch_read_t2, u16x16, u16x32, u16x8, u32x16, u32x8,
u64x4, u64x8, u8x16, u8x32, u8x64, u8x8, BF16x16, BF16x8, F16x16, F32Mask16, F32Mask8, F32x16, F32x8, F64Mask4,
F64Mask8, F64x4, F64x8, I16x16, I16x32, I32x16, I32x8, I64x4, I64x8, I8x16, I8x32, I8x64, U16x16, U16x32, U16x8,
U32x16, U32x8, U64x4, U64x8, U8x16, U8x32, U8x64, U8x8,
};
#[cfg(all(target_arch = "x86_64", target_feature = "avx512f", not(feature = "nightly-simd")))]
pub use crate::simd_avx512::{
batch_packed_i4_16,
f32x16,
f32x8,
f64x4,
f64x8,
i16x16,
i16x32,
i32x16,
i32x8,
i64x4,
i64x8,
i8x16,
i8x32,
i8x64,
palette_lookup_u8x8,
prefetch_read_t0,
prefetch_read_t1,
prefetch_read_t2,
u16x16,
u16x8,
u32x16,
u32x8,
u64x4,
u64x8,
u8x16,
u8x64,
u8x8,
F32Mask16,
// 256-bit lane masks (vector masks on every x86 arm)
F32Mask8,
// 512-bit (native AVX-512, __m512/__m512d/__m512i)
F32x16,
// 256-bit (AVX2, __m256/__m256d/__m256i)
F32x8,
F64Mask4,
F64Mask8,
F64x4,
F64x8,
I16x16,
I16x32,
I32x16,
// 256-bit int polyfills surfaced 2026-05-20 (re-exported from
// `simd_avx2` via `simd_avx512`'s re-export at line ~2260).
I32x8,
I64x4,
I64x8,
I8x16,
I8x32,
I8x64,
U16x16,
U16x32,
U16x8,
U32x16,
U32x8,
U64x4,
U64x8,
U8x16,
U8x64,
U8x8,
};
// BF16 types + batch conversion (always available — scalar fallback built in)
#[cfg(target_arch = "x86_64")]
pub use crate::simd_avx512::{bf16_to_f32_batch, bf16_to_f32_scalar, f32_to_bf16_batch, f32_to_bf16_scalar};
// BF16 RNE (round-to-nearest-even) path — pure AVX-512-F, byte-exact vs
// hardware `_mm512_cvtneps_pbh` on Sapphire Rapids+ (verified on 1M inputs
// in ndarray::simd_avx512::tests). Consumer code should call
// `f32_to_bf16_batch_rne` in hot loops (500-20000× faster than the scalar
// path via AMX / AVX-512 tiles); `f32_to_bf16_scalar_rne` is exposed only
// as a unit-test reference implementation and MUST NOT be called in hot
// loops per the workspace-wide "never scalar ever" rule for F32→BF16.
// See lance-graph/CLAUDE.md § Certification Process.
#[cfg(target_arch = "x86_64")]
pub use crate::simd_avx512::{f32_to_bf16_batch_rne, f32_to_bf16_scalar_rne};
// BF16 SIMD types only available when avx512bf16 is enabled at compile time
#[cfg(all(target_arch = "x86_64", target_feature = "avx512bf16", not(feature = "nightly-simd")))]
pub use crate::simd_avx512::{BF16x16, BF16x8};
// AVX2 arm — selected whenever `avx512f` is not compiled in (a
// `.cargo/config-v3.toml` build, or the default `target-cpu=native` on a host
// without AVX-512). The
// predicate is `not(avx512f)` rather than `avx2 + not(avx512f)` so that
// an x86-64 baseline build (e.g. a `RUSTFLAGS` env that REPLACES the
// `.cargo/config.toml` target-cpu pin) still has a matching arm and
// COMPILES: the struct-field types (`__m256` / `__m256i`) are core::arch
// declarations that need no target feature at the type level.
//
// CORRECTED 2026-09-14: an earlier version of this comment claimed the
// inner intrinsics in `simd_avx2.rs` carry per-function
// `#[target_feature(enable = "avx,avx2,fma")]`. They do not, and by
// standing rule they must not — every `simd_{isa}.rs` file is one
// backend for one compile-time target, so a per-function feature gate is
// a second, contradictory selection mechanism. The intrinsic calls in
// `simd_avx2.rs` sit inside narrow `unsafe` blocks whose SAFETY
// precondition is AVX2 at run time, a caller obligation (the default
// `target-cpu=native` names no tier); a baseline build compiles this arm but is not a supported
// execution target for it (it would SIGILL on the first `vp*` — the
// PR #170 failure mode the config pin exists to prevent).
#[cfg(all(
target_arch = "x86_64",
not(target_feature = "avx512f"),
not(all(target_feature = "sse4.2", not(target_feature = "avx"))),
not(feature = "nightly-simd")
))]
pub use crate::simd_avx512::{
batch_packed_i4_16, f32x8, f64x4, i16x16, i8x16, i8x32, palette_lookup_u8x8, prefetch_read_t0, prefetch_read_t1,
prefetch_read_t2, u16x8, u8x16, u8x8, F32Mask8, F32x8, F64Mask4, F64x4, I16x16, I8x16, I8x32, U16x8, U8x16, U8x8,
};
#[cfg(all(
target_arch = "x86_64",
not(target_feature = "avx512f"),
not(all(target_feature = "sse4.2", not(target_feature = "avx"))),
not(feature = "nightly-simd")
))]
pub use crate::simd_avx2::{
f32x16, f64x8, i16x32, i32x16, i32x8, i64x4, i64x8, i8x64, u16x16, u32x16, u32x8, u64x4, u64x8, u8x64, F32Mask16,
F32x16, F64Mask8, F64x8, I16x32, I32x16, I32x8, I64x4, I64x8, I8x64, U16x16, U16x32, U32x16, U32x8, U64x4, U64x8,
U8x64,
};
// U8x32 — native AVX2 byte width (one __m256i = 32 bytes). Available on
// both AVX-512 and AVX2 builds: it's the natural width for byte-level
// AVX2 ops, and on AVX-512 builds it's the half-register companion to
// U8x64. Lives in simd_avx2.rs (single source of truth) and is re-exported
// from both tier branches.
#[cfg(all(
target_arch = "x86_64",
not(all(target_feature = "sse4.2", not(target_feature = "avx"))),
not(feature = "nightly-simd")
))]
pub use crate::simd_avx2::{u8x32, U8x32};
// ============================================================================
// Non-x86: scalar fallback types with identical API
// ============================================================================
// Scalar backend lives in its own file (`src/simd_scalar.rs`), declared
// here with `#[path]` so the internal module name stays `scalar` and
// the existing `pub use scalar::{...}` re-exports below don't need to
// change. Extracted from this file in Phase 4 of the integration plan
// (1271 LoC of macro expansions out of the dispatcher).
#[cfg(all(
any(
not(target_arch = "x86_64"),
all(target_feature = "sse4.2", not(target_feature = "avx"))
),
not(feature = "nightly-simd")
))]
#[path = "simd_scalar.rs"]
pub(crate) mod scalar;
// aarch64: F32x16/F64x8 come from the real NEON paired-load implementation
// in simd_neon::aarch64_simd (verified 2026-04-30, agent A7 — burn parity item 9).
// Integer + 256-bit float types still come from the scalar fallback; they're
// not on the critical path for f32 BLAS-1 / VML kernels.
#[cfg(all(target_arch = "aarch64", not(feature = "nightly-simd")))]
pub use crate::simd_neon::aarch64_simd::{f32x16, f64x8, F32Mask16, F32x16, F64Mask8, F64x8};
// W1a NEON-native types + free functions
#[cfg(all(target_arch = "aarch64", not(feature = "nightly-simd")))]
pub use crate::simd_neon::{
batch_packed_i4_16, i8x16, i8x32, palette_lookup_u8x8, prefetch_read_t0, prefetch_read_t1, prefetch_read_t2, u8x16,
u8x8, I8x16, I8x32, U8x16, U8x8,
};
// The 64×8 and 32×16 signed rungs of the ladder (64×8, 32×16, 16×32). `simd_neon.rs` has
// carried them since #337 but no arm re-exported them, so aarch64 had neither type.
#[cfg(all(target_arch = "aarch64", not(feature = "nightly-simd")))]
pub use crate::simd_neon::{i16x32, i8x64, I16x32, I8x64};
// U16x8 on aarch64 comes from simd_neon (backed by uint16x8_t)
#[cfg(all(target_arch = "aarch64", not(feature = "nightly-simd")))]
pub use crate::simd_neon::{u16x8, U16x8};
// U32x16 (native `[U32x4; 4]`) — the ARX lane the ChaCha20 backend rides. Comes
// from simd_neon, not the scalar fallback, so it carries Add/BitXor/rotate_left.
#[cfg(all(target_arch = "aarch64", not(feature = "nightly-simd")))]
pub use crate::simd_neon::{u32x16, U32x16};
// U64x8 + I32x16 — native `[uint64x2_t; 4]` / `[int32x4_t; 4]` fan-outs since
// 2026-09-13 (the five-flavour audit of #306: every bulk mask op and the whole
// signed-compare family ride these two types, and both used to resolve to the
// scalar backend here — the polyfill law wants a peer realisation per backend).
// The lowercase aliases travel WITH the types: `i32x16`/`u64x8` must name the
// same nominal type as `I32x16`/`U64x8` on every arm, so they come from the
// arm that owns the type (an alias left on the scalar list would silently
// split the facade into two types on this arch — product-engineer, PR #306).
#[cfg(all(target_arch = "aarch64", not(feature = "nightly-simd")))]
pub use crate::simd_neon::{i32x16, u64x8, I32x16, U64x8};
#[cfg(all(target_arch = "aarch64", not(feature = "nightly-simd")))]
pub use scalar::{
f32x8, f64x4, i32x8, i64x4, i64x8, u16x16, u32x8, u64x4, u8x64, F32Mask8, F32x8, F64Mask4, F64x4, I32x8, I64x4,
I64x8, U16x16, U16x32, U32x8, U64x4, U8x64,
};
// wasm32 + simd128: the native v128 float hot path (F32x16 / F64x8 + masks)
// and native I8x16 come from `simd_wasm::wasm32_simd`; the long-tail integer
// and 256-bit-shaped types come from the scalar fallback. Same split
// `simd_neon` uses on aarch64 (native float kernels, scalar for the rest).
// The `wasm32_simd` module only exists under `target_feature = "simd128"`,
// so this arm is gated identically.
#[cfg(all(target_arch = "wasm32", target_feature = "simd128", not(feature = "nightly-simd")))]
pub use crate::simd_wasm::wasm32_simd::{
f32x16, f64x8, i32x16, i8x16, u32x16, u64x8, u8x16, F32Mask16, F32x16, F64Mask8, F64x8, I32x16, I8x16, U32x16,
U64x8, U8x16,
};
// `u32x16`/`U32x16`, `i32x16`/`I32x16` and `u64x8`/`U64x8` come from the
// native `wasm32_simd` arm above (the lowercase alias travels with its type —
// see the aarch64 note), so they are dropped from this scalar list.
#[cfg(all(target_arch = "wasm32", target_feature = "simd128", not(feature = "nightly-simd")))]
pub use scalar::{
batch_packed_i4_16, f32x8, f64x4, i16x16, i16x32, i32x8, i64x4, i64x8, i8x32, i8x64, palette_lookup_u8x8,
prefetch_read_t0, prefetch_read_t1, prefetch_read_t2, u16x16, u16x8, u32x8, u64x4, u8x64, u8x8, F32Mask8, F32x8,
F64Mask4, F64x4, I16x16, I16x32, I32x8, I64x4, I64x8, I8x32, I8x64, U16x16, U16x32, U16x8, U32x8, U64x4, U8x64,
U8x8,
};
// Other non-x86 targets — wasm32 without simd128, riscv, etc.: full scalar
// fallback. Excludes the wasm32+simd128 case handled by the native arm above.
#[cfg(all(
any(
all(
not(target_arch = "x86_64"),
not(target_arch = "aarch64"),
not(all(target_arch = "wasm32", target_feature = "simd128"))
),
// x86-64-v2 (SSE4.2, no AVX): `simd_avx2.rs`/`simd_avx512.rs` types wrap
// 256/512-bit registers, so this arm takes the scalar realization, which
// LLVM vectorizes to SSE. Plan: `.claude/plans/simd-sse-v2-tier-v1.md`.
all(target_arch = "x86_64", all(target_feature = "sse4.2", not(target_feature = "avx")))
),
not(feature = "nightly-simd")
))]
pub use scalar::{
batch_packed_i4_16, f32x16, f32x8, f64x4, f64x8, i16x16, i16x32, i32x16, i32x8, i64x4, i64x8, i8x16, i8x32, i8x64,
palette_lookup_u8x8, prefetch_read_t0, prefetch_read_t1, prefetch_read_t2, u16x16, u16x8, u32x16, u32x8, u64x4,
u64x8, u8x16, u8x64, u8x8, F32Mask16, F32Mask8, F32x16, F32x8, F64Mask4, F64Mask8, F64x4, F64x8, I16x16, I16x32,
I32x16, I32x8, I64x4, I64x8, I8x16, I8x32, I8x64, U16x16, U16x32, U16x8, U32x16, U32x8, U64x4, U64x8, U8x16, U8x64,
U8x8,
};
// Scalar BF16 conversion — always available on all platforms
#[cfg(not(target_arch = "x86_64"))]
pub fn bf16_to_f32_scalar(bits: u16) -> f32 {
f32::from_bits((bits as u32) << 16)
}
#[cfg(not(target_arch = "x86_64"))]
pub fn f32_to_bf16_scalar(v: f32) -> u16 {
(v.to_bits() >> 16) as u16
}
#[cfg(not(target_arch = "x86_64"))]
pub fn bf16_to_f32_batch(input: &[u16], output: &mut [f32]) {
for (i, &b) in input.iter().enumerate() {
if i < output.len() {
output[i] = bf16_to_f32_scalar(b);
}
}
}
#[cfg(not(target_arch = "x86_64"))]
pub fn f32_to_bf16_batch(input: &[f32], output: &mut [u16]) {
for (i, &v) in input.iter().enumerate() {
if i < output.len() {
output[i] = f32_to_bf16_scalar(v);
}
}
}
// ============================================================================
// SIMD math functions — ndarray additions (not in std::simd)
// ============================================================================
/// Fast exp(x) for F32x16 — Cephes minimax polynomial after range reduction.
///
/// Within 1 ULP of the correctly rounded result for normal results
/// (measured on 4 M points over [-87, 88.5]). Uses the standard
/// range-reduction approach: exp(x) = 2^n * exp(r) where r = x - n*ln(2).
///
/// Domain: inputs from ln(f32::MAX) up return +Inf, and inputs are clamped
/// to [-110, ln(f32::MAX)] before reduction, so -Inf and anything below
/// about -103.9 return +0.0 and the range in between returns subnormals.
/// The clamp also keeps `n` far from `i32` overflow in `pow2n_from_int`.
///
/// NaN handling: `simd_clamp` is `max(lo).min(hi)`, and `_mm512_max_ps` /
/// `_mm512_min_ps` return the SECOND operand when the first is NaN (per
/// Intel SDM § MAXPS/MINPS). That would silently clamp NaN inputs to `lo`
/// (-87.336) producing `exp(-87.336) ≈ 1.4e-38` — a finite tiny value
/// masquerading as valid output. Caught by codex review on PR #142.
///
/// Fix: capture NaN lanes via `x.simd_ne(x)` (NaN ≠ itself per IEEE 754)
/// before the clamp, then mask-select NaN back into those lanes after
/// the polynomial. NaN lanes propagate as NaN; finite lanes are unchanged.
#[inline(always)]
#[allow(dead_code)]
pub fn simd_exp_f32(x: F32x16) -> F32x16 {
let inv_ln2 = F32x16::splat(1.0 / core::f32::consts::LN_2);
let one = F32x16::splat(1.0);
// NaN-preservation mask: bit set wherever x is NaN. IEEE 754: NaN ≠ NaN.
// Captured BEFORE the clamp because simd_clamp destroys NaN lanes.
let nan_mask = x.simd_ne(x);
// At the upper clamp the true result already exceeds f32::MAX, so the
// final product overflows to +Inf for every input from there up. Below
// -110 the result rounds to +0.0 anyway, so clamping there only keeps
// `n` in range.
let x = x.simd_clamp(F32x16::splat(-110.0_f32), F32x16::splat(OVERFLOW_X));
// Range reduction: n = round(x / ln2), r = x - n * ln2, with ln2 split
// Cody-Waite style. LN2_HI has 9 significant bits, so n * LN2_HI is exact
// for |n| < 2^15 and x - n * LN2_HI is exact by Sterbenz's lemma. A
// single-constant `x - n * ln2` rounds n * ln2 at |x| ~ 90, where one ulp
// is ~7.6e-6: that error was larger than the polynomial's.
//
// Plain `*` and `+`: unfused ops round identically on every backend (the
// same rule as `gemm_f64_tiled` in `simd_ops`), and the split above makes
// the fused form unnecessary for accuracy. (`mul_add` is fused on every
// backend too, wasm included, but costs an emulation there.)
// floor(t + 0.5), not round(): `round` breaks ties to even on AVX-512,
// NEON and wasm but away from zero on AVX2, scalar and nightly, so a tie
// would pick a different n per backend. floor is the same everywhere.
let n = (x * inv_ln2 + F32x16::splat(0.5)).floor();
let r = x - n * F32x16::splat(LN2_HI);
let r = r - n * F32x16::splat(LN2_LO);
// Polynomial: exp(r) ≈ 1 + r + r²·P(r) on |r| ≤ ln2/2, with P the Cephes
// `expf` minimax of degree 5. The degree-5 Taylor series used before was
// 39 ULP off at |r| = ln2/2 (its r⁶/720 term is ~2.4e-6 relative).
let p = F32x16::splat(EXP_P[0]);
let p = p * r + F32x16::splat(EXP_P[1]);
let p = p * r + F32x16::splat(EXP_P[2]);
let p = p * r + F32x16::splat(EXP_P[3]);
let p = p * r + F32x16::splat(EXP_P[4]);
let p = p * r + F32x16::splat(EXP_P[5]);
let poly = (p * (r * r) + r) + one;
// Reconstruct: exp(x) = 2^n * poly. 2^n is only a normal f32 for n in
// [-126, 127], but n reaches 128 near the overflow edge and about -159
// at the lower clamp. Those lanes scale by 2^(n-1) then 2, or by
// 2^(n+64) then 2^-64, so the top results are not halved and the bottom
// ones land on the right subnormal instead of the 2^-126 floor.
let high = n.simd_gt(F32x16::splat(127.0));
let low = n.simd_lt(F32x16::splat(-126.0));
let n = high.select(n - one, low.select(n + F32x16::splat(64.0), n));
let result = poly * pow2n_from_int(n);
let result = high.select(result * F32x16::splat(2.0), result);
let result = low.select(result * F32x16::splat(TWO_POW_NEG_64), result);
// Restore NaN in lanes where the input was NaN (clamp had destroyed them).
nan_mask.select(F32x16::splat(f32::NAN), result)
}
/// Cephes `expf` coefficients, highest degree first: `exp(r) ≈ 1 + r + r²·P(r)`.
const EXP_P: [f32; 6] = [
1.987_569_150_0e-4, 1.398_199_950_7e-3, 8.333_451_907_3e-3, 4.166_579_589_4e-2, 1.666_666_545_9e-1,
5.000_000_120_1e-1,
];
/// f32 just above ln(f32::MAX): `exp` of it overflows to +inf.
const OVERFLOW_X: f32 = 88.722_84;
/// High part of ln 2 (Cephes): 355/512, 9 significant bits.
const LN2_HI: f32 = 0.693_359_4;
/// ln 2 - LN2_HI.
const LN2_LO: f32 = -2.121_944_4e-4;
/// 2^-64, exact in f32.
const TWO_POW_NEG_64: f32 = 5.421_011e-20;
/// Compute 2^n where n is an integer stored as f32.
///
/// Uses the IEEE 754 trick: set the exponent field directly.
///
/// The `ni` is clamped to [-126, 127] before adding the 127 bias so that
/// `(ni + 127) as u32` stays in [1, 254] (valid normal-number exponent
/// field). Without this clamp, an `Inf` input from `simd_exp_f32` would
/// saturate to `i32::MAX`, then `+ 127` would panic in debug or wrap in
/// release, producing a garbage IEEE bit pattern (was: silent ~0.5 result).
/// Caller `simd_exp_f32` already pre-clamps the domain so this is defense
/// in depth.
#[inline(always)]
#[allow(dead_code)]
fn pow2n_from_int(n: F32x16) -> F32x16 {
// `n` is integral (it comes from `round`), so after the clamp
// `2^23 + 127 + n` is an exact f32 whose mantissa field holds the biased
// exponent `k = n + 127` in [1, 254] and whose exponent field is
// 0x4B00_0000. Shifting the bits left by 23 pushes 0x4B00_0000 out of the
// word and moves `k` into the exponent field: the bits of 2^n. No lane
// leaves its register.
let biased = n.simd_clamp(F32x16::splat(-126.0), F32x16::splat(127.0)) + F32x16::splat(8_388_608.0 + 127.0);
F32x16::from_bits(biased.to_bits() << U32x16::splat(23))
}
/// Fast natural log for F32x16.
#[inline(always)]
#[allow(dead_code)]
pub fn simd_ln_f32(x: F32x16) -> F32x16 {
let arr = x.to_array();
let mut out = [0.0f32; 16];
for i in 0..16 {
out[i] = arr[i].ln();
}
F32x16::from_array(out)
}
// ============================================================================
// Cognitive shader foundation re-exports
// ============================================================================
// HPC re-exports — only available when the hpc module is compiled.
// Without `hpc-extras`, consumers still get the SIMD polyfill types above
// (F32x16, I8x32, etc.) but NOT the domain-specific functions below.
/// Truth-table immediates for `U64x8::ternlog` / `U32x16::ternlog`.
///
/// A ternlog immediate IS the truth table of a 3-input boolean function: for
/// each bit position, `index = (a << 2) | (b << 1) | c`, and the result bit is
/// `(IMM >> index) & 1`. Intel's VPTERNLOG convention, reproduced exactly by
/// every backend in this crate.
///
/// Lives on the facade — NOT in a backend — so `ndarray::simd::ternlog::AND3`
/// resolves on every dispatch arm (a backend-resident module is compiled out
/// whenever another backend is selected, which is exactly what happened to
/// this module's first home in the scalar backend).
pub mod ternlog {
/// `a & b & c` — stack three prerequisite masks.
pub const AND3: i32 = 0x80;
/// `a & b & !c` — stack two prerequisites, exclude a third.
pub const AND2_ANDNOT: i32 = 0x40;
/// `a & !b & !c` — one base mask, two exclusions.
pub const AND_ANDNOT2: i32 = 0x10;
/// `(a | b) & c` — either of two prerequisites, gated by a third.
pub const OR2_AND: i32 = 0xA8;
/// `a ^ b ^ c` — three-way parity.
pub const XOR3: i32 = 0x96;
/// `(a & b) | (a & c) | (b & c)` — two-of-three majority.
pub const MAJ3: i32 = 0xE8;
/// `a & b` — two-input AND, `c` ignored.
pub const AND2: i32 = 0xC0;
/// `a | b | c` — union of three masks.
pub const OR3: i32 = 0xFE;
/// `(a ^ b) & c` — the bits where `a` and `b` DIFFER, restricted to the
/// care set `c`; zero iff `a` matches `b` under care. The care-masked
/// (ternary) match kernel: `ternary_match_*_to_mask` tests this for zero.
pub const XOR_AND: i32 = 0x28;
/// `(a & b) | c` — two prerequisites, or an override. The immediate the
/// `lance-graph-duckmask` flagship `(A & B) | C` lowers to.
pub const AND2_OR: i32 = 0xEA;
}
pub use crate::hpc::bitwise::{hamming_distance_raw, hamming_distance_within, popcount_raw};
pub use crate::hpc::bnn_cross_plane::CollapseGate;
pub use crate::hpc::fft::{wht_f32, wht_f32_new};
pub use crate::hpc::fingerprint::{
vector_config, Fingerprint, Fingerprint1K, Fingerprint2K, Fingerprint64K, VectorConfig, VectorWidth,
};
pub use crate::hpc::phase::{phase_lut_4096, radians_from_turns, turns_from_radians, PhaseLut, PhaseStep};
pub use crate::hpc::statistics::{moments_u32, MomentsU32};
// Checked i64 arithmetic (ONNX int64 Add/Sub/Mul/Div and Range), surfaced so
// consumers name it through the facade, never through `hpc`. Plain re-exports:
// same functions, same refusal policy.
///
/// ```
/// use ndarray::simd::{checked_binary_i64, I64ArithError, I64Op};
/// let mut out = [0i64; 2];
/// checked_binary_i64(I64Op::Mul, &[4, 3], &[2], &mut out).unwrap();
/// assert_eq!(out, [8, 6]);
/// assert!(matches!(
/// checked_binary_i64(I64Op::Mul, &[i64::MAX, 1], &[2], &mut out),
/// Err(I64ArithError::Overflow { .. })
/// ));
/// ```
pub use crate::hpc::checked_i64::{checked_binary_i64, checked_i64, range_i64, range_len_i64, I64ArithError, I64Op};
// Element-wise f32 math (VML), activations and the batched f32 matmul,
// surfaced so consumers stay on the one `ndarray::simd::*` import path.
// Plain re-exports of the `hpc` items: same functions, same behaviour.
pub use crate::hpc::activations::{log_softmax_axis_f32, log_softmax_f32, sigmoid_f32, softmax_axis_f32, softmax_f32};
pub use crate::hpc::vml::{
vsabs, vsadd, vsceil, vscos, vsdiv, vserf, vsexp, vsfloor, vsln, vsmul, vsneg, vspow, vsround, vssin, vssqrt,
vstanh, vstrunc,
};
// `hpc::amx_matmul` is `#[cfg(target_arch = "x86_64")]`; the re-export uses
// the same gate. `matmul_f32` itself is not re-exported: under
// `runtime-dispatch` that name is the `simd_runtime` trampoline.
#[cfg(target_arch = "x86_64")]
pub use crate::hpc::amx_matmul::{matmul_f32_batched, MatmulError};
// PR-X1 — SoA carrier + const-size slice helpers, dispatched from their
// respective `simd_{type}.rs` modules. The W1a consumer contract forbids
// reaching past `crate::simd::*` into the implementation modules directly.
//
// `array_chunks` (non-overlapping) and `array_windows` (overlapping) are
// the stable-Rust foundation primitives for SIMD-staged kernels — together
// with `add_mul_f32` / `add_mul_f64` below, they reach within a few %
// of a Cranelift-JIT'd inner loop on the BLAS-graph GEMM path and are
// the reason the JIT-native option was deemed unnecessary. See the
// "Foundation primitives — do not remove" notice in `src/simd_ops.rs`.
pub use crate::simd_ops::{array_chunks, array_chunks_checked, array_windows, array_windows_checked};
// Crate-native tiled f64 GEMM (`C := α·A·B + β·C`) with a bit-exactness
// contract: unfused mul+add in ascending-k order per element → bit-identical
// on every backend (AVX-512/AVX2/NEON/WASM/scalar) and, at α=1 β=0,
// bit-identical to the naive triple-loop reference. This is the in-crate
// ground-truth GEMM for probes/certification AND the engine behind
// `backend::native::gemm_f64` (own Rust in the f64 BLAS path; the f32
// sibling still delegates to the external `matrixmultiply` crate).
// `gemm_f64_tiled_fma` is the fast fused tier (same tiling/order, one
// rounding per step) for consumers on FMA-pinned targets — not the
// backend engine, because its scalar polyfill can lower to libm `fma()`
// on baseline builds. Both kernels are alloc-free, but `pub mod
// simd`/`simd_ops` are std-gated in lib.rs, so they are reachable only
// in `std` builds today.
pub use crate::simd_ops::{gemm_f64_tiled, gemm_f64_tiled_fma};
pub use crate::simd_soa::MultiLaneColumn;
pub use crate::hpc::quantized::{
dequantize_i2_to_f32, dequantize_i4_to_f32, dequantize_i8_to_f32, quantize_f32_to_i2, quantize_f32_to_i4,
quantize_f32_to_i8, QuantParams,
};
// Half-precision SIMD vectors (BF16x16, F16x16) — portable scalar impl, always
// available. Note: when `target_feature = "avx512bf16"` is active a separate
// hardware-native `BF16x16` is also exported above from `simd_avx512`; in that
// case we only re-export F16x16 + slice ops to avoid name collisions.
//
// On all other targets (including avx512f-without-bf16, NEON, scalar) the
// portable `simd_half::BF16x16` is the canonical 16-lane BF16 vector.
// Always re-export the slice-level ops (no naming conflict).
#[cfg(feature = "std")]
pub use crate::simd_half::{
add_bf16_inplace, add_f16_inplace, cast_bf16_to_f32_batch, cast_f16_to_f32_batch, cast_f32_to_bf16_batch,
cast_f32_to_f16_batch, mul_bf16_inplace, mul_f16_inplace,
};
// The portable `simd_half::F16x16` yields the name to a backend that owns it:
// the `nightly-simd` arm above re-exports its own `F16x16`, so under that
// feature this re-export was a second definition (E0252 — one of the 25
// nightly-rot errors fixed 2026-09-14). Same rule as `BF16x16` below.
#[cfg(all(feature = "std", not(feature = "nightly-simd")))]
pub use crate::simd_half::F16x16;
// Re-export portable BF16x16 only when neither hardware-native variant owns the
// name (`simd_avx512::BF16x16` under avx512bf16; `simd_nightly::BF16x16` under
// `nightly-simd`).
#[cfg(all(
feature = "std",
not(feature = "nightly-simd"),
not(all(target_arch = "x86_64", target_feature = "avx512bf16"))
))]
pub use crate::simd_half::BF16x16;
// K-means + L2 distance
pub use crate::hpc::cam_pq::{kmeans, squared_l2};
// Real BLAS Level 3 GEMM (and its siblings syrk/symm/trmm/trsm) surfaced here so a
// consumer reaches the native-SIMD-dispatching matmul through the canonical
// `ndarray::simd::*` import instead of dipping into `crate::hpc::blas_level3` directly
// (the W1a consumer invariant — "all SIMD from `ndarray::simd`").
pub use crate::hpc::blas_level2::Uplo;
pub use crate::hpc::blas_level3::{BlasLevel3, Side};
// SIMD cosine
pub use crate::hpc::heel_f64x8::cosine_f32_to_f64_simd;
// The Belichtungsmesser — banded multi-resolution cascade search
// (`Cascade::expose(distance) → Band`, `recalibrate(ShiftAlert)`,
// `PackedDatabase`, `adaptive_resolution`). Trampolined as a whole module so
// consumers under the "all SIMD from `ndarray::simd`" invariant reach the
// exposure-meter surface as `ndarray::simd::cascade::*` without dipping into
// `crate::hpc` directly. Module alias, not an item list — new cascade items
// arrive here without a re-export edit. Same `std` gate as this module.
pub use crate::hpc::cascade;
// Dispatched integer matmul — the polyfill entry for batched int8 scoring.
// `matmul_i8_to_i32` runtime-selects AMX `TDPBUSD` tiles (byte-asm, 16384
// MAC/instr, Sapphire Rapids+) → AVX-512 VPDPBUSD → AVX-VNNI → scalar, and
// is bit-identical across tiers. Surfaced here so a consumer reaches the
// whole AMX ladder through the canonical `ndarray::simd::*` import (W1a)
// without dipping into `crate::hpc::amx_matmul` directly. `amx_available()`
// exposes the runtime tier check for reporting.
// AMX is x86_64-only (the `amx_matmul` / `simd_amx` modules are
// `#[cfg(target_arch = "x86_64")]`), so these re-exports are arch-gated.
// Off x86 the cross-platform entry points are `backend::gemm_i8` /
// `backend::gemm_bf16` (portable scalar / NEON / wasm-SIMD paths).
#[cfg(all(feature = "std", target_arch = "x86_64"))]
pub use crate::hpc::amx_matmul::{amx_available, matmul_i8_to_i32};
// Runtime-dispatch trampolines (`simd_runtime`, feature = "runtime-dispatch")
// surfaced through the canonical `ndarray::simd::*` namespace — the W1a
// consumer invariant is "all SIMD from `ndarray::simd`", so consumers that
// were importing `ndarray::simd_runtime::{matmul_*, gemm_u8_i8, ...}`
// directly (e.g. the tesseract-rs recognizer's int8 GEMM) can now stay on
// the one polyfill import path. These are thin `#[inline(always)]` aliases
// of the SAME underlying tier ladders (`hpc::amx_matmul`, `simd_int_ops`),
// so switching import paths is bit-identical by construction.
#[cfg(feature = "runtime-dispatch")]
pub use crate::simd_runtime::{gemm_u8_i8, matmul_bf16_to_f32, matmul_f32, vnni_dot_u8_i8};
// `matmul_i8_to_i32` already has its canonical `simd::` name on
// x86_64 + std (the `hpc::amx_matmul` re-export above — the identical
// function `simd_runtime::matmul_i8_to_i32` wraps). Off x86_64 the name
// only exists via the runtime-dispatch trampoline, re-exported here so the
// import path is arch-uniform; the cfg keeps the two aliases from
// colliding when both features hold on x86_64.
#[cfg(all(feature = "runtime-dispatch", not(target_arch = "x86_64")))]
pub use crate::simd_runtime::matmul_i8_to_i32;
// Tile-dispatching sibling of the polyfill `bf16_tile_gemm_16x16` below:
// AMX TDPBF16PS → AVX-512 VDPBF16PS → the same FMA polyfill kernel, selected
// at runtime. Same W1a rationale as `matmul_i8_to_i32` — consumers reach the
// tile ladder through `ndarray::simd::*`; the `_amx` suffix keeps the
// pure-polyfill kernel and the tile-dispatching wrapper distinguishable at
// the call site. `bf16_tile_gemm_16x16_packed` + `PackedBf16B` hoist the
// VNNI pack (and its allocation) out of hot loops — `PackedBf16B::vnni_index`
// additionally supports staging B directly in VNNI layout (zero pack cost).
// `bf16_tile_gemm_tier()` names the tier that will run, for Gotcha-9-style
// run reports.
// The INT8 (`u8 x i8 -> i32`, AMX TDPBUSD) twins: `PackedI8B` hoists the
// VNNI pack out of hot loops and the strided entry reads A at its own pitch.
#[cfg(all(feature = "std", target_arch = "x86_64"))]
pub use crate::hpc::bf16_tile_gemm::{
bf16_tile_gemm_16x16 as bf16_tile_gemm_16x16_amx, bf16_tile_gemm_16x16_packed, bf16_tile_gemm_16x16_packed_strided,
bf16_tile_gemm_tier, PackedBf16B,
};
// The INT8 (`u8 x i8 -> i32`, AMX TDPBUSD) twins of the BF16 packed entries:
// `PackedI8B` hoists the VNNI pack out of hot loops, the strided entries read A
// at its own pitch. Re-exported from the AMX backend (`simd_amx`), which faces
// the kernels in `hpc::int8_tile_gemm`; consumers never import `hpc` directly.
#[cfg(all(feature = "std", target_arch = "x86_64"))]
pub use crate::simd_amx::{
int8_gemm_packed_strided, int8_tile_gemm_16x16_packed, int8_tile_gemm_16x16_packed_strided, int8_tile_gemm_tier,
PackedI8B,
};
// CPU-generation detection (cached): SPR / EMR / GNR / Sierra Forest. Lets a
// consumer report which silicon a run landed on and distinguish "no AMX
// silicon" from "AMX present but not OS-enabled" — both surface via `amx_report`.
#[cfg(target_arch = "x86_64")]
pub use crate::simd_amx::{amx_report, cpu_model, CpuModel};
// The tier-agnostic tile gate and the per-tier silicon bits: precondition #1
// and #2 of every op in `hpc::amx_ops`, reachable through the facade so a
// consumer under the "all SIMD from `ndarray::simd`" rule can state them.
#[cfg(target_arch = "x86_64")]
pub use crate::hpc::amx_ops::{amx_features, AmxFeatures};
#[cfg(target_arch = "x86_64")]
pub use crate::simd_amx::amx_tile_available;
// Packed-bitmask predicates + mask algebra + masked reductions — the
// columnar-selection lane, owned by `simd_masking_ops.rs` (the ergonomic
// masking layer: slice/tail/in-place composition over the lane-level
// `U32x16::eq_bitmask` / `I32x16::gt_bitmask` / `U64x8::ternlog` methods,
// never an ISA). Surfaced here because the W1a invariant is "all SIMD from
// `ndarray::simd`": a consumer that reached into `ndarray::simd_masking_ops`
// directly (or worse, wrote its own compare-and-pack loop) would be a
// polyfill bypass. Bit order is normative and identical across all of them —
// element `i` at bit `i % 64` of word `i / 64`, trailing bits zero. See
// `src/simd_masking_ops.rs` for the full statement.
#[cfg(feature = "std")]
pub use crate::simd_masking_ops::{
// 2026-09-13: the closed comparison family + complement/xor/any/all + care-masked
// register match + masked min/max + blend (lance-graph-duckmask, lgj-abi D-MRL-1a).
// 2026-09-16: the u8 compare-to-mask family — one 64-lane `U8x64` chunk is
// exactly one whole 64-bit mask word, so these pack without a shift (N2/G1
// of the DuckDB->V3 translation matrix).
// 2026-09-16: the ordered u64 family (N3/G2). The width where the packing
// is NOT free — `U64x8` is 8 lanes, so eight groups share a word and each
// lands at its own byte.
blend_f32,
blend_f32_scalar,
blend_i32,
blend_i32_scalar,
blend_i64,
blend_i64_scalar,
// 2026-11-12: the position-form folds (D-DR-SELECT-K-SV): a borrowed
// `&[u32]` selection read as a bag, for selections sparse against the lane.
count_gt_i32_at,
// 2026-11-13: the bag count over a row mask (D-VAS-R12, gate A).
count_set_at,
eq_f32_pair_to_mask,
eq_f32_to_mask,
eq_f64_to_mask,
eq_i32_pair_to_mask,
eq_i32_to_mask,
eq_i32_to_mask_under,
eq_i64_pair_to_mask,
eq_i64_to_mask,
eq_u32_strided_to_mask,
eq_u32_to_mask,
eq_u32_to_mask_under,
eq_u32_via_to_mask,
eq_u64_to_mask,
eq_u8_to_mask,
fold_bounded_cross_power_sums_tiles,
fold_bounded_power_sums_tiles,
ge_f32_pair_to_mask,
ge_f32_to_mask,
ge_f64_to_mask,
ge_i32_pair_to_mask,
ge_i32_to_mask,
ge_i32_to_mask_under,
ge_i64_pair_to_mask,
ge_i64_to_mask,
ge_u64_to_mask,
ge_u8_to_mask,
gt_f32_pair_to_mask,
gt_f32_to_mask,
gt_f64_to_mask,
gt_i32_pair_to_mask,
gt_i32_to_mask,
gt_i32_to_mask_under,
gt_i64_pair_to_mask,
gt_i64_to_mask,
gt_u64_to_mask,
gt_u8_to_mask,
le_f32_pair_to_mask,
le_f32_to_mask,
le_f64_to_mask,
le_i32_pair_to_mask,
le_i32_to_mask,
le_i32_to_mask_under,
le_i64_pair_to_mask,
le_i64_to_mask,
le_u64_to_mask,
le_u8_to_mask,
lt_f32_pair_to_mask,
lt_f32_to_mask,
lt_f64_to_mask,
lt_i32_pair_to_mask,
lt_i32_to_mask,
lt_i32_to_mask_under,
lt_i64_pair_to_mask,
lt_i64_to_mask,
lt_u64_to_mask,
lt_u8_to_mask,
mask_all,
mask_and,
mask_and_assign,
mask_andnot,
mask_andnot_assign,
mask_any,