arcweight 0.3.0

A high-performance, modular library for weighted finite state transducers with comprehensive examples and benchmarks
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
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
//! SIMD-optimized operations for FST computations.
//!
//! This module provides vectorized implementations of common FST operations
//! to improve performance on modern CPUs with SIMD capabilities. Operations
//! are automatically dispatched to the best available instruction set at runtime.
//!
//! # Overview
//!
//! | Component | Purpose | Speedup |
//! |-----------|---------|---------|
//! | [`SimdOps`] | Parallel semiring operations | 2-8x |
//! | [`vectorized_arcs`] | Batch arc transformations | 2-4x |
//! | [`prefetch`] | Cache prefetching hints | 10-30% latency |
//!
//! # SIMD Instruction Set Levels
//!
//! The implementation supports multiple SIMD instruction sets with automatic
//! runtime dispatch based on CPU feature detection:
//!
//! | Level | Register Width | Elements/Op | Throughput |
//! |-------|----------------|-------------|------------|
//! | SSE | 128-bit | 4 x f32 | Baseline |
//! | AVX2 | 256-bit | 8 x f32 | 2x SSE |
//! | AVX-512 | 512-bit | 16 x f32 | 4x SSE |
//!
//! Runtime detection automatically selects the best available implementation
//! without requiring recompilation.
//!
//! # Performance Characteristics
//!
//! SIMD acceleration is most effective when:
//! - Processing batches of 8+ weights simultaneously
//! - Data is contiguous in memory (cache-friendly)
//! - Operations are compute-bound rather than memory-bound
//!
//! For small batches (<8 elements), scalar operations may be faster due
//! to SIMD setup overhead.
//!
//! # Safety
//!
//! The SIMD implementations use `unsafe` code for direct hardware access.
//! All public APIs provide safe wrappers that:
//! - Validate input slice lengths match
//! - Handle non-SIMD-aligned data with scalar fallbacks
//! - Process remaining elements when batch size is not a multiple of SIMD width
//!
//! # References
//!
//! - Intel. 2023. Intel 64 and IA-32 Architectures Optimization Reference Manual.
//!   <https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html>
//!
//! - Agner Fog. 2023. Optimizing subroutines in assembly language.
//!   <https://www.agner.org/optimize/>

use crate::semiring::Semiring;
use num_traits::Zero;

/// SIMD-optimized operations for weight computations.
///
/// Provides vectorized implementations of semiring operations that process
/// multiple weights in parallel using SIMD instructions. Implementations
/// automatically dispatch to the best available instruction set (SSE, AVX2,
/// or AVX-512) based on runtime CPU feature detection.
///
/// # Supported Semirings
///
/// | Semiring | Plus Operation | Times Operation |
/// |----------|----------------|-----------------|
/// | Tropical | SIMD min | SIMD add |
/// | Log | SIMD log-sum-exp | SIMD add |
///
/// # Performance
///
/// - **Throughput**: 4-16x scalar operations depending on SIMD level
/// - **Latency**: 3-5 cycles for most operations
/// - **Alignment**: Unaligned loads supported (slight performance penalty)
///
/// # Examples
///
/// ```rust
/// use arcweight::prelude::*;
/// use arcweight::optimization::SimdOps;
///
/// // Batch tropical weight operations
/// let left = vec![TropicalWeight::new(1.0), TropicalWeight::new(2.0)];
/// let right = vec![TropicalWeight::new(3.0), TropicalWeight::new(4.0)];
/// let mut result = vec![TropicalWeight::zero(); 2];
///
/// TropicalWeight::simd_plus(&left, &right, &mut result);
/// assert_eq!(*result[0].value(), 1.0); // min(1.0, 3.0) = 1.0
/// ```
pub trait SimdOps<W: Semiring> {
    /// Perform parallel semiring addition (plus operation) on weight arrays.
    ///
    /// Computes `result[i] = left[i] ⊕ right[i]` for all indices using SIMD
    /// vectorization. For tropical semiring, this computes element-wise minimum.
    /// For log semiring, this computes log-sum-exp.
    ///
    /// # Arguments
    ///
    /// * `left` - Left operand weights
    /// * `right` - Right operand weights (must have same length as `left`)
    /// * `result` - Output array for results (must have same length as inputs)
    ///
    /// # Panics
    ///
    /// Panics if the three slices do not have the same length.
    ///
    /// # Complexity
    ///
    /// - **Time**: O(n / SIMD_WIDTH) where SIMD_WIDTH is 4-16
    /// - **Space**: O(1) additional
    ///
    /// # Examples
    ///
    /// ```rust
    /// use arcweight::prelude::*;
    /// use arcweight::optimization::SimdOps;
    ///
    /// let left = vec![TropicalWeight::new(1.0), TropicalWeight::new(2.0)];
    /// let right = vec![TropicalWeight::new(3.0), TropicalWeight::new(4.0)];
    /// let mut result = vec![TropicalWeight::zero(); 2];
    ///
    /// TropicalWeight::simd_plus(&left, &right, &mut result);
    /// // result = [min(1,3), min(2,4)] = [1.0, 2.0]
    /// ```
    fn simd_plus(left: &[W], right: &[W], result: &mut [W]);

    /// Perform parallel semiring multiplication (times operation) on weight arrays.
    ///
    /// Computes `result[i] = left[i] ⊗ right[i]` for all indices using SIMD
    /// vectorization. For tropical semiring, this computes element-wise addition.
    /// For log semiring, this also computes element-wise addition.
    ///
    /// # Arguments
    ///
    /// * `left` - Left operand weights
    /// * `right` - Right operand weights (must have same length as `left`)
    /// * `result` - Output array for results (must have same length as inputs)
    ///
    /// # Panics
    ///
    /// Panics if the three slices do not have the same length.
    fn simd_times(left: &[W], right: &[W], result: &mut [W]);

    /// Find minimum weight in array using SIMD parallel reduction.
    ///
    /// Computes the semiring sum (minimum for tropical) across all elements
    /// using a parallel tree reduction algorithm.
    ///
    /// # Complexity
    ///
    /// - **Time**: O(n / SIMD_WIDTH + log(SIMD_WIDTH))
    /// - **Space**: O(1)
    ///
    /// # Returns
    ///
    /// Returns `W::zero()` for empty arrays.
    fn simd_min(weights: &[W]) -> W;

    /// Find maximum weight in array using SIMD parallel reduction.
    ///
    /// Computes the maximum value across all elements using a parallel
    /// tree reduction algorithm.
    ///
    /// # Returns
    ///
    /// Returns `W::zero()` for empty arrays.
    fn simd_max(weights: &[W]) -> W;
}

/// Vectorized arc processing utilities.
///
/// Provides functions for processing multiple arcs in parallel using SIMD
/// operations where beneficial. Includes batch transformations and
/// cache-aware sorting algorithms.
///
/// # Overview
///
/// | Function | Purpose | Complexity |
/// |----------|---------|------------|
/// | `parallel_transform` | Batch arc transformation | O(n) |
/// | `batch_weight_operation` | Apply operation to all weights | O(n) |
/// | `simd_sort_by_weight` | Cache-friendly weight sorting | O(n log n) |
///
/// # Performance
///
/// These functions use chunking strategies optimized for CPU cache:
/// - Chunk size of 64 elements fits in L1 cache
/// - Parallel processing with rayon (when feature enabled)
/// - Cache-friendly merge sort for larger arrays
pub mod vectorized_arcs {
    use crate::arc::Arc;
    use crate::semiring::Semiring;

    /// Process multiple arcs with a transformation function using vectorization.
    ///
    /// Applies a transformation to multiple arcs in parallel, using cache-aware
    /// chunking and optional parallel processing with rayon. The function
    /// automatically selects the best strategy based on input size.
    ///
    /// # Arguments
    ///
    /// * `arcs` - Input arcs to transform (takes ownership)
    /// * `transform` - Transformation function to apply to each arc
    ///
    /// # Type Parameters
    ///
    /// * `W` - Weight type implementing `Semiring + Send + Sync`
    /// * `F` - Transformation function type
    ///
    /// # Complexity
    ///
    /// - **Time**: O(n) where n = number of arcs
    /// - **Space**: O(n) for the result vector
    /// - **Parallelism**: Uses rayon for arrays > 256 elements (with feature)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use arcweight::prelude::*;
    /// use arcweight::optimization::vectorized_arcs::parallel_transform;
    ///
    /// let arcs = vec![
    ///     Arc::new(1, 1, TropicalWeight::new(1.0), 0),
    ///     Arc::new(2, 2, TropicalWeight::new(2.0), 1),
    /// ];
    ///
    /// // Scale all weights by 0.5 in tropical semiring (adds 0.5)
    /// let transformed = parallel_transform(arcs, |arc| {
    ///     Arc::new(
    ///         arc.ilabel,
    ///         arc.olabel,
    ///         arc.weight.times(&TropicalWeight::new(0.5)),
    ///         arc.nextstate
    ///     )
    /// });
    ///
    /// assert_eq!(*transformed[0].weight.value(), 1.5);
    /// ```
    pub fn parallel_transform<W, F>(arcs: Vec<Arc<W>>, transform: F) -> Vec<Arc<W>>
    where
        W: Semiring + Send + Sync,
        F: Fn(Arc<W>) -> Arc<W> + Send + Sync,
    {
        // Process arcs in chunks that fit in cache
        const CHUNK_SIZE: usize = 64;

        #[cfg(feature = "rayon")]
        {
            use rayon::prelude::*;

            // For large arc sets, use parallel processing with cache-aware chunking
            if arcs.len() > CHUNK_SIZE * 4 {
                arcs.par_chunks(CHUNK_SIZE)
                    .flat_map(|chunk| chunk.iter().cloned().map(&transform).collect::<Vec<_>>())
                    .collect()
            } else {
                // For smaller sets, parallel overhead isn't worth it
                arcs.into_iter().map(transform).collect()
            }
        }
        #[cfg(not(feature = "rayon"))]
        {
            // Without rayon, process in cache-friendly chunks sequentially
            arcs.chunks(CHUNK_SIZE)
                .flat_map(|chunk| chunk.iter().cloned().map(&transform).collect::<Vec<_>>())
                .collect()
        }
    }

    /// Batch process arc weights using SIMD operations.
    ///
    /// Extracts weights from arcs into a contiguous array, applies the provided
    /// SIMD-friendly operation, and writes results back to the arcs. This
    /// pattern enables efficient vectorized processing of weights.
    ///
    /// # Arguments
    ///
    /// * `arcs` - Mutable slice of arcs to process
    /// * `weight_op` - Operation to apply to the contiguous weight array
    ///
    /// # Type Parameters
    ///
    /// * `W` - Weight type implementing `Semiring + Copy`
    /// * `F` - Operation function taking `&mut [W]`
    ///
    /// # Complexity
    ///
    /// - **Time**: O(n) + cost of `weight_op`
    /// - **Space**: O(n) for temporary weight array
    ///
    /// # Examples
    ///
    /// ```rust
    /// use arcweight::prelude::*;
    /// use arcweight::optimization::vectorized_arcs::batch_weight_operation;
    ///
    /// let mut arcs = vec![
    ///     Arc::new(1, 1, TropicalWeight::new(1.0), 0),
    ///     Arc::new(2, 2, TropicalWeight::new(2.0), 1),
    /// ];
    ///
    /// // Double all weights (in tropical semiring, multiply = add)
    /// batch_weight_operation(&mut arcs, |weights| {
    ///     for w in weights.iter_mut() {
    ///         *w = w.times(&TropicalWeight::new(1.0));
    ///     }
    /// });
    /// ```
    pub fn batch_weight_operation<W, F>(arcs: &mut [Arc<W>], weight_op: F)
    where
        W: Semiring + Copy,
        F: Fn(&mut [W]),
    {
        // Extract weights into contiguous array for SIMD processing
        let mut weights: Vec<W> = arcs.iter().map(|arc| arc.weight).collect();

        // Apply SIMD operation to weights
        weight_op(&mut weights);

        // Update arcs with new weights
        for (arc, &weight) in arcs.iter_mut().zip(weights.iter()) {
            arc.weight = weight;
        }
    }

    /// Sort arcs by weight using cache-aware sorting algorithm.
    ///
    /// Uses a hybrid sorting strategy optimized for CPU cache performance:
    /// - Insertion sort for small arrays (<=16 elements)
    /// - Cache-blocked merge sort for larger arrays
    ///
    /// # Algorithm
    ///
    /// 1. Divide input into cache-friendly chunks (16 elements)
    /// 2. Sort each chunk with insertion sort (cache-resident)
    /// 3. Merge sorted chunks using bottom-up merge sort
    ///
    /// # Complexity
    ///
    /// - **Time**: O(n log n) comparisons
    /// - **Space**: O(n) for merge buffer
    /// - **Cache**: O(n / B) cache misses where B = cache line size
    ///
    /// # Examples
    ///
    /// ```rust
    /// use arcweight::prelude::*;
    /// use arcweight::optimization::vectorized_arcs::simd_sort_by_weight;
    ///
    /// let mut arcs = vec![
    ///     Arc::new(1, 1, TropicalWeight::new(3.0), 0),
    ///     Arc::new(2, 2, TropicalWeight::new(1.0), 1),
    ///     Arc::new(3, 3, TropicalWeight::new(2.0), 2),
    /// ];
    ///
    /// simd_sort_by_weight(&mut arcs);
    /// assert_eq!(*arcs[0].weight.value(), 1.0);
    /// assert_eq!(*arcs[1].weight.value(), 2.0);
    /// assert_eq!(*arcs[2].weight.value(), 3.0);
    /// ```
    pub fn simd_sort_by_weight<W: Semiring + PartialOrd>(arcs: &mut [Arc<W>]) {
        // For small arrays, use insertion sort which is cache-friendly
        if arcs.len() <= 16 {
            for i in 1..arcs.len() {
                let mut j = i;
                while j > 0 && arcs[j - 1].weight > arcs[j].weight {
                    arcs.swap(j - 1, j);
                    j -= 1;
                }
            }
            return;
        }

        // For larger arrays, use a cache-aware sorting approach
        // First, sort small chunks using insertion sort
        const CHUNK_SIZE: usize = 16;
        for chunk in arcs.chunks_mut(CHUNK_SIZE) {
            // Insertion sort for small chunks
            for i in 1..chunk.len() {
                let mut j = i;
                while j > 0 && chunk[j - 1].weight > chunk[j].weight {
                    chunk.swap(j - 1, j);
                    j -= 1;
                }
            }
        }

        // Then merge the sorted chunks
        let mut chunk_size = CHUNK_SIZE;
        while chunk_size < arcs.len() {
            let mut i = 0;
            while i < arcs.len() {
                let mid = (i + chunk_size).min(arcs.len());
                let end = (i + chunk_size * 2).min(arcs.len());

                if mid < end {
                    // Merge two adjacent sorted chunks
                    merge_sorted_chunks(&mut arcs[i..end], mid - i);
                }

                i += chunk_size * 2;
            }
            chunk_size *= 2;
        }
    }

    /// Helper function to merge two sorted chunks within a slice
    fn merge_sorted_chunks<W: Semiring + PartialOrd>(slice: &mut [Arc<W>], mid: usize) {
        // Create temporary storage for the left chunk
        let left: Vec<_> = slice[..mid].to_vec();

        let mut i = 0; // Index for left chunk
        let mut j = mid; // Index for right chunk
        let mut k = 0; // Index for merged result

        // Merge until one chunk is exhausted
        while i < left.len() && j < slice.len() {
            if left[i].weight <= slice[j].weight {
                slice[k] = left[i].clone();
                i += 1;
            } else {
                slice[k] = slice[j].clone();
                j += 1;
            }
            k += 1;
        }

        // Copy remaining elements from left chunk
        while i < left.len() {
            slice[k] = left[i].clone();
            i += 1;
            k += 1;
        }
        // Right chunk elements are already in place
    }
}

/// Cache-optimized memory prefetching utilities.
///
/// Provides CPU hints for preloading data into cache before it is needed,
/// reducing memory access latency for predictable access patterns.
///
/// # Overview
///
/// | Function | Use Case | Latency Reduction |
/// |----------|----------|-------------------|
/// | `prefetch_cache_line` | Single element | 10-30% |
/// | `prefetch_sequential` | Sequential access | 20-50% |
/// | `prefetch_strided` | Regular stride patterns | 15-40% |
///
/// # When to Use
///
/// Prefetching is most effective when:
/// - Access pattern is predictable (sequential, strided)
/// - Data is not already in cache
/// - There is sufficient time between prefetch and access
///
/// Prefetching is less effective or harmful when:
/// - Access pattern is random
/// - Data fits in cache (already resident)
/// - Prefetch distance is too short (no time to load)
///
/// # Platform Support
///
/// - **x86_64**: Uses `_mm_prefetch` intrinsic
/// - **Other platforms**: No-op (safe to call)
pub mod prefetch {
    /// Prefetch a single cache line for read access.
    ///
    /// Hints to the CPU that the memory at `data` will be accessed soon,
    /// allowing the prefetch unit to load it into L1 cache proactively.
    ///
    /// # Arguments
    ///
    /// * `data` - Reference to the data to prefetch
    ///
    /// # Platform Behavior
    ///
    /// - **x86_64**: Issues `PREFETCHT0` instruction (all cache levels)
    /// - **Other**: No-op, safe to call on any platform
    ///
    /// # Examples
    ///
    /// ```rust
    /// use arcweight::optimization::prefetch::prefetch_cache_line;
    ///
    /// let data = vec![1, 2, 3, 4, 5];
    /// prefetch_cache_line(&data[4]); // Hint that we'll access data[4] soon
    /// // ... do other work ...
    /// let value = data[4]; // This access may be faster due to prefetching
    /// ```
    pub fn prefetch_cache_line<T>(data: &T) {
        #[cfg(target_arch = "x86_64")]
        unsafe {
            std::arch::x86_64::_mm_prefetch(
                data as *const T as *const i8,
                std::arch::x86_64::_MM_HINT_T0,
            );
        }

        #[cfg(not(target_arch = "x86_64"))]
        {
            // No-op on non-x86 architectures
            let _ = data;
        }
    }

    /// Prefetch multiple cache lines for sequential access.
    ///
    /// Issues prefetch hints for multiple consecutive cache lines,
    /// optimized for sequential memory traversal patterns.
    ///
    /// # Arguments
    ///
    /// * `data` - Slice containing data to prefetch
    /// * `start_idx` - Starting index in the slice
    /// * `count` - Number of elements to prefetch (rounded to cache lines)
    ///
    /// # Complexity
    ///
    /// - **Time**: O(count / elements_per_cache_line)
    /// - **Space**: O(1)
    pub fn prefetch_sequential<T>(data: &[T], start_idx: usize, count: usize) {
        let end_idx = (start_idx + count).min(data.len());
        let step_size = 64 / std::mem::size_of::<T>(); // Assume 64-byte cache lines

        for i in (start_idx..end_idx).step_by(step_size.max(1)) {
            prefetch_cache_line(&data[i]);
        }
    }

    /// Prefetch data with stride pattern.
    ///
    /// Issues prefetch hints at regular intervals through a data structure,
    /// useful for algorithms that access memory with predictable strides
    /// (e.g., matrix column access, skip lists).
    ///
    /// # Arguments
    ///
    /// * `data` - Slice containing data to prefetch
    /// * `start_idx` - Starting index in the slice
    /// * `stride` - Number of elements between prefetch points
    /// * `count` - Number of prefetch hints to issue
    ///
    /// # Complexity
    ///
    /// - **Time**: O(count)
    /// - **Space**: O(1)
    pub fn prefetch_strided<T>(data: &[T], start_idx: usize, stride: usize, count: usize) {
        for i in 0..count {
            let idx = start_idx + i * stride;
            if idx < data.len() {
                prefetch_cache_line(&data[idx]);
            }
        }
    }
}

// Re-export prefetch function for convenience
pub use prefetch::prefetch_cache_line;

/// SIMD feature detection cache for runtime dispatch
#[cfg(target_arch = "x86_64")]
mod simd_features {
    use std::sync::atomic::{AtomicU8, Ordering};

    // Feature detection results (cached)
    const UNKNOWN: u8 = 0;
    const SSE_ONLY: u8 = 1;
    const AVX2: u8 = 2;
    const AVX512: u8 = 3;

    static DETECTED_LEVEL: AtomicU8 = AtomicU8::new(UNKNOWN);

    /// Get the best available SIMD level
    pub fn get_simd_level() -> u8 {
        let cached = DETECTED_LEVEL.load(Ordering::Relaxed);
        if cached != UNKNOWN {
            return cached;
        }

        let level = detect_simd_level();
        DETECTED_LEVEL.store(level, Ordering::Relaxed);
        level
    }

    fn detect_simd_level() -> u8 {
        if is_x86_feature_detected!("avx512f") && is_x86_feature_detected!("avx512vl") {
            AVX512
        } else if is_x86_feature_detected!("avx2") && is_x86_feature_detected!("fma") {
            AVX2
        } else {
            SSE_ONLY
        }
    }

    #[allow(dead_code)]
    pub const fn sse_only() -> u8 {
        SSE_ONLY
    }
    pub const fn avx2() -> u8 {
        AVX2
    }
    pub const fn avx512() -> u8 {
        AVX512
    }
}

/// SIMD implementation for TropicalWeight with runtime dispatch
#[cfg(target_arch = "x86_64")]
mod tropical_simd {
    use super::simd_features;
    use super::*;
    use crate::semiring::TropicalWeight;

    impl SimdOps<TropicalWeight> for TropicalWeight {
        fn simd_plus(
            left: &[TropicalWeight],
            right: &[TropicalWeight],
            result: &mut [TropicalWeight],
        ) {
            assert_eq!(left.len(), right.len());
            assert_eq!(left.len(), result.len());

            let level = simd_features::get_simd_level();
            if level >= simd_features::avx512() {
                unsafe { simd_plus_avx512(left, right, result) }
            } else if level >= simd_features::avx2() {
                unsafe { simd_plus_avx2(left, right, result) }
            } else {
                unsafe { simd_plus_sse(left, right, result) }
            }
        }

        fn simd_times(
            left: &[TropicalWeight],
            right: &[TropicalWeight],
            result: &mut [TropicalWeight],
        ) {
            assert_eq!(left.len(), right.len());
            assert_eq!(left.len(), result.len());

            let level = simd_features::get_simd_level();
            if level >= simd_features::avx512() {
                unsafe { simd_times_avx512(left, right, result) }
            } else if level >= simd_features::avx2() {
                unsafe { simd_times_avx2(left, right, result) }
            } else {
                unsafe { simd_times_sse(left, right, result) }
            }
        }

        fn simd_min(weights: &[TropicalWeight]) -> TropicalWeight {
            if weights.is_empty() {
                return TropicalWeight::zero();
            }

            let level = simd_features::get_simd_level();
            if level >= simd_features::avx512() {
                unsafe { simd_min_avx512(weights) }
            } else if level >= simd_features::avx2() {
                unsafe { simd_min_avx2(weights) }
            } else {
                unsafe { simd_min_sse(weights) }
            }
        }

        fn simd_max(weights: &[TropicalWeight]) -> TropicalWeight {
            if weights.is_empty() {
                return TropicalWeight::zero();
            }

            let level = simd_features::get_simd_level();
            if level >= simd_features::avx512() {
                unsafe { simd_max_avx512(weights) }
            } else if level >= simd_features::avx2() {
                unsafe { simd_max_avx2(weights) }
            } else {
                unsafe { simd_max_sse(weights) }
            }
        }
    }

    // ============ SSE implementations (128-bit, 4 floats) ============
    //
    // These functions use SSE SIMD instructions to process 4 f32 values at a time.
    // Safety: All functions require `target_feature = "sse"` and use unaligned
    // loads/stores which are safe for any valid memory address.

    /// SSE implementation of tropical semiring plus (element-wise minimum).
    ///
    /// # Safety
    ///
    /// This function is safe to call when:
    /// - The `sse` CPU feature is available (enforced by `target_feature`)
    /// - All input slices have the same length (checked by caller)
    ///
    /// Uses unaligned loads (`_mm_loadu_ps`) which do not require alignment.
    #[target_feature(enable = "sse")]
    unsafe fn simd_plus_sse(
        left: &[TropicalWeight],
        right: &[TropicalWeight],
        result: &mut [TropicalWeight],
    ) {
        use std::arch::x86_64::{_mm_loadu_ps, _mm_min_ps, _mm_storeu_ps};

        let len = left.len();
        let simd_len = len & !3; // Process 4 elements at a time

        for i in (0..simd_len).step_by(4) {
            let left_array = [
                *left[i].value(),
                *left[i + 1].value(),
                *left[i + 2].value(),
                *left[i + 3].value(),
            ];
            let right_array = [
                *right[i].value(),
                *right[i + 1].value(),
                *right[i + 2].value(),
                *right[i + 3].value(),
            ];

            let left_vals = _mm_loadu_ps(left_array.as_ptr());
            let right_vals = _mm_loadu_ps(right_array.as_ptr());
            let min_vals = _mm_min_ps(left_vals, right_vals);

            let mut result_array = [0.0f32; 4];
            _mm_storeu_ps(result_array.as_mut_ptr(), min_vals);

            for j in 0..4 {
                result[i + j] = TropicalWeight::new(result_array[j]);
            }
        }

        // Handle remaining elements
        for i in simd_len..len {
            result[i] = left[i].plus(&right[i]);
        }
    }

    #[target_feature(enable = "sse")]
    unsafe fn simd_times_sse(
        left: &[TropicalWeight],
        right: &[TropicalWeight],
        result: &mut [TropicalWeight],
    ) {
        use std::arch::x86_64::{_mm_add_ps, _mm_loadu_ps, _mm_storeu_ps};

        let len = left.len();
        let simd_len = len & !3;

        for i in (0..simd_len).step_by(4) {
            let left_array = [
                *left[i].value(),
                *left[i + 1].value(),
                *left[i + 2].value(),
                *left[i + 3].value(),
            ];
            let right_array = [
                *right[i].value(),
                *right[i + 1].value(),
                *right[i + 2].value(),
                *right[i + 3].value(),
            ];

            let left_vals = _mm_loadu_ps(left_array.as_ptr());
            let right_vals = _mm_loadu_ps(right_array.as_ptr());
            let sum_vals = _mm_add_ps(left_vals, right_vals);

            let mut result_array = [0.0f32; 4];
            _mm_storeu_ps(result_array.as_mut_ptr(), sum_vals);

            for j in 0..4 {
                result[i + j] = TropicalWeight::new(result_array[j]);
            }
        }

        for i in simd_len..len {
            result[i] = left[i].times(&right[i]);
        }
    }

    #[target_feature(enable = "sse")]
    unsafe fn simd_min_sse(weights: &[TropicalWeight]) -> TropicalWeight {
        use std::arch::x86_64::{_mm_loadu_ps, _mm_min_ps, _mm_set1_ps, _mm_storeu_ps};

        let len = weights.len();
        let simd_len = len & !3;

        let mut min_vec = _mm_set1_ps(f32::INFINITY);

        for i in (0..simd_len).step_by(4) {
            let vals_array = [
                *weights[i].value(),
                *weights[i + 1].value(),
                *weights[i + 2].value(),
                *weights[i + 3].value(),
            ];
            let vals = _mm_loadu_ps(vals_array.as_ptr());
            min_vec = _mm_min_ps(min_vec, vals);
        }

        let mut result_array = [0.0f32; 4];
        _mm_storeu_ps(result_array.as_mut_ptr(), min_vec);
        let mut min_val = result_array[0];
        for &val in &result_array[1..] {
            min_val = min_val.min(val);
        }

        for weight in weights.iter().skip(simd_len) {
            min_val = min_val.min(*weight.value());
        }

        TropicalWeight::new(min_val)
    }

    #[target_feature(enable = "sse")]
    unsafe fn simd_max_sse(weights: &[TropicalWeight]) -> TropicalWeight {
        use std::arch::x86_64::{_mm_loadu_ps, _mm_max_ps, _mm_set1_ps, _mm_storeu_ps};

        let len = weights.len();
        let simd_len = len & !3;

        let mut max_vec = _mm_set1_ps(f32::NEG_INFINITY);

        for i in (0..simd_len).step_by(4) {
            let vals_array = [
                *weights[i].value(),
                *weights[i + 1].value(),
                *weights[i + 2].value(),
                *weights[i + 3].value(),
            ];
            let vals = _mm_loadu_ps(vals_array.as_ptr());
            max_vec = _mm_max_ps(max_vec, vals);
        }

        let mut result_array = [0.0f32; 4];
        _mm_storeu_ps(result_array.as_mut_ptr(), max_vec);
        let mut max_val = result_array[0];
        for &val in &result_array[1..] {
            max_val = max_val.max(val);
        }

        for weight in weights.iter().skip(simd_len) {
            max_val = max_val.max(*weight.value());
        }

        TropicalWeight::new(max_val)
    }

    // ============ AVX2 implementations (256-bit, 8 floats) ============
    //
    // These functions use AVX2 SIMD instructions to process 8 f32 values at a time.
    // Safety: All functions require `target_feature = "avx2"` and use unaligned
    // loads/stores which are safe for any valid memory address.

    /// AVX2 implementation of tropical semiring plus (element-wise minimum).
    ///
    /// Processes 8 elements per iteration, providing ~2x throughput over SSE.
    ///
    /// # Safety
    ///
    /// This function is safe to call when:
    /// - The `avx2` CPU feature is available (enforced by `target_feature`)
    /// - All input slices have the same length (checked by caller)
    #[target_feature(enable = "avx2")]
    unsafe fn simd_plus_avx2(
        left: &[TropicalWeight],
        right: &[TropicalWeight],
        result: &mut [TropicalWeight],
    ) {
        use std::arch::x86_64::{_mm256_loadu_ps, _mm256_min_ps, _mm256_storeu_ps};

        let len = left.len();
        let simd_len = len & !7; // Process 8 elements at a time

        for i in (0..simd_len).step_by(8) {
            let left_array = [
                *left[i].value(),
                *left[i + 1].value(),
                *left[i + 2].value(),
                *left[i + 3].value(),
                *left[i + 4].value(),
                *left[i + 5].value(),
                *left[i + 6].value(),
                *left[i + 7].value(),
            ];
            let right_array = [
                *right[i].value(),
                *right[i + 1].value(),
                *right[i + 2].value(),
                *right[i + 3].value(),
                *right[i + 4].value(),
                *right[i + 5].value(),
                *right[i + 6].value(),
                *right[i + 7].value(),
            ];

            let left_vals = _mm256_loadu_ps(left_array.as_ptr());
            let right_vals = _mm256_loadu_ps(right_array.as_ptr());
            let min_vals = _mm256_min_ps(left_vals, right_vals);

            let mut result_array = [0.0f32; 8];
            _mm256_storeu_ps(result_array.as_mut_ptr(), min_vals);

            for j in 0..8 {
                result[i + j] = TropicalWeight::new(result_array[j]);
            }
        }

        // Handle remaining elements with SSE or scalar
        for i in simd_len..len {
            result[i] = left[i].plus(&right[i]);
        }
    }

    #[target_feature(enable = "avx2")]
    unsafe fn simd_times_avx2(
        left: &[TropicalWeight],
        right: &[TropicalWeight],
        result: &mut [TropicalWeight],
    ) {
        use std::arch::x86_64::{_mm256_add_ps, _mm256_loadu_ps, _mm256_storeu_ps};

        let len = left.len();
        let simd_len = len & !7;

        for i in (0..simd_len).step_by(8) {
            let left_array = [
                *left[i].value(),
                *left[i + 1].value(),
                *left[i + 2].value(),
                *left[i + 3].value(),
                *left[i + 4].value(),
                *left[i + 5].value(),
                *left[i + 6].value(),
                *left[i + 7].value(),
            ];
            let right_array = [
                *right[i].value(),
                *right[i + 1].value(),
                *right[i + 2].value(),
                *right[i + 3].value(),
                *right[i + 4].value(),
                *right[i + 5].value(),
                *right[i + 6].value(),
                *right[i + 7].value(),
            ];

            let left_vals = _mm256_loadu_ps(left_array.as_ptr());
            let right_vals = _mm256_loadu_ps(right_array.as_ptr());
            let sum_vals = _mm256_add_ps(left_vals, right_vals);

            let mut result_array = [0.0f32; 8];
            _mm256_storeu_ps(result_array.as_mut_ptr(), sum_vals);

            for j in 0..8 {
                result[i + j] = TropicalWeight::new(result_array[j]);
            }
        }

        for i in simd_len..len {
            result[i] = left[i].times(&right[i]);
        }
    }

    #[target_feature(enable = "avx2")]
    unsafe fn simd_min_avx2(weights: &[TropicalWeight]) -> TropicalWeight {
        use std::arch::x86_64::{_mm256_loadu_ps, _mm256_min_ps, _mm256_set1_ps, _mm256_storeu_ps};

        let len = weights.len();
        let simd_len = len & !7;

        let mut min_vec = _mm256_set1_ps(f32::INFINITY);

        for i in (0..simd_len).step_by(8) {
            let vals_array = [
                *weights[i].value(),
                *weights[i + 1].value(),
                *weights[i + 2].value(),
                *weights[i + 3].value(),
                *weights[i + 4].value(),
                *weights[i + 5].value(),
                *weights[i + 6].value(),
                *weights[i + 7].value(),
            ];
            let vals = _mm256_loadu_ps(vals_array.as_ptr());
            min_vec = _mm256_min_ps(min_vec, vals);
        }

        let mut result_array = [0.0f32; 8];
        _mm256_storeu_ps(result_array.as_mut_ptr(), min_vec);
        let mut min_val = result_array[0];
        for &val in &result_array[1..] {
            min_val = min_val.min(val);
        }

        for weight in weights.iter().skip(simd_len) {
            min_val = min_val.min(*weight.value());
        }

        TropicalWeight::new(min_val)
    }

    #[target_feature(enable = "avx2")]
    unsafe fn simd_max_avx2(weights: &[TropicalWeight]) -> TropicalWeight {
        use std::arch::x86_64::{_mm256_loadu_ps, _mm256_max_ps, _mm256_set1_ps, _mm256_storeu_ps};

        let len = weights.len();
        let simd_len = len & !7;

        let mut max_vec = _mm256_set1_ps(f32::NEG_INFINITY);

        for i in (0..simd_len).step_by(8) {
            let vals_array = [
                *weights[i].value(),
                *weights[i + 1].value(),
                *weights[i + 2].value(),
                *weights[i + 3].value(),
                *weights[i + 4].value(),
                *weights[i + 5].value(),
                *weights[i + 6].value(),
                *weights[i + 7].value(),
            ];
            let vals = _mm256_loadu_ps(vals_array.as_ptr());
            max_vec = _mm256_max_ps(max_vec, vals);
        }

        let mut result_array = [0.0f32; 8];
        _mm256_storeu_ps(result_array.as_mut_ptr(), max_vec);
        let mut max_val = result_array[0];
        for &val in &result_array[1..] {
            max_val = max_val.max(val);
        }

        for weight in weights.iter().skip(simd_len) {
            max_val = max_val.max(*weight.value());
        }

        TropicalWeight::new(max_val)
    }

    // ============ AVX-512 implementations (512-bit, 16 floats) ============
    //
    // These functions use AVX-512 SIMD instructions to process 16 f32 values at a time.
    // Safety: Functions require `target_feature = "avx512f"` and fall back to AVX2
    // when AVX-512 is not available at compile time.

    /// AVX-512 implementation of tropical semiring plus (element-wise minimum).
    ///
    /// Processes 16 elements per iteration, providing ~4x throughput over SSE.
    /// Falls back to AVX2 if AVX-512 is not available at compile time.
    ///
    /// # Safety
    ///
    /// This function is safe to call when:
    /// - The `avx512f` CPU feature is available (enforced by `target_feature`)
    /// - All input slices have the same length (checked by caller)
    #[cfg(target_feature = "avx512f")]
    #[target_feature(enable = "avx512f")]
    unsafe fn simd_plus_avx512(
        left: &[TropicalWeight],
        right: &[TropicalWeight],
        result: &mut [TropicalWeight],
    ) {
        use std::arch::x86_64::{_mm512_loadu_ps, _mm512_min_ps, _mm512_storeu_ps};

        let len = left.len();
        let simd_len = len & !15; // Process 16 elements at a time

        for i in (0..simd_len).step_by(16) {
            let mut left_array = [0.0f32; 16];
            let mut right_array = [0.0f32; 16];
            for j in 0..16 {
                left_array[j] = *left[i + j].value();
                right_array[j] = *right[i + j].value();
            }

            let left_vals = _mm512_loadu_ps(left_array.as_ptr());
            let right_vals = _mm512_loadu_ps(right_array.as_ptr());
            let min_vals = _mm512_min_ps(left_vals, right_vals);

            let mut result_array = [0.0f32; 16];
            _mm512_storeu_ps(result_array.as_mut_ptr(), min_vals);

            for j in 0..16 {
                result[i + j] = TropicalWeight::new(result_array[j]);
            }
        }

        for i in simd_len..len {
            result[i] = left[i].plus(&right[i]);
        }
    }

    // AVX-512 fallback to AVX2 when AVX-512 is not available at compile time
    #[cfg(not(target_feature = "avx512f"))]
    unsafe fn simd_plus_avx512(
        left: &[TropicalWeight],
        right: &[TropicalWeight],
        result: &mut [TropicalWeight],
    ) {
        simd_plus_avx2(left, right, result)
    }

    #[cfg(target_feature = "avx512f")]
    #[target_feature(enable = "avx512f")]
    unsafe fn simd_times_avx512(
        left: &[TropicalWeight],
        right: &[TropicalWeight],
        result: &mut [TropicalWeight],
    ) {
        use std::arch::x86_64::{_mm512_add_ps, _mm512_loadu_ps, _mm512_storeu_ps};

        let len = left.len();
        let simd_len = len & !15;

        for i in (0..simd_len).step_by(16) {
            let mut left_array = [0.0f32; 16];
            let mut right_array = [0.0f32; 16];
            for j in 0..16 {
                left_array[j] = *left[i + j].value();
                right_array[j] = *right[i + j].value();
            }

            let left_vals = _mm512_loadu_ps(left_array.as_ptr());
            let right_vals = _mm512_loadu_ps(right_array.as_ptr());
            let sum_vals = _mm512_add_ps(left_vals, right_vals);

            let mut result_array = [0.0f32; 16];
            _mm512_storeu_ps(result_array.as_mut_ptr(), sum_vals);

            for j in 0..16 {
                result[i + j] = TropicalWeight::new(result_array[j]);
            }
        }

        for i in simd_len..len {
            result[i] = left[i].times(&right[i]);
        }
    }

    #[cfg(not(target_feature = "avx512f"))]
    unsafe fn simd_times_avx512(
        left: &[TropicalWeight],
        right: &[TropicalWeight],
        result: &mut [TropicalWeight],
    ) {
        simd_times_avx2(left, right, result)
    }

    #[cfg(target_feature = "avx512f")]
    #[target_feature(enable = "avx512f")]
    unsafe fn simd_min_avx512(weights: &[TropicalWeight]) -> TropicalWeight {
        use std::arch::x86_64::{_mm512_loadu_ps, _mm512_min_ps, _mm512_set1_ps, _mm512_storeu_ps};

        let len = weights.len();
        let simd_len = len & !15;

        let mut min_vec = _mm512_set1_ps(f32::INFINITY);

        for i in (0..simd_len).step_by(16) {
            let mut vals_array = [0.0f32; 16];
            for j in 0..16 {
                vals_array[j] = *weights[i + j].value();
            }
            let vals = _mm512_loadu_ps(vals_array.as_ptr());
            min_vec = _mm512_min_ps(min_vec, vals);
        }

        let mut result_array = [0.0f32; 16];
        _mm512_storeu_ps(result_array.as_mut_ptr(), min_vec);
        let mut min_val = result_array[0];
        for &val in &result_array[1..] {
            min_val = min_val.min(val);
        }

        for weight in weights.iter().skip(simd_len) {
            min_val = min_val.min(*weight.value());
        }

        TropicalWeight::new(min_val)
    }

    #[cfg(not(target_feature = "avx512f"))]
    unsafe fn simd_min_avx512(weights: &[TropicalWeight]) -> TropicalWeight {
        simd_min_avx2(weights)
    }

    #[cfg(target_feature = "avx512f")]
    #[target_feature(enable = "avx512f")]
    unsafe fn simd_max_avx512(weights: &[TropicalWeight]) -> TropicalWeight {
        use std::arch::x86_64::{_mm512_loadu_ps, _mm512_max_ps, _mm512_set1_ps, _mm512_storeu_ps};

        let len = weights.len();
        let simd_len = len & !15;

        let mut max_vec = _mm512_set1_ps(f32::NEG_INFINITY);

        for i in (0..simd_len).step_by(16) {
            let mut vals_array = [0.0f32; 16];
            for j in 0..16 {
                vals_array[j] = *weights[i + j].value();
            }
            let vals = _mm512_loadu_ps(vals_array.as_ptr());
            max_vec = _mm512_max_ps(max_vec, vals);
        }

        let mut result_array = [0.0f32; 16];
        _mm512_storeu_ps(result_array.as_mut_ptr(), max_vec);
        let mut max_val = result_array[0];
        for &val in &result_array[1..] {
            max_val = max_val.max(val);
        }

        for weight in weights.iter().skip(simd_len) {
            max_val = max_val.max(*weight.value());
        }

        TropicalWeight::new(max_val)
    }

    #[cfg(not(target_feature = "avx512f"))]
    unsafe fn simd_max_avx512(weights: &[TropicalWeight]) -> TropicalWeight {
        simd_max_avx2(weights)
    }
}

/// SIMD implementation for LogWeight with vectorized log-sum-exp
#[cfg(target_arch = "x86_64")]
mod log_simd {
    use super::simd_features;
    use super::*;
    use crate::semiring::LogWeight;

    impl SimdOps<LogWeight> for LogWeight {
        fn simd_plus(left: &[LogWeight], right: &[LogWeight], result: &mut [LogWeight]) {
            assert_eq!(left.len(), right.len());
            assert_eq!(left.len(), result.len());

            let level = simd_features::get_simd_level();
            if level >= simd_features::avx2() {
                unsafe { simd_log_sum_exp_avx2(left, right, result) }
            } else {
                // Scalar fallback for log-sum-exp (complex operation)
                for i in 0..left.len() {
                    result[i] = left[i].plus(&right[i]);
                }
            }
        }

        fn simd_times(left: &[LogWeight], right: &[LogWeight], result: &mut [LogWeight]) {
            assert_eq!(left.len(), right.len());
            assert_eq!(left.len(), result.len());

            let level = simd_features::get_simd_level();
            if level >= simd_features::avx2() {
                unsafe { simd_log_times_avx2(left, right, result) }
            } else {
                unsafe { simd_log_times_sse(left, right, result) }
            }
        }

        fn simd_min(weights: &[LogWeight]) -> LogWeight {
            if weights.is_empty() {
                return LogWeight::zero();
            }

            // For LogWeight, min corresponds to max probability
            let mut min_val = f64::INFINITY;
            for weight in weights {
                let val = *weight.value();
                if val < min_val {
                    min_val = val;
                }
            }

            LogWeight::new(min_val)
        }

        fn simd_max(weights: &[LogWeight]) -> LogWeight {
            if weights.is_empty() {
                return LogWeight::zero();
            }

            let mut max_val = f64::NEG_INFINITY;
            for weight in weights {
                let val = *weight.value();
                if val > max_val && !val.is_infinite() {
                    max_val = val;
                }
            }

            if max_val == f64::NEG_INFINITY {
                LogWeight::zero()
            } else {
                LogWeight::new(max_val)
            }
        }
    }

    // LogWeight times is just addition in log space - easy to vectorize
    #[target_feature(enable = "sse2")]
    unsafe fn simd_log_times_sse(
        left: &[LogWeight],
        right: &[LogWeight],
        result: &mut [LogWeight],
    ) {
        use std::arch::x86_64::{_mm_add_pd, _mm_loadu_pd, _mm_storeu_pd};

        let len = left.len();
        let simd_len = len & !1; // Process 2 f64s at a time

        for i in (0..simd_len).step_by(2) {
            let left_array = [*left[i].value(), *left[i + 1].value()];
            let right_array = [*right[i].value(), *right[i + 1].value()];

            let left_vals = _mm_loadu_pd(left_array.as_ptr());
            let right_vals = _mm_loadu_pd(right_array.as_ptr());
            let sum_vals = _mm_add_pd(left_vals, right_vals);

            let mut result_array = [0.0f64; 2];
            _mm_storeu_pd(result_array.as_mut_ptr(), sum_vals);

            result[i] = LogWeight::new(result_array[0]);
            result[i + 1] = LogWeight::new(result_array[1]);
        }

        for i in simd_len..len {
            result[i] = left[i].times(&right[i]);
        }
    }

    #[target_feature(enable = "avx2")]
    unsafe fn simd_log_times_avx2(
        left: &[LogWeight],
        right: &[LogWeight],
        result: &mut [LogWeight],
    ) {
        use std::arch::x86_64::{_mm256_add_pd, _mm256_loadu_pd, _mm256_storeu_pd};

        let len = left.len();
        let simd_len = len & !3; // Process 4 f64s at a time

        for i in (0..simd_len).step_by(4) {
            let left_array = [
                *left[i].value(),
                *left[i + 1].value(),
                *left[i + 2].value(),
                *left[i + 3].value(),
            ];
            let right_array = [
                *right[i].value(),
                *right[i + 1].value(),
                *right[i + 2].value(),
                *right[i + 3].value(),
            ];

            let left_vals = _mm256_loadu_pd(left_array.as_ptr());
            let right_vals = _mm256_loadu_pd(right_array.as_ptr());
            let sum_vals = _mm256_add_pd(left_vals, right_vals);

            let mut result_array = [0.0f64; 4];
            _mm256_storeu_pd(result_array.as_mut_ptr(), sum_vals);

            for j in 0..4 {
                result[i + j] = LogWeight::new(result_array[j]);
            }
        }

        for i in simd_len..len {
            result[i] = left[i].times(&right[i]);
        }
    }

    // Vectorized log-sum-exp using AVX2
    // log-sum-exp(a, b) = max(a, b) + log(1 + exp(-|a - b|))
    #[target_feature(enable = "avx2")]
    unsafe fn simd_log_sum_exp_avx2(
        left: &[LogWeight],
        right: &[LogWeight],
        result: &mut [LogWeight],
    ) {
        use std::arch::x86_64::{
            _mm256_add_pd, _mm256_and_pd, _mm256_castsi256_pd, _mm256_loadu_pd, _mm256_max_pd,
            _mm256_set1_epi64x, _mm256_storeu_pd, _mm256_sub_pd,
        };

        let len = left.len();
        let simd_len = len & !3;

        // Constant for absolute value mask (clear sign bit)
        let abs_mask = _mm256_castsi256_pd(_mm256_set1_epi64x(0x7FFFFFFFFFFFFFFF_u64 as i64));

        for i in (0..simd_len).step_by(4) {
            // Check for infinities (zeros in log semiring)
            let mut has_inf = false;
            for j in 0..4 {
                if left[i + j].value().is_infinite() || right[i + j].value().is_infinite() {
                    has_inf = true;
                    break;
                }
            }

            if has_inf {
                // Fall back to scalar for infinity handling
                for j in 0..4 {
                    result[i + j] = left[i + j].plus(&right[i + j]);
                }
                continue;
            }

            let left_array = [
                -*left[i].value(),
                -*left[i + 1].value(),
                -*left[i + 2].value(),
                -*left[i + 3].value(),
            ];
            let right_array = [
                -*right[i].value(),
                -*right[i + 1].value(),
                -*right[i + 2].value(),
                -*right[i + 3].value(),
            ];

            let a = _mm256_loadu_pd(left_array.as_ptr());
            let b = _mm256_loadu_pd(right_array.as_ptr());

            // max(a, b)
            let max_ab = _mm256_max_pd(a, b);

            // |a - b|
            let diff = _mm256_sub_pd(a, b);
            let abs_diff = _mm256_and_pd(abs_mask, diff);

            // Store intermediate results and compute log(1 + exp(-|diff|)) using scalar
            let mut max_array = [0.0f64; 4];
            let mut abs_diff_array = [0.0f64; 4];
            _mm256_storeu_pd(max_array.as_mut_ptr(), max_ab);
            _mm256_storeu_pd(abs_diff_array.as_mut_ptr(), abs_diff);

            // Compute log(1 + exp(-x)) with scalar math (more accurate)
            let mut log1pexp = [0.0f64; 4];
            for j in 0..4 {
                let x = abs_diff_array[j];
                // Use log1p for better numerical stability
                log1pexp[j] = (1.0 + (-x).exp()).ln();
            }

            // max + log(1 + exp(-|diff|))
            let log1pexp_vec = _mm256_loadu_pd(log1pexp.as_ptr());
            let sum = _mm256_add_pd(max_ab, log1pexp_vec);

            let mut result_array = [0.0f64; 4];
            _mm256_storeu_pd(result_array.as_mut_ptr(), sum);

            // Negate back to log semiring convention
            for j in 0..4 {
                result[i + j] = LogWeight::new(-result_array[j]);
            }
        }

        // Handle remaining elements
        for i in simd_len..len {
            result[i] = left[i].plus(&right[i]);
        }
    }
}

// Non-SIMD fallback implementations
#[cfg(not(target_arch = "x86_64"))]
mod fallback_simd {
    use super::*;
    use crate::semiring::{LogWeight, TropicalWeight};

    impl SimdOps<TropicalWeight> for TropicalWeight {
        fn simd_plus(
            left: &[TropicalWeight],
            right: &[TropicalWeight],
            result: &mut [TropicalWeight],
        ) {
            for ((l, r), res) in left.iter().zip(right.iter()).zip(result.iter_mut()) {
                *res = l.plus(r);
            }
        }

        fn simd_times(
            left: &[TropicalWeight],
            right: &[TropicalWeight],
            result: &mut [TropicalWeight],
        ) {
            for ((l, r), res) in left.iter().zip(right.iter()).zip(result.iter_mut()) {
                *res = l.times(r);
            }
        }

        fn simd_min(weights: &[TropicalWeight]) -> TropicalWeight {
            weights
                .iter()
                .fold(TropicalWeight::zero(), |acc, w| acc.plus(w))
        }

        fn simd_max(weights: &[TropicalWeight]) -> TropicalWeight {
            weights
                .iter()
                .fold(TropicalWeight::new(f32::NEG_INFINITY), |acc, w| {
                    if w.value() > acc.value() {
                        *w
                    } else {
                        acc
                    }
                })
        }
    }

    impl SimdOps<LogWeight> for LogWeight {
        fn simd_plus(left: &[LogWeight], right: &[LogWeight], result: &mut [LogWeight]) {
            for ((l, r), res) in left.iter().zip(right.iter()).zip(result.iter_mut()) {
                *res = l.plus(r);
            }
        }

        fn simd_times(left: &[LogWeight], right: &[LogWeight], result: &mut [LogWeight]) {
            for ((l, r), res) in left.iter().zip(right.iter()).zip(result.iter_mut()) {
                *res = l.times(r);
            }
        }

        fn simd_min(weights: &[LogWeight]) -> LogWeight {
            weights.iter().fold(LogWeight::zero(), |acc, w| {
                if w.value() < acc.value() {
                    *w
                } else {
                    acc
                }
            })
        }

        fn simd_max(weights: &[LogWeight]) -> LogWeight {
            weights
                .iter()
                .fold(LogWeight::new(f64::NEG_INFINITY), |acc, w| {
                    if w.value() > acc.value() && !w.value().is_infinite() {
                        *w
                    } else {
                        acc
                    }
                })
        }
    }
}

#[cfg(test)]
mod tests {
    use super::prefetch;
    use super::vectorized_arcs;
    use crate::prelude::*;
    use crate::semiring::LogWeight;
    use num_traits::Zero;

    #[test]
    fn test_simd_plus() {
        let left = vec![TropicalWeight::new(1.0), TropicalWeight::new(2.0)];
        let right = vec![TropicalWeight::new(3.0), TropicalWeight::new(1.5)];
        let mut result = vec![TropicalWeight::zero(); 2];

        TropicalWeight::simd_plus(&left, &right, &mut result);

        assert_eq!(result[0], TropicalWeight::new(1.0)); // min(1.0, 3.0)
        assert_eq!(result[1], TropicalWeight::new(1.5)); // min(2.0, 1.5)
    }

    #[test]
    fn test_simd_times() {
        let left = vec![TropicalWeight::new(1.0), TropicalWeight::new(2.0)];
        let right = vec![TropicalWeight::new(3.0), TropicalWeight::new(1.5)];
        let mut result = vec![TropicalWeight::zero(); 2];

        TropicalWeight::simd_times(&left, &right, &mut result);

        assert_eq!(result[0], TropicalWeight::new(4.0)); // 1.0 + 3.0
        assert_eq!(result[1], TropicalWeight::new(3.5)); // 2.0 + 1.5
    }

    #[test]
    fn test_simd_min() {
        let weights = vec![
            TropicalWeight::new(3.0),
            TropicalWeight::new(1.0),
            TropicalWeight::new(2.0),
            TropicalWeight::new(0.5),
        ];

        let min_weight = TropicalWeight::simd_min(&weights);
        assert_eq!(min_weight, TropicalWeight::new(0.5));
    }

    #[test]
    fn test_simd_plus_large() {
        // Test with enough elements to trigger SIMD paths (8+ for AVX2, 16+ for AVX-512)
        let left: Vec<TropicalWeight> = (0..32).map(|i| TropicalWeight::new(i as f32)).collect();
        let right: Vec<TropicalWeight> = (0..32)
            .map(|i| TropicalWeight::new((31 - i) as f32))
            .collect();
        let mut result = vec![TropicalWeight::zero(); 32];

        TropicalWeight::simd_plus(&left, &right, &mut result);

        // Verify all results (min of each pair)
        for (i, res) in result.iter().enumerate().take(32) {
            let expected = (i as f32).min((31 - i) as f32);
            assert_eq!(*res, TropicalWeight::new(expected));
        }
    }

    #[test]
    fn test_simd_times_large() {
        let left: Vec<TropicalWeight> = (0..32).map(|i| TropicalWeight::new(i as f32)).collect();
        let right: Vec<TropicalWeight> = (0..32).map(|i| TropicalWeight::new(i as f32)).collect();
        let mut result = vec![TropicalWeight::zero(); 32];

        TropicalWeight::simd_times(&left, &right, &mut result);

        // Verify all results (sum of each pair)
        for (i, res) in result.iter().enumerate().take(32) {
            let expected = (i as f32) + (i as f32);
            assert_eq!(*res, TropicalWeight::new(expected));
        }
    }

    #[test]
    fn test_simd_min_large() {
        let weights: Vec<TropicalWeight> =
            (0..100).map(|i| TropicalWeight::new(i as f32)).collect();
        let min_weight = TropicalWeight::simd_min(&weights);
        assert_eq!(min_weight, TropicalWeight::new(0.0));

        let weights: Vec<TropicalWeight> = (0..100)
            .map(|i| TropicalWeight::new(100.0 - i as f32))
            .collect();
        let min_weight = TropicalWeight::simd_min(&weights);
        assert_eq!(min_weight, TropicalWeight::new(1.0));
    }

    #[test]
    fn test_simd_max_large() {
        let weights: Vec<TropicalWeight> =
            (0..100).map(|i| TropicalWeight::new(i as f32)).collect();
        let max_weight = TropicalWeight::simd_max(&weights);
        assert_eq!(max_weight, TropicalWeight::new(99.0));
    }

    // LogWeight SIMD tests
    #[test]
    fn test_log_simd_times() {
        let left = vec![LogWeight::new(1.0), LogWeight::new(2.0)];
        let right = vec![LogWeight::new(3.0), LogWeight::new(1.5)];
        let mut result = vec![LogWeight::zero(); 2];

        LogWeight::simd_times(&left, &right, &mut result);

        // Times in log semiring is addition
        assert_eq!(result[0], LogWeight::new(4.0)); // 1.0 + 3.0
        assert_eq!(result[1], LogWeight::new(3.5)); // 2.0 + 1.5
    }

    #[test]
    fn test_log_simd_times_large() {
        let left: Vec<LogWeight> = (0..32).map(|i| LogWeight::new(i as f64)).collect();
        let right: Vec<LogWeight> = (0..32).map(|i| LogWeight::new(i as f64 * 0.5)).collect();
        let mut result = vec![LogWeight::zero(); 32];

        LogWeight::simd_times(&left, &right, &mut result);

        for (i, res) in result.iter().enumerate().take(32) {
            let expected = (i as f64) + (i as f64 * 0.5);
            assert!(res.approx_eq(&LogWeight::new(expected), 1e-10));
        }
    }

    #[test]
    fn test_log_simd_plus() {
        // Test log-sum-exp operation
        let left = vec![LogWeight::new(1.0), LogWeight::new(2.0)];
        let right = vec![LogWeight::new(2.0), LogWeight::new(2.0)];
        let mut result = vec![LogWeight::zero(); 2];

        LogWeight::simd_plus(&left, &right, &mut result);

        // Verify using scalar implementation
        let expected0 = left[0].plus(&right[0]);
        let expected1 = left[1].plus(&right[1]);

        assert!(result[0].approx_eq(&expected0, 1e-10));
        assert!(result[1].approx_eq(&expected1, 1e-10));
    }

    #[test]
    fn test_log_simd_plus_large() {
        let left: Vec<LogWeight> = (0..32).map(|i| LogWeight::new(i as f64)).collect();
        let right: Vec<LogWeight> = (0..32).map(|i| LogWeight::new(i as f64 + 0.5)).collect();
        let mut result = vec![LogWeight::zero(); 32];

        LogWeight::simd_plus(&left, &right, &mut result);

        // Verify against scalar implementation
        for i in 0..32 {
            let expected = left[i].plus(&right[i]);
            assert!(
                result[i].approx_eq(&expected, 1e-6),
                "Mismatch at {}: got {:?}, expected {:?}",
                i,
                result[i],
                expected
            );
        }
    }

    #[test]
    fn test_log_simd_with_infinity() {
        // Test log-sum-exp with infinity (zero in log semiring)
        let left = vec![LogWeight::zero(), LogWeight::new(1.0)];
        let right = vec![LogWeight::new(2.0), LogWeight::zero()];
        let mut result = vec![LogWeight::new(999.0); 2];

        LogWeight::simd_plus(&left, &right, &mut result);

        // Zero + x = x in log semiring
        assert_eq!(result[0], LogWeight::new(2.0));
        assert_eq!(result[1], LogWeight::new(1.0));
    }

    #[test]
    fn test_vectorized_transform() {
        let arcs = vec![
            Arc::new(1, 1, TropicalWeight::new(1.0), 0),
            Arc::new(2, 2, TropicalWeight::new(2.0), 1),
        ];

        let transformed = vectorized_arcs::parallel_transform(arcs, |arc| {
            Arc::new(
                arc.ilabel,
                arc.olabel,
                arc.weight.times(&TropicalWeight::new(0.5)),
                arc.nextstate,
            )
        });

        assert_eq!(transformed[0].weight, TropicalWeight::new(1.5));
        assert_eq!(transformed[1].weight, TropicalWeight::new(2.5));
    }

    #[test]
    fn test_prefetch() {
        let data = vec![1, 2, 3, 4, 5];

        // This should not panic and is safe to call
        prefetch_cache_line(&data[0]);
        prefetch::prefetch_sequential(&data, 0, 5);
        prefetch::prefetch_strided(&data, 0, 2, 3);
    }
}