magemath 0.1.1

Configurable scalar and SIMD transcendental approximations with explicit numerical contracts.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
use super::*;
use crate::{Execution, Portability, SimdMath, Validation};
extern crate std;
#[path = "../../tests/data/powf.rs"]
mod fixtures;

// Keep full frozen fixtures available without making every ordinary test/Miri
// invocation replay the full cross-product. Both tiers use the same oracle and
// assertions; the explicit _exhaustive-tests feature restores every row.
fn oracle_rows() -> impl Iterator<Item = &'static [u32; 5]> {
    fixtures::POWF
        .iter()
        .enumerate()
        .filter_map(|(index, row)| {
            let [base, exponent, _, _, _] = *row;
            let directed =
                exponent == 0x4019_999a || exponent == 0x3f00_0000 || base == 0x3f80_0000;
            (cfg!(feature = "_exhaustive-tests") || directed || index % 97 == 0).then_some(row)
        })
}

fn options(domain: u32) -> PowfOptions {
    let base = match domain {
        0 => PowfOptions::new(),
        1 => PowfOptions::new().admit_zero(),
        2 => PowfOptions::new().gamma(),
        _ => panic!("unknown test domain"),
    };
    base.reject_subnormals().caller()
}

fn expected_kind(code: u32) -> PowfErrorKind {
    match code {
        1 => PowfErrorKind::InvalidExponent,
        2 => PowfErrorKind::InvalidBase,
        3 => PowfErrorKind::OutsideApproximationRange,
        _ => panic!("unexpected oracle rejection stage"),
    }
}

const POS_UPGRADE: u128 = PowfOptions::new().reject_subnormals().upgrade().bits();
const ZERO_UPGRADE: u128 = PowfOptions::new()
    .admit_zero()
    .reject_subnormals()
    .upgrade()
    .bits();
const GAMMA_UPGRADE: u128 = PowfOptions::new()
    .gamma()
    .reject_subnormals()
    .upgrade()
    .bits();
const POS_CALLER: u128 = PowfOptions::new().reject_subnormals().caller().bits();
const ZERO_CALLER: u128 = PowfOptions::new()
    .admit_zero()
    .reject_subnormals()
    .caller()
    .bits();
const GAMMA_CALLER: u128 = PowfOptions::new()
    .gamma()
    .reject_subnormals()
    .caller()
    .bits();

// Runtime dispatch exists only in the test harness. Every arm instantiates
// one literal options integer all the way through the public API.
macro_rules! const_options {
    ($domain:expr, $execution:expr, |$cfg:ident| $body:expr) => {{
        match ($domain, $execution) {
            (0, Execution::Upgrade) => {
                const $cfg: u128 = POS_UPGRADE;
                $body
            }
            (1, Execution::Upgrade) => {
                const $cfg: u128 = ZERO_UPGRADE;
                $body
            }
            (2, Execution::Upgrade) => {
                const $cfg: u128 = GAMMA_UPGRADE;
                $body
            }
            (0, Execution::Caller) => {
                const $cfg: u128 = POS_CALLER;
                $body
            }
            (1, Execution::Caller) => {
                const $cfg: u128 = ZERO_CALLER;
                $body
            }
            (2, Execution::Caller) => {
                const $cfg: u128 = GAMMA_CALLER;
                $body
            }
            _ => panic!("legacy test uses restricted domains"),
        }
    }};
}

macro_rules! check {
    ($token:expr) => {{
        let token = $token;
        for domain in [1, 2] {
            let input = [0.0, 1.0, 4.0, 16.0];
            assert_eq!(
                options(domain)
                    .runtime()
                    .simd(
                        magetypes::simd::generic::f32x4::from_array_t(token, input),
                        0.5
                    )
                    .unwrap()
                    .to_array()
                    .map(f32::to_bits),
                [0.0_f32, 1.0, 2.0, 4.0].map(f32::to_bits),
            );
        }
        // Distinct accepted lanes catch packing/shuffle errors that splats miss.
        let bases = [
            0x3780_0000,
            0x3780_0001,
            0x3f7f_ffff,
            0x3f80_0000,
            0x3f80_0001,
            0x3f35_04f3,
            0x3fb5_04f3,
            0x4000_0000,
            0x4080_0000,
            0x477f_ffff,
            0x4780_0000,
        ];
        for domain in 0..3 {
            for exponent in [0.5_f32, 2.4, 4.0] {
                for execution in [Execution::Caller, Execution::Upgrade] {
                    let exponent = std::hint::black_box(exponent);
                    let opts = options(domain).execution(execution);
                    macro_rules! mixed_width {
                        ($ty:ident, $n:literal) => {{
                            let input: [f32; $n] =
                                std::hint::black_box(core::array::from_fn(|i| {
                                    f32::from_bits(if i == 0 && domain != 0 {
                                        0
                                    } else {
                                        bases[i % bases.len()]
                                    })
                                }));
                            let expected: [u32; $n] = core::array::from_fn(|i| {
                                let row = fixtures::POWF
                                    .iter()
                                    .find(|r| {
                                        r[0] == input[i].to_bits()
                                            && r[1] == exponent.to_bits()
                                            && r[4] == domain
                                    })
                                    .expect("independent mixed-lane fixture");
                                assert_eq!(row[3], 0);
                                row[2]
                            });
                            assert_eq!(
                                const_options!(domain, execution, |CFG| {
                                    magetypes::simd::generic::$ty::from_array_t(token, input)
                                        .try_powf_with::<CFG>(exponent)
                                })
                                .unwrap()
                                .to_array()
                                .map(f32::to_bits),
                                expected
                            );
                            assert_eq!(
                                opts.runtime()
                                    .simd(
                                        magetypes::simd::generic::$ty::from_array_t(token, input),
                                        exponent,
                                    )
                                    .unwrap()
                                    .to_array()
                                    .map(f32::to_bits),
                                expected
                            );
                        }};
                    }
                    mixed_width!(f32x4, 4);
                    mixed_width!(f32x8, 8);
                    #[cfg(feature = "w512")]
                    mixed_width!(f32x16, 16);
                }
            }
        }
        for &[base, exponent, expected, error, allow_zero] in oracle_rows() {
            let b = f32::from_bits(std::hint::black_box(base));
            let n = f32::from_bits(std::hint::black_box(exponent));
            let base_opts = options(allow_zero);
            macro_rules! width {
                ($ty:ident, $width:literal) => {{
                    let result = base_opts.runtime().simd(
                        magetypes::simd::generic::$ty::from_array_t(token, [b; $width]),
                        n,
                    );
                    for execution in [Execution::Caller, Execution::Upgrade] {
                        let constant = const_options!(allow_zero, execution, |CFG| {
                            magetypes::simd::generic::$ty::from_array_t(token, [b; $width])
                                .try_powf_with::<CFG>(n)
                        });
                        assert_eq!(
                            constant.map(|v| v.to_array().map(f32::to_bits)),
                            result.map(|v| v.to_array().map(f32::to_bits)),
                            "const flags base={base:08x} exponent={exponent:08x}"
                        );
                    }
                    if error == 0 {
                        assert_eq!(
                            result.unwrap().to_array().map(f32::to_bits),
                            [expected; $width],
                            "base={base:08x} exponent={exponent:08x}"
                        );
                    } else {
                        assert_eq!(
                            result.unwrap_err(),
                            PowfError {
                                kind: expected_kind(error),
                                lane_mask: ((1_u32 << $width) - 1) as u16
                            }
                        );
                    }
                }};
            }
            width!(f32x4, 4);
            width!(f32x8, 8);
            #[cfg(feature = "w512")]
            width!(f32x16, 16);
        }
    }};
}

#[test]
fn scalar_array_and_auto_have_identical_graph() {
    for &[base, exponent, expected, error, allow_zero] in oracle_rows() {
        let b = f32::from_bits(std::hint::black_box(base));
        let n = f32::from_bits(std::hint::black_box(exponent));
        for execution in [Execution::Caller, Execution::Upgrade] {
            let opts = options(allow_zero).execution(execution);
            let rt = opts.runtime();
            let result = rt.scalar(b, n);
            let constant = const_options!(allow_zero, execution, |CFG| Powf::<CFG>::scalar(b, n));
            assert_eq!(constant.map(f32::to_bits), result.map(f32::to_bits));
            assert_eq!(
                const_options!(allow_zero, execution, |CFG| {
                    Powf::<CFG>::scalar_with_token(archmage::ScalarToken, b, n)
                })
                .map(f32::to_bits),
                result.map(f32::to_bits)
            );
            assert_eq!(
                const_options!(allow_zero, execution, |CFG| Powf::<CFG>::array::<1>([b], n))
                    .map(|v| v.map(f32::to_bits)),
                result.map(|v| [v.to_bits()])
            );
            assert_eq!(
                rt.scalar_with_token(archmage::ScalarToken, b, n)
                    .map(f32::to_bits),
                result.map(f32::to_bits),
            );
            if error == 0 {
                assert_eq!(
                    result.unwrap().to_bits(),
                    expected,
                    "base={base:08x}, exponent={exponent:08x}"
                );
                assert_eq!(
                    rt.array([b; 4], n).unwrap().map(f32::to_bits),
                    [expected; 4]
                );
            } else {
                assert_eq!(
                    result.unwrap_err(),
                    PowfError {
                        kind: expected_kind(error),
                        lane_mask: 1
                    }
                );
            }
        }
    }
}

#[test]
fn mixed_lanes_reject_atomically_with_exact_mask() {
    let rt = options(0).runtime();
    let input = [2.0, f32::NAN, f32::from_bits(1), -1.0];
    assert_eq!(
        rt.array(input, 2.4).unwrap_err(),
        PowfError {
            kind: PowfErrorKind::InvalidBase,
            lane_mask: 0b1110
        }
    );
    assert_eq!(
        rt.array([2.0, 4.0, f32::MAX, f32::MIN_POSITIVE], 2.0)
            .unwrap_err(),
        PowfError {
            kind: PowfErrorKind::OutsideApproximationRange,
            lane_mask: 0b1100
        }
    );
    assert_eq!(
        rt.array([2.0; 4], f32::NAN).unwrap_err(),
        PowfError {
            kind: PowfErrorKind::InvalidExponent,
            lane_mask: 0b1111
        }
    );
    assert_eq!(
        rt.array([1.0; 3], 1.0).unwrap_err().kind,
        PowfErrorKind::UnsupportedWidth
    );
    assert_eq!(
        rt.array([], 1.0).unwrap_err().kind,
        PowfErrorKind::UnsupportedWidth
    );
    assert_eq!(
        rt.array([1.0; 32], 1.0).unwrap_err(),
        PowfError {
            kind: PowfErrorKind::UnsupportedWidth,
            lane_mask: 0
        }
    );
}

#[test]
fn caller_scalar_never_upgrades() {
    assert!(matches!(
        dispatch::select(archmage::ScalarToken, Execution::Caller, false),
        dispatch::Plan::Software
    ));
}

#[test]
fn automatic_plan_matches_requested_runtime_context() {
    let plan = dispatch::select(archmage::ScalarToken, Execution::Upgrade, false);
    std::eprintln!("powf upgrade plan: {plan:?}");
    if let Ok(expected) = std::env::var("ARCHMAGE_POWF_EXPECT_PLAN") {
        let matches = match expected.as_str() {
            "software" => matches!(plan, dispatch::Plan::Software),
            #[cfg(all(feature = "std", not(miri)))]
            "std" => matches!(plan, dispatch::Plan::Std),
            #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))]
            "v3" => matches!(plan, dispatch::Plan::V3(_)),
            #[cfg(all(target_arch = "x86_64", target_feature = "sse2", feature = "avx512"))]
            "v4" => matches!(plan, dispatch::Plan::V4(_)),
            #[cfg(all(target_arch = "x86_64", target_feature = "sse2", feature = "avx512"))]
            "v4x" => matches!(plan, dispatch::Plan::V4x(_)),
            #[cfg(target_arch = "aarch64")]
            "neon" => matches!(plan, dispatch::Plan::Neon(_)),
            #[cfg(target_arch = "wasm32")]
            "wasm-fused" => matches!(plan, dispatch::Plan::Wasm(_, true)),
            #[cfg(target_arch = "wasm32")]
            "wasm-software" => matches!(plan, dispatch::Plan::Wasm(_, false)),
            name => panic!("unknown requested plan {name}"),
        };
        assert!(matches, "expected {expected}, got {plan:?}");
    }
}

macro_rules! payloads {
    ($token:expr, $stride:expr) => {{
        let token = $token;
        for sign in [0, 0x8000_0000] {
            for payload in (1..=0x007f_ffff_u32).step_by($stride) {
                for rejected in [sign | 0x7f80_0000 | payload, sign | payload] {
                    let nan = f32::from_bits(std::hint::black_box(rejected));
                    macro_rules! width {
                        ($ty:ident, $n:literal, $domain:expr) => {{
                            let lane = payload as usize % $n;
                            let mut input = [1.0; $n];
                            input[lane] = nan;
                            let rt = options($domain).runtime();
                            let constant = const_options!($domain, Execution::Caller, |CFG| {
                                magetypes::simd::generic::$ty::from_array_t(token, input)
                                    .try_powf_with::<CFG>(2.4)
                            });
                            assert_eq!(
                                constant.unwrap_err(),
                                PowfError {
                                    kind: PowfErrorKind::InvalidBase,
                                    lane_mask: 1 << lane
                                }
                            );
                            let constant = const_options!($domain, Execution::Caller, |CFG| {
                                magetypes::simd::generic::$ty::from_array_t(token, [1.0; $n])
                                    .try_powf_with::<CFG>(nan)
                            });
                            assert_eq!(
                                constant.unwrap_err(),
                                PowfError {
                                    kind: PowfErrorKind::InvalidExponent,
                                    lane_mask: ((1_u32 << $n) - 1) as u16
                                }
                            );
                            assert_eq!(
                                rt.simd(
                                    magetypes::simd::generic::$ty::from_array_t(token, input),
                                    2.4,
                                )
                                .unwrap_err(),
                                PowfError {
                                    kind: PowfErrorKind::InvalidBase,
                                    lane_mask: 1 << lane
                                },
                                "base_bits={rejected:08x}, width={}, domain={}",
                                $n,
                                $domain
                            );
                            assert_eq!(
                                rt.simd(
                                    magetypes::simd::generic::$ty::from_array_t(token, [1.0; $n]),
                                    nan,
                                )
                                .unwrap_err(),
                                PowfError {
                                    kind: PowfErrorKind::InvalidExponent,
                                    lane_mask: ((1_u32 << $n) - 1) as u16,
                                },
                                "exponent_bits={rejected:08x}, width={}, domain={}",
                                $n,
                                $domain
                            );
                        }};
                    }
                    for domain in 0..3 {
                        width!(f32x4, 4, domain);
                        width!(f32x8, 8, domain);
                        #[cfg(feature = "w512")]
                        width!(f32x16, 16, domain);
                    }
                }
            }
        }
    }};
}

#[archmage::attune(_*_t, +v4(cfg(avx512)), +v4x(cfg(avx512)))]
fn run_rational(token: Token, expected: &str) {
    assert_eq!(
        <Token as archmage::SimdToken>::NAME,
        expected,
        "requested backend did not execute"
    );
    check!(token);
}

#[archmage::attune(_*_t, +v4(cfg(avx512)), +v4x(cfg(avx512)))]
fn run_payloads(token: Token, expected: &str, stride: usize) {
    assert_eq!(
        <Token as archmage::SimdToken>::NAME,
        expected,
        "requested backend did not execute"
    );
    payloads!(token, stride);
}

macro_rules! require_tier {
    ($family:ident $(, $argument:expr)*) => {{
        use archmage::SimdToken;
        let tier = std::env::var("ARCHMAGE_POWF_TIER").unwrap_or_else(|_| "scalar".into());
        match tier.as_str() {
            "scalar" => archmage::attuned!($family(archmage::ScalarToken::NAME $(, $argument)*), [_scalar_t]),
            #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))]
            "v3" => archmage::attuned!($family(archmage::X64V3Token::NAME $(, $argument)*), [_v3_t, _scalar_t]),
            #[cfg(all(target_arch = "x86_64", target_feature = "sse2", feature = "avx512"))]
            "v4" => archmage::attuned!($family(archmage::X64V4Token::NAME $(, $argument)*), [_v4_t, _scalar_t]),
            #[cfg(all(target_arch = "x86_64", target_feature = "sse2", feature = "avx512"))]
            "v4x" => archmage::attuned!($family(archmage::X64V4xToken::NAME $(, $argument)*), [_v4x_t, _scalar_t]),
            #[cfg(target_arch = "aarch64")]
            "neon" => archmage::attuned!($family(archmage::NeonToken::NAME $(, $argument)*), [_neon_t, _scalar_t]),
            #[cfg(target_arch = "wasm32")]
            "wasm128" => archmage::attuned!($family(archmage::Wasm128Token::NAME $(, $argument)*), [_wasm128_t, _scalar_t]),
            other => panic!("unsupported requested powf backend {other}"),
        }
    }};
}

#[test]
fn rational_graph_and_selected_backend() {
    require_tier!(run_rational);
}

#[test]
fn nan_sign_payload_and_subnormal_families_reject_with_exact_masks() {
    let stride: usize = std::env::var("ARCHMAGE_NAN_STRIDE")
        .unwrap_or_else(|_| "65537".into())
        .parse()
        .unwrap();
    assert!(stride > 0);
    require_tier!(run_payloads, stride);
}

#[test]
fn const_array_width_and_rejection_precedence() {
    const GAMMA_C: u128 = PowfOptions::new().gamma().caller().bits();
    const CALLER_CHECKED_REJECT: u128 = PowfOptions::new().reject_subnormals().caller().bits();
    assert_eq!(
        Powf::<GAMMA_C>::array::<0>([], f32::NAN).unwrap_err(),
        PowfError {
            kind: PowfErrorKind::UnsupportedWidth,
            lane_mask: 0
        }
    );
    assert_eq!(
        Powf::<GAMMA_C>::array::<3>([1.0; 3], f32::NAN).unwrap_err(),
        PowfError {
            kind: PowfErrorKind::UnsupportedWidth,
            lane_mask: 0
        }
    );
    assert_eq!(
        Powf::<GAMMA_C>::array::<32>([1.0; 32], f32::NAN).unwrap_err(),
        PowfError {
            kind: PowfErrorKind::UnsupportedWidth,
            lane_mask: 0
        }
    );
    assert_eq!(
        Powf::<GAMMA_C>::array::<4>([f32::NAN; 4], f32::NAN).unwrap_err(),
        PowfError {
            kind: PowfErrorKind::InvalidExponent,
            lane_mask: 15
        }
    );
    assert_eq!(
        Powf::<CALLER_CHECKED_REJECT>::array::<4>([2.0, f32::NAN, f32::from_bits(1), -1.0], 2.4)
            .unwrap_err(),
        PowfError {
            kind: PowfErrorKind::InvalidBase,
            lane_mask: 14
        }
    );
    assert_eq!(
        Powf::<CALLER_CHECKED_REJECT>::array::<4>([2.0, 4.0, f32::MAX, f32::MIN_POSITIVE], 2.0)
            .unwrap_err(),
        PowfError {
            kind: PowfErrorKind::OutsideApproximationRange,
            lane_mask: 12
        }
    );
}

#[test]
fn const_builder_encodes_each_supported_configuration() {
    for base in [
        PowfOptions::new(),
        PowfOptions::new().admit_zero(),
        PowfOptions::new().gamma(),
        PowfOptions::new().positive_gamma(),
        PowfOptions::new()
            .base_range(1.0e-4, 65536.0)
            .exponent_range(-4.0, 4.0)
            .clamp_output(),
        PowfOptions::new().full_domain().highp(),
    ] {
        for execution in [Execution::Upgrade, Execution::Caller] {
            for portability in [Portability::BitExact, Portability::BackendDependent] {
                for validation in [Validation::Checked, Validation::AssumeValid] {
                    let opts = base
                        .execution(execution)
                        .portability(portability)
                        .validation(validation);
                    if !opts.is_valid() {
                        continue;
                    }
                    let bits = opts.bits();
                    assert_eq!(PowfOptions::from_bits(bits), Some(opts));
                }
            }
        }
    }
    assert_eq!(PowfOptions::from_bits(0), None);
    assert_eq!(
        PowfOptions::from_bits(crate::expf::ExpfOptions::new().bits()),
        None
    );
    assert_eq!(
        PowfOptions::from_bits(crate::logf::LogfOptions::new().bits()),
        None
    );
    assert_eq!(
        PowfOptions::from_bits(crate::cbrtf::CbrtfOptions::new().bits()),
        None
    );
}

#[test]
fn new_policy_presets_and_invalid_runtime_combinations() {
    for opts in [
        PowfOptions::new().gamma().midp().bit_exact(),
        PowfOptions::new().gamma().lowp().bit_exact(),
        PowfOptions::new().gamma().midp().backend_dependent(),
        PowfOptions::new().gamma().lowp().backend_dependent(),
    ] {
        let rt = opts.runtime();
        assert_eq!(
            rt.array([0., 1., 4., 16.], 0.).unwrap()[0].to_bits(),
            1f32.to_bits()
        );
        let error = rt
            .array([0., f32::NAN, -0., f32::from_bits(1)], 2.4)
            .unwrap_err();
        assert_eq!(
            error,
            PowfError {
                kind: PowfErrorKind::InvalidBase,
                lane_mask: 6
            }
        );
        assert_eq!(
            rt.scalar(f32::from_bits(1), 2.4).unwrap().to_bits(),
            0.0_f32.to_bits()
        );
    }
    for opts in [
        PowfOptions::new().full_domain(),
        PowfOptions::new().lowp().full_domain(),
    ] {
        assert_eq!(
            opts.runtime().scalar(1., 2.4).unwrap_err(),
            PowfError {
                kind: PowfErrorKind::UnsupportedOptions,
                lane_mask: 0
            }
        );
    }
    #[cfg(not(feature = "std"))]
    assert_eq!(
        PowfOptions::new()
            .full_domain()
            .highp()
            .backend_dependent()
            .runtime()
            .scalar(1., 2.4)
            .unwrap_err()
            .kind,
        PowfErrorKind::UnsupportedOptions
    );
}

#[test]
fn lowp_admitted_zero_survives_huge_exponent_in_both_const_modes() {
    const PORTABLE: u128 = PowfOptions::new().admit_zero().lowp().caller().bits();
    const BACKEND: u128 = PowfOptions::new()
        .admit_zero()
        .lowp()
        .backend_dependent()
        .caller()
        .bits();
    for n in [1_073_741_824., f32::MAX] {
        assert_eq!(Powf::<PORTABLE>::scalar(0., n).unwrap().to_bits(), 0);
        assert_eq!(Powf::<BACKEND>::scalar(0., n).unwrap().to_bits(), 0);
    }
}

#[test]
#[cfg(feature = "std")]
fn std_highp_full_domain_and_restricted_masks() {
    const STD: u128 = PowfOptions::new()
        .full_domain()
        .highp()
        .backend_dependent()
        .bits();
    let result = Powf::<STD>::array::<4>([-2., -0., f32::INFINITY, f32::NAN], 3.).unwrap();
    // Std power has unspecified precision, including under Miri. Only its
    // admitted domain and sign/classification are the HIGHP contract here.
    assert!(result[0].is_normal() && result[0].is_sign_negative());
    assert_eq!(result[1].to_bits(), (-0.0f32).to_bits());
    assert_eq!(result[2], f32::INFINITY);
    assert!(result[3].is_nan());
    assert_eq!(
        Powf::<STD>::array::<4>([f32::NAN, 0., -0., f32::INFINITY], 0.).unwrap(),
        [1.; 4]
    );
    assert_eq!(Powf::<STD>::scalar(0., -1.).unwrap(), f32::INFINITY);
    let tiny = Powf::<STD>::scalar(f32::from_bits(1), 1.).unwrap();
    assert!(tiny.is_subnormal() || tiny == 0.);
    assert_eq!(
        Powf::<STD>::array::<3>([1.; 3], 2.).unwrap_err().kind,
        PowfErrorKind::UnsupportedWidth
    );
    let rt = PowfOptions::new()
        .reject_subnormals()
        .highp()
        .backend_dependent()
        .runtime();
    assert_eq!(
        rt.array([2., -1., f32::from_bits(1), f32::NAN], 2.)
            .unwrap_err(),
        PowfError {
            kind: PowfErrorKind::InvalidBase,
            lane_mask: 14
        }
    );
    assert_eq!(
        rt.array([2., 4., f32::MAX, f32::MIN_POSITIVE], 2.)
            .unwrap_err(),
        PowfError {
            kind: PowfErrorKind::OutsideApproximationRange,
            lane_mask: 12
        }
    );
}

#[test]
fn positive_gamma_preserves_nonzero_graph_and_rejects_zero() {
    fn check<const PG: u128, const G: u128>(options: PowfOptions) {
        assert_eq!(options.bits(), PG);
        let is_std_highp = options.is_highp() && options.is_backend();
        let is_checked = !options.assume_valid();
        let rt = options.runtime();
        let compare = |left: [f32; 4], right: [f32; 4]| {
            if is_std_highp {
                // This provider delegates to std::powf, whose precision is
                // unspecified and can vary between calls under Miri. This
                // fixture checks ordinary results, not a portable std graph.
                for (a, b) in left.into_iter().zip(right) {
                    assert!(a.is_normal() && b.is_normal());
                    assert!((a - b).abs() <= a.abs() * 0.000_01);
                }
            } else {
                assert_eq!(
                    left.map(f32::to_bits),
                    right.map(f32::to_bits),
                    "options={options:?}"
                );
            }
        };
        for n in [0., -0., 0.5, 2.4, 4.] {
            let input = [1.0 / 65_536.0, 0.75, 1., 65_536.0];
            let got = Powf::<PG>::array::<4>(input, n).unwrap();
            let gamma = Powf::<G>::array::<4>(input, n).unwrap();
            compare(got, gamma);
            for (x, y) in input.into_iter().zip(got) {
                compare(
                    [Powf::<PG>::scalar_with_token(archmage::ScalarToken, x, n).unwrap(); 4],
                    [y; 4],
                );
            }
            compare(got, rt.array(input, n).unwrap());
            if is_checked {
                compare(
                    [rt.scalar(f32::from_bits(1), n).unwrap(); 4],
                    [rt.scalar(input[0], n).unwrap(); 4],
                );
                for x in [0., -0., f32::NAN, f32::INFINITY] {
                    assert_eq!(
                        Powf::<PG>::scalar_with_token(archmage::ScalarToken, x, n).unwrap_err(),
                        PowfError {
                            kind: PowfErrorKind::InvalidBase,
                            lane_mask: 1
                        }
                    );
                    assert_eq!(
                        Powf::<PG>::array::<4>([1., x, 1., x], n).unwrap_err(),
                        PowfError {
                            kind: PowfErrorKind::InvalidBase,
                            lane_mask: 10
                        }
                    );
                }
            }
        }
    }

    macro_rules! pair {
        ($prec:ident, $exec:ident, $port:ident, $val:ident) => {{
            const PG_OPTS: PowfOptions = PowfOptions::new()
                .positive_gamma()
                .$prec()
                .$exec()
                .$port()
                .$val();
            const G_OPTS: PowfOptions = PowfOptions::new().gamma().$prec().$exec().$port().$val();
            check::<{ PG_OPTS.bits() }, { G_OPTS.bits() }>(PG_OPTS);
        }};
    }

    macro_rules! sweep_exec_val {
        ($prec:ident, $port:ident) => {{
            pair!($prec, upgrade, $port, checked);
            pair!($prec, caller, $port, checked);
            pair!($prec, upgrade, $port, unchecked);
            pair!($prec, caller, $port, unchecked);
        }};
    }

    sweep_exec_val!(midp, bit_exact);
    sweep_exec_val!(midp, backend_dependent);
    sweep_exec_val!(lowp, bit_exact);
    sweep_exec_val!(lowp, backend_dependent);
    sweep_exec_val!(highp, bit_exact);
    #[cfg(feature = "std")]
    sweep_exec_val!(highp, backend_dependent);
}

#[cfg(all(
    target_arch = "x86_64",
    target_feature = "sse2",
    feature = "avx512",
    feature = "std"
))]
#[test]
fn avx512_selector_upgrades_and_falls_back_across_all_families() {
    use archmage::{SimdToken, X64V3Token, X64V4Token, X64V4xToken};

    struct RestoreV4;
    impl Drop for RestoreV4 {
        fn drop(&mut self) {
            let _ = X64V4xToken::dangerously_disable_token_process_wide(false);
            let _ = X64V4Token::dangerously_disable_token_process_wide(false);
        }
    }

    let _lock = archmage::testing::lock_token_testing();
    let _restore = RestoreV4;
    let _ = X64V4xToken::dangerously_disable_token_process_wide(false);
    let _ = X64V4Token::dangerously_disable_token_process_wide(false);

    let Some(v3) = X64V3Token::summon() else {
        return;
    };

    // Execution::Caller and narrow (widen_v3 = false) calls always retain V3.
    assert!(matches!(
        super::dispatch::select(v3, Execution::Caller, true),
        super::dispatch::Plan::V3(_)
    ));
    assert!(matches!(
        super::dispatch::select(v3, Execution::Upgrade, false),
        super::dispatch::Plan::V3(_)
    ));
    assert!(matches!(
        super::dispatch::select_highp(v3, Execution::Caller, true),
        super::dispatch::Plan::V3(_)
    ));
    assert!(matches!(
        crate::expf::dispatch::select(v3, Execution::Caller, false, true),
        crate::expf::dispatch::Plan::V3(_)
    ));
    assert!(matches!(
        crate::logf::dispatch::select(v3, Execution::Caller, false, true),
        crate::logf::dispatch::Plan::V3(_)
    ));
    assert!(matches!(
        crate::cbrtf::dispatch::select(v3, Execution::Caller, true),
        crate::cbrtf::dispatch::Plan::V3(_)
    ));

    // When V4x is available on the host, Execution::Upgrade + widen_v3 = true selects V4x.
    if X64V4xToken::summon().is_some() {
        assert!(matches!(
            super::dispatch::select(v3, Execution::Upgrade, true),
            super::dispatch::Plan::V4x(_)
        ));
        assert!(matches!(
            super::dispatch::select_relaxed(v3, Execution::Upgrade, true),
            super::dispatch::Plan::V4x(_)
        ));
        assert!(matches!(
            super::dispatch::select_highp(v3, Execution::Upgrade, true),
            super::dispatch::Plan::V4x(_)
        ));
        assert!(matches!(
            crate::expf::dispatch::select(v3, Execution::Upgrade, false, true),
            crate::expf::dispatch::Plan::V4x(_)
        ));
        assert!(matches!(
            crate::logf::dispatch::select(v3, Execution::Upgrade, false, true),
            crate::logf::dispatch::Plan::V4x(_)
        ));
        assert!(matches!(
            crate::cbrtf::dispatch::select(v3, Execution::Upgrade, true),
            crate::cbrtf::dispatch::Plan::V4x(_)
        ));
    }

    // Disabling V4x while keeping V4 active selects Plan::V4.
    if X64V4xToken::dangerously_disable_token_process_wide(true).is_ok()
        && X64V4Token::summon().is_some()
    {
        assert!(matches!(
            super::dispatch::select(v3, Execution::Upgrade, true),
            super::dispatch::Plan::V4(_)
        ));
        assert!(matches!(
            super::dispatch::select_highp(v3, Execution::Upgrade, true),
            super::dispatch::Plan::V4(_)
        ));
        assert!(matches!(
            crate::expf::dispatch::select(v3, Execution::Upgrade, false, true),
            crate::expf::dispatch::Plan::V4(_)
        ));
        assert!(matches!(
            crate::logf::dispatch::select(v3, Execution::Upgrade, false, true),
            crate::logf::dispatch::Plan::V4(_)
        ));
        assert!(matches!(
            crate::cbrtf::dispatch::select(v3, Execution::Upgrade, true),
            crate::cbrtf::dispatch::Plan::V4(_)
        ));
    }

    // Disabling V4 as well falls back cleanly to Plan::V3.
    if X64V4xToken::dangerously_disable_token_process_wide(true).is_ok()
        && X64V4Token::dangerously_disable_token_process_wide(true).is_ok()
    {
        assert!(matches!(
            super::dispatch::select(v3, Execution::Upgrade, true),
            super::dispatch::Plan::V3(_)
        ));
        assert!(matches!(
            super::dispatch::select_highp(v3, Execution::Upgrade, true),
            super::dispatch::Plan::V3(_)
        ));
        assert!(matches!(
            crate::expf::dispatch::select(v3, Execution::Upgrade, false, true),
            crate::expf::dispatch::Plan::V3(_)
        ));
        assert!(matches!(
            crate::logf::dispatch::select(v3, Execution::Upgrade, false, true),
            crate::logf::dispatch::Plan::V3(_)
        ));
        assert!(matches!(
            crate::cbrtf::dispatch::select(v3, Execution::Upgrade, true),
            crate::cbrtf::dispatch::Plan::V3(_)
        ));
    }
}

#[test]
fn malformed_u128_words_are_rejected_across_all_families() {
    use crate::{cbrtf::CbrtfOptions, expf::ExpfOptions, log1pf::Log1pfOptions, logf::LogfOptions};

    let one_bf16 = 0x3f80_u128; // 1.0
    let two_bf16 = 0x4000_u128; // 2.0
    let neg_zero_bf16 = 0x8000_u128;
    let inf_bf16 = 0x7f80_u128;
    let nan_bf16 = 0x7fc0_u128;
    let sub_bf16 = 0x0001_u128;

    let p_base = PowfOptions::new().reject_subnormals().bits();
    // Out-of-range enum discriminants (PowfDomain = 10, Subnormals = 3, Validation = 4, Precision = 3, EXP_MODE = 3).
    assert_eq!(
        PowfOptions::from_bits((p_base & !(0x1f << 4)) | (10 << 4)),
        None
    );
    assert_eq!(
        PowfOptions::from_bits((p_base & !(0x7 << 9)) | (3 << 9)),
        None
    );
    assert_eq!(
        PowfOptions::from_bits((p_base & !(0x7 << 12)) | (4 << 12)),
        None
    );
    assert_eq!(
        PowfOptions::from_bits((p_base & !(0x7 << 15)) | (3 << 15)),
        None
    );
    assert_eq!(PowfOptions::from_bits(p_base | (3 << 23)), None);
    // Reserved bits [26..64].
    assert_eq!(PowfOptions::from_bits(p_base | (1_u128 << 26)), None);
    assert_eq!(PowfOptions::from_bits(p_base | (1_u128 << 63)), None);
    // AllFloats combined with subnormal override or custom base/exp.
    let p_full = PowfOptions::new().full_domain().highp().bits();
    assert_eq!(PowfOptions::from_bits(p_full | (1 << 9)), None);
    assert_eq!(
        PowfOptions::from_bits(p_full | (2 << 23) | ((1.0_f32.to_bits() as u128) << 96)),
        None
    );
    // Base payload without HAS_CUSTOM_BASE, or inverted / subnormal / -0.0 / Inf / NaN with HAS_CUSTOM_BASE.
    assert_eq!(PowfOptions::from_bits(p_base | (one_bf16 << 64)), None);
    assert_eq!(
        PowfOptions::from_bits(p_base | (1 << 22) | (two_bf16 << 64) | (one_bf16 << 80)),
        None
    );
    assert_eq!(
        PowfOptions::from_bits(p_base | (1 << 22) | (sub_bf16 << 64) | (one_bf16 << 80)),
        None
    );
    assert_eq!(
        PowfOptions::from_bits(p_base | (1 << 22) | (one_bf16 << 64) | (inf_bf16 << 80)),
        None
    );
    assert_eq!(
        PowfOptions::from_bits(p_base | (1 << 22) | (one_bf16 << 64) | (nan_bf16 << 80)),
        None
    );
    // Exponent slot without EXP_MODE, RangeBf16 with -0.0 / Inf / NaN / inverted / subnormal-only,
    // and ConstF32 with -0.0 / Inf / NaN / subnormal-under-Reject.
    assert_eq!(PowfOptions::from_bits(p_base | (one_bf16 << 96)), None);
    assert_eq!(
        PowfOptions::from_bits(p_base | (1 << 23) | (neg_zero_bf16 << 96) | (one_bf16 << 112)),
        None
    );
    assert_eq!(
        PowfOptions::from_bits(p_base | (1 << 23) | (one_bf16 << 96) | (inf_bf16 << 112)),
        None
    );
    assert_eq!(
        PowfOptions::from_bits(p_base | (1 << 23) | (one_bf16 << 96) | (nan_bf16 << 112)),
        None
    );
    assert_eq!(
        PowfOptions::from_bits(p_base | (1 << 23) | (sub_bf16 << 96) | (sub_bf16 << 112)),
        None
    );
    assert_eq!(
        PowfOptions::from_bits(p_base | (2 << 23) | (0x8000_0000_u128 << 96)),
        None
    );
    assert_eq!(
        PowfOptions::from_bits(p_base | (2 << 23) | ((f32::INFINITY.to_bits() as u128) << 96)),
        None
    );
    assert_eq!(
        PowfOptions::from_bits(p_base | (2 << 23) | ((f32::NAN.to_bits() as u128) << 96)),
        None
    );
    assert_eq!(
        PowfOptions::from_bits(p_base | (2 << 23) | (1_u128 << 96)),
        None
    );

    // Expf, Logf, Log1pf, Cbrtf: reserved bits, out-of-range discriminants, absent HAS_CUSTOM_RANGE payloads,
    // -0.0, NaN, Inf, inverted, and MAX_CBRT_BF16 bound check.
    let e_base = ExpfOptions::new().bits();
    assert_eq!(
        ExpfOptions::from_bits((e_base & !(0x1f << 4)) | (7 << 4)),
        None
    );
    assert_eq!(ExpfOptions::from_bits(e_base | (1_u128 << 20)), None);
    assert_eq!(ExpfOptions::from_bits(e_base | (1_u128 << 96)), None);
    assert_eq!(ExpfOptions::from_bits(e_base | (one_bf16 << 64)), None);
    assert_eq!(
        ExpfOptions::from_bits(e_base | (1 << 19) | (neg_zero_bf16 << 64) | (one_bf16 << 80)),
        None
    );
    assert_eq!(
        ExpfOptions::from_bits(e_base | (1 << 19) | (nan_bf16 << 64) | (one_bf16 << 80)),
        None
    );
    assert_eq!(
        ExpfOptions::from_bits(e_base | (1 << 19) | (one_bf16 << 64) | (inf_bf16 << 80)),
        None
    );
    assert_eq!(
        ExpfOptions::from_bits(e_base | (1 << 19) | (two_bf16 << 64) | (one_bf16 << 80)),
        None
    );

    for (l_base, decode) in [
        (
            LogfOptions::new().bits(),
            (|b| LogfOptions::from_bits(b).is_some()) as fn(u128) -> bool,
        ),
        (Log1pfOptions::new().bits(), |b| {
            Log1pfOptions::from_bits(b).is_some()
        }),
    ] {
        assert!(!decode(l_base | (1_u128 << 24)));
        assert!(!decode(l_base | (1_u128 << 96)));
        assert!(!decode(l_base | (one_bf16 << 64)));
        assert!(!decode(
            l_base | (1 << 22) | (neg_zero_bf16 << 64) | (one_bf16 << 80)
        ));
        assert!(!decode(
            l_base | (1 << 22) | (nan_bf16 << 64) | (one_bf16 << 80)
        ));
        assert!(!decode(
            l_base | (1 << 22) | (one_bf16 << 64) | (inf_bf16 << 80)
        ));
        assert!(!decode(
            l_base | (1 << 22) | (two_bf16 << 64) | (one_bf16 << 80)
        ));
    }

    let c_base = CbrtfOptions::new().bits();
    assert_eq!(
        CbrtfOptions::from_bits((c_base & !(0x1f << 4)) | (5 << 4)),
        None
    );
    assert_eq!(CbrtfOptions::from_bits(c_base | (1_u128 << 23)), None);
    assert_eq!(CbrtfOptions::from_bits(c_base | (1_u128 << 96)), None);
    assert_eq!(CbrtfOptions::from_bits(c_base | (one_bf16 << 64)), None);
    assert_eq!(
        CbrtfOptions::from_bits(c_base | (1 << 22) | (neg_zero_bf16 << 64) | (one_bf16 << 80)),
        None
    );
    assert_eq!(
        CbrtfOptions::from_bits(c_base | (1 << 22) | (sub_bf16 << 64) | (sub_bf16 << 80)),
        None
    );
    // MAX_BF16 (0x7f7f) exceeds MAX_CBRT_BF16 (0x7ed5) and must be rejected on CbrtfOptions.
    assert_eq!(
        CbrtfOptions::from_bits(c_base | (1 << 22) | (one_bf16 << 64) | (0x7f7f_u128 << 80)),
        None
    );
    // Cross-family magic rejection for Log1pfOptions too.
    assert_eq!(PowfOptions::from_bits(Log1pfOptions::new().bits()), None);
    assert_eq!(LogfOptions::from_bits(Log1pfOptions::new().bits()), None);
    assert_eq!(Log1pfOptions::from_bits(LogfOptions::new().bits()), None);
}

#[test]
#[should_panic(expected = "full_domain requires PowfPrecision::Highp")]
fn decode_const_surfaces_specific_validate_message() {
    let bad = PowfOptions::new().full_domain().bits();
    let _ = PowfOptions::decode_const(bad);
}

#[test]
fn prepare_exponent_clamps_one_sided_subnormal_bounds_inward() {
    let pos_opts = PowfOptions::new()
        .exponent_range(f32::MIN_POSITIVE / 2.0, f32::MIN_POSITIVE)
        .clamp_out_of_bounds();
    for exp_in in [f32::NEG_INFINITY, -1.0, -0.0, 0.0, f32::from_bits(1)] {
        let prepared = super::const_api::prepare_exponent::<1>(pos_opts, exp_in)
            .unwrap()
            .unwrap();
        assert_eq!(prepared.to_bits(), f32::MIN_POSITIVE.to_bits());
    }

    let neg_opts = PowfOptions::new()
        .exponent_range(-f32::MIN_POSITIVE, -f32::MIN_POSITIVE / 2.0)
        .clamp_out_of_bounds();
    for exp_in in [-f32::from_bits(1), -0.0, 0.0, 1.0, f32::INFINITY] {
        let prepared = super::const_api::prepare_exponent::<1>(neg_opts, exp_in)
            .unwrap()
            .unwrap();
        assert_eq!(prepared.to_bits(), (-f32::MIN_POSITIVE).to_bits());
    }
}

#[cfg(all(test, target_arch = "x86_64", target_feature = "sse2", not(miri)))]
mod registry_token_dispatch {
    use super::super::dispatch::{select, select_highp, select_relaxed};
    use crate::Execution;
    use crate::{
        cbrtf::dispatch as cbrtf, expf::dispatch as expf, log1pf::Log1pf, log1pf::Log1pfOptions,
        logf::dispatch as logf,
    };
    use archmage::{
        Avx512Fp16Token, IntoConcreteToken, SimdToken, X64V3CryptoToken, X64V3GfniCryptoToken,
        X64V3VnniToken,
    };

    fn check_dispatch(token: impl IntoConcreteToken, expected: impl IntoConcreteToken) {
        let caller = Execution::Caller;
        let upgrade = Execution::Upgrade;
        let token_name = token.name();
        macro_rules! same_tier {
            ($select:path, $execution:expr, $($options:expr),+) => {
                assert_eq!(
                    core::mem::discriminant(&$select(token, $execution, $($options),+)),
                    core::mem::discriminant(&$select(expected, $execution, $($options),+)),
                    "{token_name} in {} with {:?}", stringify!($select), $execution,
                )
            };
        }
        for (execution, widen) in [
            (caller, false),
            (caller, true),
            (upgrade, false),
            (upgrade, true),
        ] {
            same_tier!(cbrtf::select, execution, widen);
            same_tier!(expf::select, execution, false, widen);
            same_tier!(expf::select, execution, true, widen);
            same_tier!(logf::select, execution, false, widen);
            same_tier!(logf::select, execution, true, widen);
            same_tier!(select, execution, widen);
            same_tier!(select_relaxed, execution, widen);
            same_tier!(select_highp, execution, widen);
        }

        // Log1pf shares Logf's selector and calls its OP=3 slice kernels.
        type CallerLog1p = Log1pf<{ Log1pfOptions::new().caller().bits() }>;
        let input = core::array::from_fn::<_, 19, _>(|lane| lane as f32 * 0.125 - 0.75);
        let (mut actual, mut reference) = ([0.0; 19], [0.0; 19]);
        CallerLog1p::slice_with_token(token, &input, &mut actual).unwrap();
        CallerLog1p::slice_with_token(expected, &input, &mut reference).unwrap();
        assert_eq!(
            actual.map(f32::to_bits),
            reference.map(f32::to_bits),
            "{token_name}"
        );
        std::eprintln!("Checked {token_name} against {}", expected.name());
    }

    #[test]
    fn v3_extensions_dispatch_like_v3() {
        #[cfg(all(feature = "avx512", feature = "std"))]
        let _lock = archmage::testing::lock_token_testing();
        if let Some(token) = X64V3CryptoToken::summon() {
            check_dispatch(token, token.v3());
        }
        if let Some(token) = X64V3GfniCryptoToken::summon() {
            check_dispatch(token, token.v3());
        }
        if let Some(token) = X64V3VnniToken::summon() {
            check_dispatch(token, token.v3());
        }
    }

    #[test]
    fn fp16_dispatches_like_the_available_base_tier() {
        #[cfg(all(feature = "avx512", feature = "std"))]
        let _lock = archmage::testing::lock_token_testing();
        if let Some(token) = Avx512Fp16Token::summon() {
            #[cfg(feature = "avx512")]
            check_dispatch(token, token.v4());
            #[cfg(not(feature = "avx512"))]
            check_dispatch(token, token.v3());
        }
    }
}