ruxla-kernels 0.1.0

Internal crate of ruxla (use the `ruxla` crate): semantics of ruxla's operations, shared by the native backend and the IR interpreter
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
//! Array operations on row-major buffers.
//!
//! Each function takes the elements of its operands as slices with their
//! shapes, and returns the elements of the result. Shapes are assumed to
//! have been checked (by shape inference); the functions panic on
//! inconsistent inputs.

use std::cmp::Ordering;

use crate::buffer::Buffer;
use crate::dtype::{DType, Element, Value, cast};
use crate::ops::{BinaryOp, UnaryOp};

/// Returns the row-major strides of `shape`.
pub fn strides(shape: &[usize]) -> Vec<usize> {
    let mut s = vec![1; shape.len()];
    for i in (0..shape.len().saturating_sub(1)).rev() {
        s[i] = s[i + 1] * shape[i + 1];
    }
    s
}

/// [`strides`] on the stack, for at most 8 dimensions.
fn small_strides(shape: &[usize]) -> [usize; 8] {
    let mut s = [1usize; 8];
    for i in (0..shape.len().saturating_sub(1)).rev() {
        s[i] = s[i + 1] * shape[i + 1];
    }
    s
}

/// Returns the number of elements of `shape`.
pub fn size(shape: &[usize]) -> usize {
    shape.iter().product()
}

/// Converts a flat index into a multi-index.
pub fn unravel(mut flat: usize, shape: &[usize]) -> Vec<usize> {
    let mut index = vec![0; shape.len()];
    for (i, &d) in shape.iter().enumerate().rev() {
        if d > 0 {
            index[i] = flat % d;
            flat /= d;
        }
    }
    index
}

/// Converts a multi-index into a flat index, given strides.
pub fn ravel(index: &[usize], strides: &[usize]) -> usize {
    index.iter().zip(strides).map(|(i, s)| i * s).sum()
}

/// Applies `f` to the multi-index of each element of `shape`, in row-major
/// order, and collects the results.
fn map_indices<T>(shape: &[usize], mut f: impl FnMut(&[usize]) -> T) -> Vec<T> {
    let n = size(shape);
    let mut out = Vec::with_capacity(n);
    let mut index = vec![0; shape.len()];
    for _ in 0..n {
        out.push(f(&index));
        for d in (0..shape.len()).rev() {
            index[d] += 1;
            if index[d] < shape[d] {
                break;
            }
            index[d] = 0;
        }
    }
    out
}

/// `broadcast_in_dim`: dimension `i` of `x` becomes dimension `dims[i]` of
/// the result, which has shape `out_shape`.
pub fn broadcast_in_dim<T: Copy>(
    x: &[T],
    shape: &[usize],
    out_shape: &[usize],
    dims: &[usize],
) -> Vec<T> {
    let n = size(out_shape);
    if n == 0 {
        return Vec::new();
    }
    let st = strides(shape);
    let mut src = vec![0usize; out_shape.len()];
    for (i, &d) in dims.iter().enumerate() {
        if shape[i] != 1 {
            src[d] = st[i];
        }
    }
    strided_gather(x, out_shape, &src)
}

/// [`broadcast_in_dim`] written to `out` (of `size(out_shape)` elements).
pub fn broadcast_in_dim_into<T: Copy>(
    x: &[T],
    shape: &[usize],
    out_shape: &[usize],
    dims: &[usize],
    out: &mut [T],
) {
    if out_shape.len() > 8 {
        out.copy_from_slice(&broadcast_in_dim(x, shape, out_shape, dims));
        return;
    }
    let st = small_strides(shape);
    let mut src = [0usize; 8];
    for (i, &d) in dims.iter().enumerate() {
        if shape[i] != 1 {
            src[d] = st[i];
        }
    }
    strided_gather_into(x, out_shape, &src[..out_shape.len()], out);
}

/// The elements of `x` at `sum(index[d] * src_strides[d])` for every index
/// of `out_shape`, in row-major order: the positions advance by adding
/// strides, and the innermost dimension is filled, copied, or gathered.
pub fn strided_gather<T: Copy>(x: &[T], out_shape: &[usize], src_strides: &[usize]) -> Vec<T> {
    let n = size(out_shape);
    if n == 0 {
        return Vec::new();
    }
    let mut out = vec![x[0]; n];
    strided_gather_into(x, out_shape, src_strides, &mut out);
    out
}

/// [`strided_gather`] written to `out` (of `size(out_shape)` elements),
/// without allocating for up to 8 dimensions.
pub fn strided_gather_into<T: Copy>(
    x: &[T],
    out_shape: &[usize],
    src_strides: &[usize],
    out: &mut [T],
) {
    if out.is_empty() {
        return;
    }
    // Dimensions of size 1 dropped, and each merged into the one before it
    // where contiguous.
    // (At most one per dimension: on the stack for up to 8.)
    let mut stack = [(0usize, 0usize); 8];
    let mut heap = Vec::new();
    let mut nd = 0;
    for (&d, &st) in out_shape.iter().zip(src_strides) {
        if d == 1 {
            continue;
        }
        let dims: &mut [(usize, usize)] = if out_shape.len() <= 8 {
            &mut stack
        } else {
            if heap.is_empty() {
                heap = vec![(0usize, 0usize); out_shape.len()];
            }
            &mut heap
        };
        if nd > 0 && dims[nd - 1].1 == d * st {
            dims[nd - 1] = (dims[nd - 1].0 * d, st);
        } else {
            dims[nd] = (d, st);
            nd += 1;
        }
    }
    let dims: &[(usize, usize)] = if out_shape.len() <= 8 {
        &stack[..nd]
    } else {
        &heap[..nd]
    };
    if dims.is_empty() {
        out.fill(x[0]);
        return;
    }
    // The two innermost dimensions in tight loops, the others by an
    // odometer that adds strides.
    let (inner, inner_st) = dims[dims.len() - 1];
    let (mid, mid_st) = if dims.len() >= 2 {
        dims[dims.len() - 2]
    } else {
        (1, 0)
    };
    let rest = &dims[..dims.len().saturating_sub(2)];
    let block = inner * mid;
    let mut index = [0usize; 8];
    let mut index_heap = if rest.len() > 8 {
        vec![0usize; rest.len()]
    } else {
        Vec::new()
    };
    let index: &mut [usize] = if rest.len() <= 8 {
        &mut index[..rest.len()]
    } else {
        &mut index_heap
    };
    let mut base = 0usize;
    for chunk in out.chunks_exact_mut(block) {
        for (m, row) in chunk.chunks_exact_mut(inner).enumerate() {
            let b = base + m * mid_st;
            match inner_st {
                0 => row.fill(x[b]),
                1 => row.copy_from_slice(&x[b..b + inner]),
                s => {
                    for (j, o) in row.iter_mut().enumerate() {
                        *o = x[b + j * s];
                    }
                }
            }
        }
        for d in (0..rest.len()).rev() {
            index[d] += 1;
            base += rest[d].1;
            if index[d] < rest[d].0 {
                break;
            }
            base -= rest[d].1 * rest[d].0;
            index[d] = 0;
        }
    }
}

/// `transpose`: dimension `i` of the result is dimension `perm[i]` of `x`.
pub fn transpose<T: Copy>(x: &[T], shape: &[usize], perm: &[usize]) -> Vec<T> {
    let st = strides(shape);
    let out_shape: Vec<usize> = perm.iter().map(|&p| shape[p]).collect();
    let src: Vec<usize> = perm.iter().map(|&p| st[p]).collect();
    strided_gather(x, &out_shape, &src)
}

/// [`transpose`] written to `out` (of `size(shape)` elements), without
/// allocating for up to 8 dimensions.
pub fn transpose_into<T: Copy>(x: &[T], shape: &[usize], perm: &[usize], out: &mut [T]) {
    if perm.len() > 8 {
        out.copy_from_slice(&transpose(x, shape, perm));
        return;
    }
    let st = small_strides(shape);
    let (mut out_shape, mut src) = ([0usize; 8], [0usize; 8]);
    for (i, &p) in perm.iter().enumerate() {
        out_shape[i] = shape[p];
        src[i] = st[p];
    }
    let r = perm.len();
    strided_gather_into(x, &out_shape[..r], &src[..r], out);
}

/// `slice` with static bounds and strides.
pub fn slice<T: Copy>(
    x: &[T],
    shape: &[usize],
    start: &[usize],
    limit: &[usize],
    step: &[usize],
) -> Vec<T> {
    let st = strides(shape);
    let out_shape: Vec<usize> = (0..shape.len())
        .map(|i| (limit[i].saturating_sub(start[i])).div_ceil(step[i]))
        .collect();
    map_indices(&out_shape, |out| {
        let flat: usize = (0..shape.len())
            .map(|i| (start[i] + out[i] * step[i]) * st[i])
            .sum();
        x[flat]
    })
}

/// Clamps start indices so that a window of `sizes` stays inside `shape`,
/// as XLA does for `dynamic_slice` and `dynamic_update_slice`.
pub fn clamp_starts(starts: &[i64], shape: &[usize], sizes: &[usize]) -> Vec<usize> {
    starts
        .iter()
        .zip(shape.iter().zip(sizes))
        .map(|(&s, (&n, &k))| s.clamp(0, (n - k) as i64) as usize)
        .collect()
}

/// `dynamic_slice`: a window of `sizes` at (clamped) `starts`.
pub fn dynamic_slice<T: Copy>(x: &[T], shape: &[usize], starts: &[i64], sizes: &[usize]) -> Vec<T> {
    let start = clamp_starts(starts, shape, sizes);
    let ones = vec![1; shape.len()];
    let limit: Vec<usize> = start.iter().zip(sizes).map(|(s, k)| s + k).collect();
    slice(x, shape, &start, &limit, &ones)
}

/// `dynamic_update_slice`: `x` with `update` written at (clamped) `starts`.
pub fn dynamic_update_slice<T: Copy>(
    x: &[T],
    shape: &[usize],
    update: &[T],
    update_shape: &[usize],
    starts: &[i64],
) -> Vec<T> {
    let start = clamp_starts(starts, shape, update_shape);
    let st = strides(shape);
    let mut out = x.to_vec();
    let mut i = 0;
    map_indices(update_shape, |u| {
        let flat: usize = (0..shape.len()).map(|d| (start[d] + u[d]) * st[d]).sum();
        out[flat] = update[i];
        i += 1;
    });
    out
}

/// `concatenate` along `dim`.
pub fn concatenate<T: Copy>(parts: &[(&[T], &[usize])], dim: usize) -> Vec<T> {
    let shape0 = parts[0].1;
    let outer: usize = shape0[..dim].iter().product();
    let mut out = Vec::new();
    for o in 0..outer {
        for (x, shape) in parts {
            let inner: usize = shape[dim..].iter().product();
            out.extend_from_slice(&x[o * inner..(o + 1) * inner]);
        }
    }
    out
}

/// `pad`: for each dimension, `(low, high, interior)` padding with `value`.
/// Negative `low` or `high` removes elements.
pub fn pad<T: Copy>(x: &[T], shape: &[usize], value: T, config: &[(i64, i64, usize)]) -> Vec<T> {
    let out_shape: Vec<usize> = shape
        .iter()
        .zip(config)
        .map(|(&n, &(lo, hi, int))| {
            let inner = if n == 0 { 0 } else { n + (n - 1) * int } as i64;
            (lo + hi + inner).max(0) as usize
        })
        .collect();
    let st = strides(shape);
    map_indices(&out_shape, |out| {
        let mut flat = 0;
        for d in 0..shape.len() {
            let (lo, _, int) = config[d];
            let pos = out[d] as i64 - lo;
            let step = int as i64 + 1;
            if pos < 0 || pos % step != 0 || pos / step >= shape[d] as i64 {
                return value;
            }
            flat += (pos / step) as usize * st[d];
        }
        x[flat]
    })
}

/// `rev`: reverses the elements along `dims`.
pub fn rev<T: Copy>(x: &[T], shape: &[usize], dims: &[usize]) -> Vec<T> {
    let n = size(shape);
    if n == 0 {
        return Vec::new();
    }
    // The trailing dimensions that are not reversed form contiguous blocks,
    // copied whole; the dimensions before them are walked by an odometer
    // (the last of them, reversed, in a loop).
    let mut k = shape.len();
    let mut block = 1;
    while k > 0 && !dims.contains(&(k - 1)) {
        k -= 1;
        block *= shape[k];
    }
    if k == 0 {
        return x.to_vec();
    }
    let outer = &shape[..k - 1];
    let last = shape[k - 1];
    // Strides in blocks.
    let mut st = vec![0usize; k];
    let mut s = 1;
    for d in (0..k).rev() {
        st[d] = s;
        s *= shape[d];
    }
    let mut out = Vec::with_capacity(n);
    let mut index = vec![0usize; outer.len()];
    loop {
        let base: usize = index
            .iter()
            .enumerate()
            .map(|(d, &i)| {
                let i = if dims.contains(&d) {
                    shape[d] - 1 - i
                } else {
                    i
                };
                i * st[d]
            })
            .sum();
        for j in (0..last).rev() {
            let src = (base + j) * block;
            out.extend_from_slice(&x[src..src + block]);
        }
        // The next index of the outer dimensions.
        let mut d = outer.len();
        loop {
            if d == 0 {
                return out;
            }
            d -= 1;
            index[d] += 1;
            if index[d] < outer[d] {
                break;
            }
            index[d] = 0;
        }
    }
}

/// The order of `lax.sort` keys: integers and booleans in their natural
/// order, and floats in the total order `-inf < ... < 0 < ... < inf < NaN`
/// in which `-0.0` equals `0.0` and all NaNs are equal, as JAX's comparator
/// makes it by canonicalizing zeros and NaNs before a total-order
/// comparison.
///
/// Complex numbers order lexicographically by their real and imaginary
/// parts, each in the order of floats, as JAX's comparator splits them into
/// two keys.
pub fn sort_order<T: Element>(a: T, b: T) -> Ordering {
    if let (Value::Complex(ar, ai), Value::Complex(br, bi)) = (a.to_value(), b.to_value()) {
        return sort_order(ar, br).then_with(|| sort_order(ai, bi));
    }
    // `x != x` holds only for NaN.
    #[allow(clippy::eq_op)]
    let (a_nan, b_nan) = (a != a, b != b);
    match (a_nan, b_nan) {
        (true, true) => Ordering::Equal,
        (true, false) => Ordering::Greater,
        (false, true) => Ordering::Less,
        (false, false) => a.partial_cmp(&b).unwrap_or(Ordering::Equal),
    }
}

/// The permutation that sorts along `dim` stably by `cmp`, which compares
/// the flat indices of two elements: for each element of the result, the
/// flat index of the element it comes from.
pub fn sort_permutation(
    shape: &[usize],
    dim: usize,
    cmp: impl Fn(usize, usize) -> Ordering,
) -> Vec<usize> {
    let n = shape[dim];
    let inner: usize = shape[dim + 1..].iter().product();
    let outer: usize = shape[..dim].iter().product();
    let mut perm = vec![0; size(shape)];
    let mut line: Vec<usize> = Vec::with_capacity(n);
    for o in 0..outer {
        for i in 0..inner {
            let base = o * n * inner + i;
            line.clear();
            line.extend((0..n).map(|k| base + k * inner));
            // `sort_by` is stable.
            line.sort_by(|&a, &b| cmp(a, b));
            for (k, &src) in line.iter().enumerate() {
                perm[base + k * inner] = src;
            }
        }
    }
    perm
}

/// `sort`: sorts the operands (of the same shape) along `dim`, stably and
/// lexicographically by the first `num_keys` of them in [`sort_order`].
pub fn sort(operands: &[&Buffer], shape: &[usize], dim: usize, num_keys: usize) -> Vec<Buffer> {
    type Cmp<'a> = Box<dyn Fn(usize, usize) -> Ordering + 'a>;
    let keys: Vec<Cmp<'_>> = operands[..num_keys]
        .iter()
        .map(|b| crate::with_buffer!(b, |v| Box::new(|i, j| sort_order(v[i], v[j])) as Cmp<'_>))
        .collect();
    let perm = sort_permutation(shape, dim, |i, j| {
        keys.iter()
            .map(|cmp| cmp(i, j))
            .find(|&o| o != Ordering::Equal)
            .unwrap_or(Ordering::Equal)
    });
    operands
        .iter()
        .map(|b| {
            crate::with_buffer!(b, |v| Buffer::from_vec(
                perm.iter().map(|&p| v[p]).collect()
            ))
        })
        .collect()
}

/// `iota`: the index along `dim` of each element of `shape`.
pub fn iota<T: Element>(shape: &[usize], dim: usize) -> Vec<T> {
    let mut out = vec![T::default(); size(shape)];
    iota_into(shape, dim, &mut out);
    out
}

/// [`iota`] written to `out` (of `size(shape)` elements), without
/// allocating.
pub fn iota_into<T: Element>(shape: &[usize], dim: usize, out: &mut [T]) {
    // Runs of `inner` equal values, `n` values per block.
    let n = shape[dim];
    let inner: usize = shape[dim + 1..].iter().product();
    if n == 0 || inner == 0 {
        return;
    }
    for block in out.chunks_exact_mut(n * inner) {
        for (k, run) in block.chunks_exact_mut(inner).enumerate() {
            run.fill(cast::<u64, T>(k as u64));
        }
    }
}

/// A reduction.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum ReduceOp {
    /// Sum (integers wrap around).
    Sum,
    /// Maximum, propagating NaN (logical or for booleans).
    Max,
    /// Minimum, propagating NaN (logical and for booleans).
    Min,
}

impl ReduceOp {
    /// The binary operation that combines elements.
    pub fn binary(self) -> BinaryOp {
        match self {
            ReduceOp::Sum => BinaryOp::Add,
            ReduceOp::Max => BinaryOp::Max,
            ReduceOp::Min => BinaryOp::Min,
        }
    }

    /// The identity.
    pub fn identity<T: Element>(self) -> T {
        match self {
            ReduceOp::Sum => T::default(),
            ReduceOp::Max => T::lowest(),
            ReduceOp::Min => T::highest(),
        }
    }
}

/// Returns `shape` without `axes`.
pub fn reduced_shape(shape: &[usize], axes: &[usize]) -> Vec<usize> {
    shape
        .iter()
        .enumerate()
        .filter(|(i, _)| !axes.contains(i))
        .map(|(_, &d)| d)
        .collect()
}

/// Reduces `x` over `axes`, combining elements in row-major order.
pub fn reduce<T: Element>(x: &[T], shape: &[usize], axes: &[usize], op: ReduceOp) -> Vec<T> {
    // Reduced axes that are contiguous (after sorting) make the operand
    // `[pre, n, post]`, reduced over `n` in order.
    let mut sorted = axes.to_vec();
    sorted.sort_unstable();
    if sorted.windows(2).all(|w| w[1] == w[0] + 1)
        && sorted.last().is_some_and(|&a| a < shape.len())
    {
        let (a, b) = (sorted[0], sorted[sorted.len() - 1] + 1);
        let pre = size(&shape[..a]);
        let n = size(&shape[a..b]);
        let post = size(&shape[b..]);
        let mut out = vec![op.identity::<T>(); pre * post];
        match op {
            ReduceOp::Sum => reduce_middle(x, &mut out, [pre, n, post], |a, b| {
                T::binary(BinaryOp::Add, a, b)
            }),
            ReduceOp::Max => reduce_middle(x, &mut out, [pre, n, post], |a, b| {
                T::binary(BinaryOp::Max, a, b)
            }),
            ReduceOp::Min => reduce_middle(x, &mut out, [pre, n, post], |a, b| {
                T::binary(BinaryOp::Min, a, b)
            }),
        }
        return out;
    }
    let out_shape = reduced_shape(shape, axes);
    let out_st = strides(&out_shape);
    let mut out = vec![op.identity::<T>(); size(&out_shape)];
    // The stride in the result of each operand dimension (0 if reduced).
    let mut kept = out_st.iter();
    let st: Vec<usize> = (0..shape.len())
        .map(|d| {
            if axes.contains(&d) {
                0
            } else {
                *kept.next().expect("one stride per kept dimension")
            }
        })
        .collect();
    match op {
        ReduceOp::Sum => reduce_strided(x, &mut out, shape, &st, |a, b| {
            T::binary(BinaryOp::Add, a, b)
        }),
        ReduceOp::Max => reduce_strided(x, &mut out, shape, &st, |a, b| {
            T::binary(BinaryOp::Max, a, b)
        }),
        ReduceOp::Min => reduce_strided(x, &mut out, shape, &st, |a, b| {
            T::binary(BinaryOp::Min, a, b)
        }),
    }
    out
}

/// `out[o] = f(out[o], x[i])` for every element `i` of `x` (of `shape`) in
/// order, with `o` the dot product of its index and `st` (the strides in
/// `out`, 0 for reduced dimensions): rows of the last dimension at a time,
/// with the offset of each row updated as an odometer.
#[inline(always)]
fn reduce_strided<T: Element>(
    x: &[T],
    out: &mut [T],
    shape: &[usize],
    st: &[usize],
    f: impl Fn(T, T) -> T,
) {
    let Some((&inner, outer_shape)) = shape.split_last() else {
        if let (Some(o), Some(&v)) = (out.first_mut(), x.first()) {
            *o = f(*o, v);
        }
        return;
    };
    if inner == 0 {
        return;
    }
    let s_in = st[shape.len() - 1];
    let mut index = vec![0usize; outer_shape.len()];
    let mut base = 0usize;
    for row in x.chunks_exact(inner) {
        if s_in == 0 {
            let mut acc = out[base];
            for &v in row {
                acc = f(acc, v);
            }
            out[base] = acc;
        } else {
            for (j, &v) in row.iter().enumerate() {
                let o = base + j * s_in;
                out[o] = f(out[o], v);
            }
        }
        for d in (0..outer_shape.len()).rev() {
            index[d] += 1;
            base += st[d];
            if index[d] < outer_shape[d] {
                break;
            }
            base -= st[d] * outer_shape[d];
            index[d] = 0;
        }
    }
}

/// `out[p, q] = f(...f(out[p, q], x[p, 0, q])..., x[p, n - 1, q])` for `x` of
/// shape `[pre, n, post]`.
#[inline(always)]
fn reduce_middle<T: Element>(
    x: &[T],
    out: &mut [T],
    [pre, n, post]: [usize; 3],
    f: impl Fn(T, T) -> T,
) {
    if post == 1 {
        // Rows of `n` contiguous elements.
        for (o, row) in out.iter_mut().zip(x.chunks_exact(n.max(1))) {
            for &v in row {
                *o = f(*o, v);
            }
        }
        return;
    }
    for p in 0..pre {
        let o = &mut out[p * post..(p + 1) * post];
        for k in 0..n {
            let row = &x[(p * n + k) * post..(p * n + k + 1) * post];
            for (o, &v) in o.iter_mut().zip(row) {
                *o = f(*o, v);
            }
        }
    }
}

/// `x` folded by `op` from `op`'s identity, element by element in order.
/// Integers and booleans, whose operations are associative, are folded in
/// eight lanes, which gives the same result.
pub fn reduce_all<T: Element>(x: &[T], op: ReduceOp) -> T {
    let id = op.identity::<T>();
    let associative = !matches!(
        T::DTYPE.kind(),
        crate::DTypeKind::Float | crate::DTypeKind::Complex
    );
    match op {
        ReduceOp::Sum => fold(x, id, associative, |a, b| T::binary(BinaryOp::Add, a, b)),
        ReduceOp::Max => fold(x, id, associative, |a, b| T::binary(BinaryOp::Max, a, b)),
        ReduceOp::Min => fold(x, id, associative, |a, b| T::binary(BinaryOp::Min, a, b)),
    }
}

#[inline(always)]
fn fold<T: Element>(x: &[T], id: T, associative: bool, f: impl Fn(T, T) -> T) -> T {
    if associative && x.len() >= 16 {
        let mut lanes = [id; 8];
        let (chunks, rest) = x.as_chunks::<8>();
        for c in chunks {
            for (l, &v) in lanes.iter_mut().zip(c) {
                *l = f(*l, v);
            }
        }
        let acc = lanes.into_iter().fold(id, &f);
        return rest.iter().fold(acc, |a, &v| f(a, v));
    }
    x.iter().fold(id, |a, &v| f(a, v))
}

/// The index of the largest (`max`) or smallest element along `axis`. NaN
/// counts as the extreme, and ties take the first index, as in JAX.
pub fn arg_min_max<T: Element>(x: &[T], shape: &[usize], axis: usize, max: bool) -> Vec<u64> {
    let n = shape[axis];
    let post: usize = shape[axis + 1..].iter().product();
    let pre: usize = shape[..axis].iter().product();
    let mut out = Vec::with_capacity(pre * post);
    for p in 0..pre {
        for q in 0..post {
            let mut best = 0usize;
            let mut best_v: Option<T> = None;
            for k in 0..n {
                let v = x[(p * n + k) * post + q];
                let better = match best_v {
                    None => true,
                    Some(b) => {
                        // `x != x` tests for NaN without a `Float` bound.
                        #[allow(clippy::eq_op)]
                        let (v_nan, b_nan) = (v != v, b != b);
                        if b_nan {
                            false
                        } else if v_nan {
                            true
                        } else if max {
                            v > b
                        } else {
                            v < b
                        }
                    }
                };
                if better {
                    best = k;
                    best_v = Some(v);
                }
            }
            out.push(best as u64);
        }
    }
    out
}

/// The operation of a cumulative reduction (`cumsum` and the like).
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum CumulativeOp {
    /// Sum (integers wrap around).
    Sum,
    /// Product (integers wrap around).
    Prod,
    /// Maximum, propagating NaN.
    Max,
    /// Minimum, propagating NaN.
    Min,
    /// `log(exp(a) + exp(b))`, computed as JAX's `logaddexp` (floats only).
    LogSumExp,
}

impl CumulativeOp {
    /// The identity: the initial value of XLA's `reduce_window`.
    pub fn identity<T: Element>(self) -> T {
        match self {
            CumulativeOp::Sum => T::default(),
            CumulativeOp::Prod => cast::<u64, T>(1),
            CumulativeOp::Max | CumulativeOp::LogSumExp => T::lowest(),
            CumulativeOp::Min => T::highest(),
        }
    }

    /// Combines an accumulated value with the next element.
    #[inline]
    pub fn combine<T: Element>(self, a: T, b: T) -> T {
        match self {
            CumulativeOp::Sum => T::binary(BinaryOp::Add, a, b),
            CumulativeOp::Prod => T::binary(BinaryOp::Mul, a, b),
            CumulativeOp::Max => T::binary(BinaryOp::Max, a, b),
            CumulativeOp::Min => T::binary(BinaryOp::Min, a, b),
            CumulativeOp::LogSumExp => {
                // JAX's `logaddexp`: `max(a, b) + log1p(exp(-|a - b|))`, or
                // `a + b` where `a - b` is NaN (NaNs, or infinities of the
                // same sign).
                let delta = T::binary(BinaryOp::Sub, a, b);
                #[allow(clippy::eq_op)] // `x != x` holds only for NaN
                if delta != delta {
                    T::binary(BinaryOp::Add, a, b)
                } else {
                    let amax = T::binary(BinaryOp::Max, a, b);
                    let e = T::unary(UnaryOp::Neg, T::unary(UnaryOp::Abs, delta));
                    let l = T::unary(UnaryOp::Log1p, T::unary(UnaryOp::Exp, e));
                    T::binary(BinaryOp::Add, amax, l)
                }
            }
        }
    }
}

/// The length of the blocks of XLA's `ReduceWindowRewriter`, which rewrites
/// a long cumulative `reduce_window` on CPU into scans of blocks.
const SCAN_BLOCK: usize = 16;

/// The window of XLA's `reduce_window` (on CPU) at each position, written to
/// `out`: `init` combined with the elements of the window in order. The
/// window of a forward scan ends at the position, and that of a reverse
/// scan starts there; with `exclusive`, the position itself is left out.
fn scan_windows_into<T: Element>(
    x: &[T],
    out: &mut [T],
    reverse: bool,
    exclusive: bool,
    op: CumulativeOp,
) {
    let init = op.identity::<T>();
    if !reverse {
        // Each window extends the previous one, so a running value folds
        // the elements in the same order.
        let mut acc = init;
        for (o, &v) in out.iter_mut().zip(x) {
            let before = acc;
            acc = op.combine(acc, v);
            *o = if exclusive { before } else { acc };
        }
    } else {
        for (i, o) in out.iter_mut().enumerate() {
            let start = if exclusive { i + 1 } else { i };
            *o = x[start..].iter().fold(init, |acc, &v| op.combine(acc, v));
        }
    }
}

/// An inclusive scan of one line, written to `out`, as XLA computes
/// `reduce_window` with a window as long as the line on CPU (as JAX lowers
/// cumulative reductions): lines up to [`SCAN_BLOCK`] long directly, and
/// longer lines as XLA's `ReduceWindowRewriter` rewrites them. The line is
/// padded with the identity to whole blocks, each block is scanned, the
/// totals of the blocks are scanned exclusively (recursively), and each
/// element is combined with the total before its block.
fn scan_line_into<T: Element>(x: &[T], out: &mut [T], reverse: bool, op: CumulativeOp) {
    let n = x.len();
    if n <= SCAN_BLOCK {
        scan_windows_into(x, out, reverse, false, op);
        return;
    }
    let init = op.identity::<T>();
    let blocks = n.div_ceil(SCAN_BLOCK);
    let mut totals = vec![init; blocks];
    let (mut block, mut scanned) = ([init; SCAN_BLOCK], [init; SCAN_BLOCK]);
    for (b, total) in totals.iter_mut().enumerate() {
        let (lo, hi) = (b * SCAN_BLOCK, ((b + 1) * SCAN_BLOCK).min(n));
        block[..hi - lo].copy_from_slice(&x[lo..hi]);
        block[hi - lo..].fill(init);
        scan_windows_into(&block, &mut scanned, reverse, false, op);
        out[lo..hi].copy_from_slice(&scanned[..hi - lo]);
        *total = if reverse {
            scanned[0]
        } else {
            scanned[SCAN_BLOCK - 1]
        };
    }
    let mut outer = vec![init; blocks];
    if blocks <= SCAN_BLOCK {
        scan_windows_into(&totals, &mut outer, reverse, true, op);
    } else {
        // An exclusive scan is rewritten as an inclusive one, shifted.
        let mut inclusive = vec![init; blocks];
        scan_line_into(&totals, &mut inclusive, reverse, op);
        if reverse {
            outer[..blocks - 1].copy_from_slice(&inclusive[1..]);
        } else {
            outer[1..].copy_from_slice(&inclusive[..blocks - 1]);
        }
    }
    for (i, o) in out.iter_mut().enumerate() {
        *o = op.combine(*o, outer[i / SCAN_BLOCK]);
    }
}

/// A cumulative reduction along `axis` (inclusive; from the end with
/// `reverse`), combining elements in the order XLA does on CPU.
pub fn cumulative<T: Element>(
    x: &[T],
    shape: &[usize],
    axis: usize,
    reverse: bool,
    op: CumulativeOp,
) -> Vec<T> {
    let mut out = vec![T::default(); x.len()];
    cumulative_into(x, shape, axis, reverse, op, &mut out);
    out
}

/// [`cumulative`] written to `out` (of the size of `x`).
pub fn cumulative_into<T: Element>(
    x: &[T],
    shape: &[usize],
    axis: usize,
    reverse: bool,
    op: CumulativeOp,
    out: &mut [T],
) {
    let n = shape[axis];
    let inner: usize = shape[axis + 1..].iter().product();
    let outer: usize = shape[..axis].iter().product();
    if inner == 1 {
        for o in 0..outer {
            let base = o * n;
            scan_line_into(&x[base..base + n], &mut out[base..base + n], reverse, op);
        }
        return;
    }
    let (mut line, mut scanned) = (vec![T::default(); n], vec![T::default(); n]);
    for o in 0..outer {
        for i in 0..inner {
            let base = o * n * inner + i;
            for (k, l) in line.iter_mut().enumerate() {
                *l = x[base + k * inner];
            }
            scan_line_into(&line, &mut scanned, reverse, op);
            for (k, &v) in scanned.iter().enumerate() {
                out[base + k * inner] = v;
            }
        }
    }
}

/// The key by which `top_k` orders elements, as XLA's comparator does: the
/// total order of floats by their bits (`-NaN < -inf < ... < -0.0 < 0.0 <
/// ... < inf < NaN`), and the natural order of integers and booleans.
fn top_k_key<T: Element>(v: T) -> i128 {
    let dtype = T::DTYPE;
    if dtype.is_float() {
        let bits = 8 * dtype.size_in_bytes() as u32;
        // Sign-extend the bit pattern, then flip the magnitude of negative
        // values so that they order in reverse.
        let shift = 64 - bits;
        let s = ((v.to_bits() << shift) as i64) >> shift;
        let s = if s < 0 {
            s ^ (u64::MAX >> (65 - bits)) as i64
        } else {
            s
        };
        i128::from(s)
    } else {
        match v.to_value() {
            Value::Int(i) => i128::from(i),
            Value::UInt(u) => i128::from(u),
            _ => i128::from(v.to_bits()),
        }
    }
}

/// `top_k` along `axis`: the `k` largest elements of each line in
/// descending order (ties in their original order), and their indices.
pub fn top_k<T: Element>(x: &[T], shape: &[usize], k: usize, axis: usize) -> (Vec<T>, Vec<i32>) {
    let rank = shape.len();
    if axis + 1 == rank {
        return top_k_last(x, shape, k);
    }
    // Move the axis last and back (the permutation is its own inverse).
    let mut perm: Vec<usize> = (0..rank).collect();
    perm.swap(axis, rank - 1);
    let moved: Vec<usize> = perm.iter().map(|&d| shape[d]).collect();
    let (values, indices) = top_k_last(&transpose(x, shape, &perm), &moved, k);
    let mut out = moved;
    out[rank - 1] = k;
    (
        transpose(&values, &out, &perm),
        transpose(&indices, &out, &perm),
    )
}

/// [`top_k`] along the last dimension.
fn top_k_last<T: Element>(x: &[T], shape: &[usize], k: usize) -> (Vec<T>, Vec<i32>) {
    let n = *shape.last().expect("top_k needs at least one dimension");
    let lines = size(&shape[..shape.len() - 1]);
    let mut values = Vec::with_capacity(lines * k);
    let mut indices = Vec::with_capacity(lines * k);
    let mut order: Vec<usize> = Vec::with_capacity(n);
    for l in 0..lines {
        let line = &x[l * n..(l + 1) * n];
        order.clear();
        order.extend(0..n);
        // `sort_by` is stable.
        order.sort_by(|&a, &b| top_k_key(line[b]).cmp(&top_k_key(line[a])));
        for &i in &order[..k] {
            values.push(line[i]);
            indices.push(i as i32);
        }
    }
    (values, indices)
}

/// The dimensions that `dot_general` contracts and batches over. The result
/// has the batch dimensions, then the free dimensions of the left operand,
/// then those of the right operand.
#[derive(Clone, PartialEq, Eq, Hash, Debug, Default)]
pub struct DotDims {
    /// Contracting dimensions of the left operand.
    pub lhs_contracting: Vec<usize>,
    /// Contracting dimensions of the right operand.
    pub rhs_contracting: Vec<usize>,
    /// Batch dimensions of the left operand.
    pub lhs_batch: Vec<usize>,
    /// Batch dimensions of the right operand.
    pub rhs_batch: Vec<usize>,
}

/// The dimensions of an operand that are neither contracted nor batched.
pub fn free_dims(rank: usize, contracting: &[usize], batch: &[usize]) -> Vec<usize> {
    (0..rank)
        .filter(|d| !contracting.contains(d) && !batch.contains(d))
        .collect()
}

/// The shape of the result of `dot_general`.
pub fn dot_shape(lhs: &[usize], rhs: &[usize], d: &DotDims) -> Vec<usize> {
    let mut out: Vec<usize> = d.lhs_batch.iter().map(|&i| lhs[i]).collect();
    out.extend(
        free_dims(lhs.len(), &d.lhs_contracting, &d.lhs_batch)
            .iter()
            .map(|&i| lhs[i]),
    );
    out.extend(
        free_dims(rhs.len(), &d.rhs_contracting, &d.rhs_batch)
            .iter()
            .map(|&i| rhs[i]),
    );
    out
}

/// `dot_general`: sums of products over the contracting dimensions, in the
/// operands' type.
pub fn dot_general<T: Element>(
    lhs: &[T],
    lshape: &[usize],
    rhs: &[T],
    rshape: &[usize],
    d: &DotDims,
) -> Vec<T> {
    // Like XLA on CPU, 16-bit floats are multiplied and accumulated in `f32`
    // and rounded once.
    if matches!(T::DTYPE, DType::F16 | DType::BF16) {
        let wide = |x: &[T]| {
            x.iter()
                .map(|&v| crate::cast::<T, f32>(v))
                .collect::<Vec<f32>>()
        };
        return dot_general(&wide(lhs), lshape, &wide(rhs), rshape, d)
            .into_iter()
            .map(crate::cast::<f32, T>)
            .collect();
    }
    // Every product is computed as a batch of matrix products `[M, K] x
    // [K, N]`: the operands are permuted (copied only if needed) to `[batch,
    // free, contracting]` and `[batch, contracting, free]`, the contracting
    // dimensions in the order of `d` (row-major), which is the order of the
    // sums, so every element is summed in the same order whatever the
    // layout.
    let lfree = free_dims(lshape.len(), &d.lhs_contracting, &d.lhs_batch);
    let rfree = free_dims(rshape.len(), &d.rhs_contracting, &d.rhs_batch);
    let lperm: Vec<usize> = d
        .lhs_batch
        .iter()
        .chain(&lfree)
        .chain(&d.lhs_contracting)
        .copied()
        .collect();
    let rperm: Vec<usize> = d
        .rhs_batch
        .iter()
        .chain(&d.rhs_contracting)
        .chain(&rfree)
        .copied()
        .collect();
    let lt = permuted(lhs, lshape, &lperm);
    let rt = permuted(rhs, rshape, &rperm);
    let batch: usize = d.lhs_batch.iter().map(|&i| lshape[i]).product();
    let m: usize = lfree.iter().map(|&i| lshape[i]).product();
    let kk: usize = d.lhs_contracting.iter().map(|&i| lshape[i]).product();
    let n: usize = rfree.iter().map(|&i| rshape[i]).product();
    let mut out = vec![T::default(); batch * m * n];
    if m * n == 0 || kk == 0 {
        return out;
    }
    for ((o, l), r) in out
        .chunks_exact_mut(m * n)
        .zip(lt.chunks_exact(m * kk))
        .zip(rt.chunks_exact(kk * n))
    {
        matmul_rows(o, l, r, kk, n);
    }
    out
}

/// `x` transposed by `perm`, borrowed if `perm` is the identity.
fn permuted<'a, T: Copy>(x: &'a [T], shape: &[usize], perm: &[usize]) -> std::borrow::Cow<'a, [T]> {
    if perm.iter().enumerate().all(|(i, &p)| i == p) {
        std::borrow::Cow::Borrowed(x)
    } else {
        std::borrow::Cow::Owned(transpose(x, shape, perm))
    }
}

/// `out += l r` for row-major `l` (`m x kk`) and `r` (`kk x n`), where `out`
/// starts at zero: each row of the result is accumulated over `k` in order,
/// a whole row at a time, so that the loop over the columns vectorizes.
fn matmul_rows<T: Element>(out: &mut [T], l: &[T], r: &[T], kk: usize, n: usize) {
    let fma = |o: T, a: T, b: T| T::binary(BinaryOp::Add, o, T::binary(BinaryOp::Mul, a, b));
    let m = out.len() / n;
    let full_cols = n - n % TILE_COLS;
    let mut i = 0;
    // Tiles of 4 x `TILE_COLS` elements of the result stay in registers for
    // the whole loop over `k`; each element is summed over `k` in order.
    while i + 4 <= m {
        let mut j = 0;
        while j < full_cols {
            let mut acc = [[T::default(); TILE_COLS]; 4];
            for k in 0..kk {
                let rrow: &[T; TILE_COLS] = r[k * n + j..k * n + j + TILE_COLS]
                    .try_into()
                    .expect("tile");
                for (t, accrow) in acc.iter_mut().enumerate() {
                    let a = l[(i + t) * kk + k];
                    for (x, &b) in accrow.iter_mut().zip(rrow) {
                        *x = fma(*x, a, b);
                    }
                }
            }
            for (t, accrow) in acc.iter().enumerate() {
                out[(i + t) * n + j..(i + t) * n + j + TILE_COLS].copy_from_slice(accrow);
            }
            j += TILE_COLS;
        }
        i += 4;
    }
    // The remaining rows and columns, a row at a time.
    for row in 0..m {
        let cols = if row < i { full_cols..n } else { 0..n };
        if cols.is_empty() {
            continue;
        }
        let lrow = &l[row * kk..(row + 1) * kk];
        let orow = &mut out[row * n + cols.start..row * n + cols.end];
        for (k, &a) in lrow.iter().enumerate() {
            let rrow = &r[k * n + cols.start..k * n + cols.end];
            for (o, &b) in orow.iter_mut().zip(rrow) {
                *o = fma(*o, a, b);
            }
        }
    }
}

/// The columns of a tile of [`matmul_rows`].
const TILE_COLS: usize = 16;

/// `select_n`: element `i` comes from `cases[which[i]]` (`which` is a scalar
/// or has the shape of the cases). Out-of-range indices are clamped.
pub fn select_n<T: Copy>(which: &[usize], cases: &[&[T]]) -> Vec<T> {
    let n = cases[0].len();
    (0..n)
        .map(|i| {
            let w = if which.len() == 1 { which[0] } else { which[i] };
            cases[w.min(cases.len() - 1)][i]
        })
        .collect()
}

/// `clamp(lo, x, hi)`, propagating NaN; `lo` and `hi` are scalars or have
/// the shape of `x`.
pub fn clamp<T: Element>(lo: &[T], x: &[T], hi: &[T]) -> Vec<T> {
    let at = |a: &[T], i: usize| if a.len() == 1 { a[0] } else { a[i] };
    (0..x.len())
        .map(|i| {
            let v = T::binary(BinaryOp::Max, x[i], at(lo, i));
            T::binary(BinaryOp::Min, v, at(hi, i))
        })
        .collect()
}

/// How `gather` and `scatter` treat out-of-bounds indices.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
pub enum GatherScatterMode {
    /// Indices are clamped so that the slice or window is in bounds.
    #[default]
    Clip,
    /// Out-of-bounds updates are dropped (scatter only).
    FillOrDrop,
    /// The caller promises that indices are in bounds; XLA's native behavior
    /// (clamping for gather, dropping for scatter) applies otherwise.
    PromiseInBounds,
}

/// StableHLO's gather dimension numbers; the index vector is the last
/// dimension of the indices, as in JAX.
#[derive(Clone, PartialEq, Eq, Hash, Debug, Default)]
pub struct GatherDims {
    /// The dimensions of the result that index into a slice.
    pub offset_dims: Vec<usize>,
    /// Operand dimensions whose slices have size 1 and are dropped.
    pub collapsed_slice_dims: Vec<usize>,
    /// The operand dimension that each index vector component starts.
    pub start_index_map: Vec<usize>,
    /// Operand batching dimensions, matched with `start_indices_batching_dims`.
    pub operand_batching_dims: Vec<usize>,
    /// Batching dimensions of the indices.
    pub start_indices_batching_dims: Vec<usize>,
}

/// StableHLO's scatter dimension numbers; the index vector is the last
/// dimension of the indices, as in JAX.
#[derive(Clone, PartialEq, Eq, Hash, Debug, Default)]
pub struct ScatterDims {
    /// The dimensions of the updates that index into a window.
    pub update_window_dims: Vec<usize>,
    /// Operand dimensions whose windows have size 1 and are not in the updates.
    pub inserted_window_dims: Vec<usize>,
    /// The operand dimension that each index vector component starts.
    pub scatter_dims_to_operand_dims: Vec<usize>,
    /// Operand batching dimensions, matched with `scatter_indices_batching_dims`.
    pub operand_batching_dims: Vec<usize>,
    /// Batching dimensions of the indices.
    pub scatter_indices_batching_dims: Vec<usize>,
}

/// The shape of the result of a gather.
pub fn gather_shape(indices: &[usize], d: &GatherDims, slice_sizes: &[usize]) -> Vec<usize> {
    let q = indices.len();
    let out_rank = d.offset_dims.len() + q - 1;
    let mut offsets = (0..slice_sizes.len())
        .filter(|i| !d.collapsed_slice_dims.contains(i) && !d.operand_batching_dims.contains(i))
        .map(|i| slice_sizes[i]);
    let mut batch = indices[..q - 1].iter().copied();
    (0..out_rank)
        .map(|i| {
            if d.offset_dims.contains(&i) {
                offsets.next().expect("offset dimension")
            } else {
                batch.next().expect("batch dimension")
            }
        })
        .collect()
}

/// `gather`, with start indices clamped so that slices are in bounds (the
/// semantics of every mode that gather supports).
pub fn gather<T: Copy>(
    x: &[T],
    shape: &[usize],
    indices: &[i64],
    indices_shape: &[usize],
    d: &GatherDims,
    slice_sizes: &[usize],
) -> Vec<T> {
    let out_shape = gather_shape(indices_shape, d, slice_sizes);
    let st = strides(shape);
    let out_st = strides(&out_shape);
    let q = indices_shape.len();
    let vec_len = indices_shape[q - 1];
    let batch_dims: Vec<usize> = (0..out_shape.len())
        .filter(|i| !d.offset_dims.contains(i))
        .collect();
    let offset_operand: Vec<usize> = (0..shape.len())
        .filter(|i| !d.collapsed_slice_dims.contains(i) && !d.operand_batching_dims.contains(i))
        .collect();
    // The positions of the slice elements in the operand and in the result,
    // relative to the start of the slice and of its place in the result.
    let slice_shape: Vec<usize> = offset_operand.iter().map(|&od| slice_sizes[od]).collect();
    let mut slice_x = Vec::with_capacity(slice_shape.iter().product());
    let mut slice_out = Vec::with_capacity(slice_x.capacity());
    for_each_index(&slice_shape, |o| {
        let mut ox = 0;
        let mut oo = 0;
        for (k, &v) in o.iter().enumerate() {
            ox += v * st[offset_operand[k]];
            oo += v * out_st[d.offset_dims[k]];
        }
        slice_x.push(ox);
        slice_out.push(oo);
    });
    let batch_shape = &indices_shape[..q - 1];
    let size: usize = out_shape.iter().product();
    if size == 0 {
        return Vec::new();
    }
    // Every position of the result is written below.
    let mut out = vec![x[0]; size];
    let mut b = 0;
    for_each_index(batch_shape, |batch| {
        let start = &indices[b * vec_len..(b + 1) * vec_len];
        let mut base = 0;
        for (&i, &od) in start.iter().zip(&d.start_index_map) {
            let hi = (shape[od] - slice_sizes[od]) as i64;
            base += i.clamp(0, hi) as usize * st[od];
        }
        for (&ob, &ib) in d
            .operand_batching_dims
            .iter()
            .zip(&d.start_indices_batching_dims)
        {
            base += batch[ib] * st[ob];
        }
        let out_base: usize = batch
            .iter()
            .zip(&batch_dims)
            .map(|(&v, &od)| v * out_st[od])
            .sum();
        for (&sx, &so) in slice_x.iter().zip(&slice_out) {
            out[out_base + so] = x[base + sx];
        }
        b += 1;
    });
    out
}

/// Calls `f` with every index of `shape` in row-major order (once with an
/// empty index for a scalar shape).
fn for_each_index(shape: &[usize], mut f: impl FnMut(&[usize])) {
    if shape.contains(&0) {
        return;
    }
    let mut index = vec![0usize; shape.len()];
    loop {
        f(&index);
        let mut k = shape.len();
        loop {
            if k == 0 {
                return;
            }
            k -= 1;
            index[k] += 1;
            if index[k] < shape[k] {
                break;
            }
            index[k] = 0;
        }
    }
}

/// The size of the window of a scatter in each operand dimension.
pub fn scatter_window(rank: usize, updates_shape: &[usize], d: &ScatterDims) -> Vec<usize> {
    let mut window = d.update_window_dims.iter();
    (0..rank)
        .map(|i| {
            if d.inserted_window_dims.contains(&i) || d.operand_batching_dims.contains(&i) {
                1
            } else {
                updates_shape[*window.next().expect("window dimension")]
            }
        })
        .collect()
}

/// `scatter`: combines `updates` into `x` with `combine(old, update)` (or
/// replaces when `combine` is `None`), in row-major order of the updates.
/// With `Clip`, start indices are clamped; otherwise windows that are not
/// entirely in bounds are skipped, as XLA does.
#[allow(clippy::too_many_arguments)]
pub fn scatter<T: Copy>(
    x: &[T],
    shape: &[usize],
    indices: &[i64],
    indices_shape: &[usize],
    updates: &[T],
    updates_shape: &[usize],
    d: &ScatterDims,
    mode: GatherScatterMode,
    combine: Option<&dyn Fn(T, T) -> T>,
) -> Vec<T> {
    let window = scatter_window(shape.len(), updates_shape, d);
    let st = strides(shape);
    let ist = strides(indices_shape);
    let ust = strides(updates_shape);
    let q = indices_shape.len();
    let scatter_dims: Vec<usize> = (0..updates_shape.len())
        .filter(|i| !d.update_window_dims.contains(i))
        .collect();
    let window_operand: Vec<usize> = (0..shape.len())
        .filter(|i| !d.inserted_window_dims.contains(i) && !d.operand_batching_dims.contains(i))
        .collect();
    let mut out = x.to_vec();
    let ru = updates_shape.len();
    let nw = d.update_window_dims.len();
    if d.operand_batching_dims.is_empty()
        && d.update_window_dims.iter().copied().eq(ru - nw..ru)
        && q >= 1
    {
        // The window dimensions trail the updates: each index vector's
        // window is a block of the updates. The operand position of each
        // window element is computed once, then each block is combined at
        // its start, in the order of the updates (as below).
        let window_size: usize = updates_shape[ru - nw..].iter().product();
        let mut offsets = vec![0usize; window_size];
        for (w, o) in offsets.iter_mut().enumerate() {
            let mut rem = w;
            for (k, &od) in window_operand.iter().enumerate().rev() {
                let n = updates_shape[ru - nw + k];
                *o += (rem % n) * st[od];
                rem /= n;
            }
        }
        let vector = indices_shape[q - 1];
        let blocks = updates.len().checked_div(window_size).unwrap_or(0);
        'blocks: for b in 0..blocks {
            let mut base = 0;
            for (k, &od) in d.scatter_dims_to_operand_dims.iter().enumerate() {
                let hi = (shape[od] - window[od]) as i64;
                let start = indices[b * vector + k];
                let start = if mode == GatherScatterMode::Clip {
                    start.clamp(0, hi)
                } else if (0..=hi).contains(&start) {
                    start
                } else {
                    continue 'blocks;
                };
                base += start as usize * st[od];
            }
            let ub = &updates[b * window_size..(b + 1) * window_size];
            match combine {
                Some(f) => {
                    for (&o, &u) in offsets.iter().zip(ub) {
                        out[base + o] = f(out[base + o], u);
                    }
                }
                None => {
                    for (&o, &u) in offsets.iter().zip(ub) {
                        out[base + o] = u;
                    }
                }
            }
        }
        return out;
    }
    // Scratch buffers, reused for every update element.
    let mut up = vec![0usize; updates_shape.len()];
    let mut full = vec![0i64; shape.len()];
    for (flat, &u) in updates.iter().enumerate() {
        for (k, (&s, &n)) in ust.iter().zip(updates_shape).enumerate() {
            up[k] = (flat / s) % n;
        }
        // The flat position of the index vector of this update (the index
        // vector dimension is the last of the indices).
        let at0: usize = scatter_dims
            .iter()
            .zip(&ist[..q - 1])
            .map(|(&sd, &s)| up[sd] * s)
            .sum();
        full.iter_mut().for_each(|f| *f = 0);
        let mut dropped = false;
        for (k, &od) in d.scatter_dims_to_operand_dims.iter().enumerate() {
            let hi = (shape[od] - window[od]) as i64;
            let start = indices[at0 + k * ist[q - 1]];
            if mode == GatherScatterMode::Clip {
                full[od] = start.clamp(0, hi);
            } else if (0..=hi).contains(&start) {
                full[od] = start;
            } else {
                dropped = true;
                break;
            }
        }
        if dropped {
            continue;
        }
        for (&ob, &ib) in d
            .operand_batching_dims
            .iter()
            .zip(&d.scatter_indices_batching_dims)
        {
            full[ob] += up[scatter_dims[ib]] as i64;
        }
        for (&od, &ud) in window_operand.iter().zip(&d.update_window_dims) {
            full[od] += up[ud] as i64;
        }
        let o: usize = full.iter().zip(&st).map(|(&v, &s)| v as usize * s).sum();
        out[o] = match combine {
            Some(f) => f(out[o], u),
            None => u,
        };
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Reductions over axes that are not adjacent agree with a sum over the
    /// indices, element by element in order.
    #[test]
    fn reduce_over_axes_apart() {
        let shape = [2, 3, 2, 3, 2];
        let x: Vec<f32> = (0..72).map(|i| (i as f32 * 0.37).sin()).collect();
        for axes in [vec![1, 3], vec![0, 2, 4], vec![0, 4], vec![1, 3, 4]] {
            let out_shape = reduced_shape(&shape, &axes);
            let mut expected = vec![0.0f32; size(&out_shape)];
            let mut index = [0usize; 5];
            for &v in &x {
                let mut o = 0;
                for d in 0..5 {
                    if !axes.contains(&d) {
                        o = o * shape[d] + index[d];
                    }
                }
                expected[o] += v;
                for d in (0..5).rev() {
                    index[d] += 1;
                    if index[d] < shape[d] {
                        break;
                    }
                    index[d] = 0;
                }
            }
            let got = reduce(&x, &shape, &axes, ReduceOp::Sum);
            let bits = |v: &[f32]| v.iter().map(|f| f.to_bits()).collect::<Vec<_>>();
            assert_eq!(bits(&got), bits(&expected), "axes {axes:?}");
            let max = reduce(&x, &shape, &axes, ReduceOp::Max);
            assert_eq!(max.len(), expected.len());
        }
    }

    #[test]
    fn shape_operations() {
        let x: Vec<i32> = (0..6).collect();
        assert_eq!(transpose(&x, &[2, 3], &[1, 0]), [0, 3, 1, 4, 2, 5]);
        assert_eq!(broadcast_in_dim(&[1, 2], &[2], &[2, 2], &[0]), [1, 1, 2, 2]);
        assert_eq!(slice(&x, &[2, 3], &[0, 1], &[2, 3], &[1, 2]), [1, 4]);
        assert_eq!(dynamic_slice(&x, &[2, 3], &[5, -1], &[1, 2]), [3, 4]);
        assert_eq!(
            dynamic_update_slice(&x, &[2, 3], &[9], &[1, 1], &[1, 9]),
            [0, 1, 2, 3, 4, 9]
        );
        assert_eq!(concatenate(&[(&[1, 2], &[2]), (&[3], &[1])], 0), [1, 2, 3]);
        assert_eq!(pad(&[1, 2], &[2], 0, &[(1, -1, 1)]), [0, 1, 0]);
        assert_eq!(rev(&x, &[2, 3], &[1]), [2, 1, 0, 5, 4, 3]);
        assert_eq!(iota::<f32>(&[2, 2], 1), [0.0, 1.0, 0.0, 1.0]);
    }

    #[test]
    fn cumulative_reductions() {
        let x = [1, 2, 3, 4, 5, 6];
        let c = |axis, reverse, op| cumulative(&x, &[2, 3], axis, reverse, op);
        assert_eq!(c(1, false, CumulativeOp::Sum), [1, 3, 6, 4, 9, 15]);
        assert_eq!(c(1, true, CumulativeOp::Sum), [6, 5, 3, 15, 11, 6]);
        assert_eq!(c(0, false, CumulativeOp::Prod), [1, 2, 3, 4, 10, 18]);
        assert_eq!(c(0, true, CumulativeOp::Min), [1, 2, 3, 4, 5, 6]);
        // Lines longer than a block (and than 16 blocks) give the running
        // values, which are exact for integers.
        for n in [17, 40, 300] {
            let x: Vec<i32> = (0..n).map(|i| (i * 7) % 11 - 5).collect();
            let fwd = cumulative(&x, &[n as usize], 0, false, CumulativeOp::Sum);
            let rev = cumulative(&x, &[n as usize], 0, true, CumulativeOp::Sum);
            let mut acc = 0;
            for i in 0..x.len() {
                acc += x[i];
                assert_eq!(fwd[i], acc);
                assert_eq!(rev[i], x[i..].iter().sum::<i32>());
            }
        }
        let x = [1.0f32, f32::NAN, 0.5];
        let m = cumulative(&x, &[3], 0, false, CumulativeOp::Max);
        assert!(m[0] == 1.0 && m[1].is_nan() && m[2].is_nan());
        let l = cumulative(&[0.0f64, 0.0], &[2], 0, false, CumulativeOp::LogSumExp);
        assert_eq!(l, [0.0, 2f64.ln()]);
    }

    #[test]
    fn top_k_orders_by_bits() {
        let nan = f32::NAN;
        let x = [1.0, -nan, -0.0, 0.0, nan, f32::NEG_INFINITY, 1.0];
        let (v, i) = top_k(&x, &[7], 7, 0);
        assert_eq!(i, [4, 0, 6, 3, 2, 5, 1]);
        assert!(v[0].is_nan() && v[6].is_nan());
        assert_eq!(v[3].to_bits(), 0.0f32.to_bits());
        assert_eq!(v[4].to_bits(), (-0.0f32).to_bits());
        // Along the first axis of [3, 2].
        let (v, i) = top_k(&[1, 5, 3, 2, 3, 9], &[3, 2], 2, 0);
        assert_eq!(v, [3, 9, 3, 5]);
        assert_eq!(i, [1, 2, 2, 0]);
    }

    #[test]
    fn sorting() {
        let nan = f32::NAN;
        let x = [1.0f32, -nan, 0.0, -0.0, f32::NEG_INFINITY, nan, -1.0];
        let v: Vec<i32> = (0..7).collect();
        let out = sort(
            &[&Buffer::from_vec(x.to_vec()), &Buffer::from_vec(v)],
            &[7],
            0,
            1,
        );
        // Zeros keep their order (they are equal), as do NaNs.
        assert_eq!(out[1].as_slice::<i32>().unwrap(), [4, 6, 2, 3, 0, 1, 5]);
        // Lexicographic over two keys, along the last dimension.
        let k1 = Buffer::from_vec(vec![1u8, 0, 1, 0, 2, 2]);
        let k2 = Buffer::from_vec(vec![true, true, false, false, true, false]);
        let out = sort(&[&k1, &k2], &[2, 3], 1, 2);
        assert_eq!(out[0].as_slice::<u8>().unwrap(), [0, 1, 1, 0, 2, 2]);
        assert_eq!(
            out[1].as_slice::<bool>().unwrap(),
            [true, false, true, false, false, true]
        );
        // Along the first dimension.
        let out = sort(&[&k1], &[2, 3], 0, 1);
        assert_eq!(out[0].as_slice::<u8>().unwrap(), [0, 0, 1, 1, 2, 2]);
    }

    #[test]
    fn reductions() {
        let x = [1.0f32, 5.0, 3.0, 7.0, 2.0, 7.0];
        assert_eq!(reduce(&x, &[2, 3], &[1], ReduceOp::Sum), [9.0, 16.0]);
        assert_eq!(reduce(&x, &[2, 3], &[0, 1], ReduceOp::Max), [7.0]);
        assert_eq!(arg_min_max(&x, &[2, 3], 1, true), [1, 0]);
        assert_eq!(arg_min_max(&[1.0f32, f32::NAN, 3.0], &[3], 0, true), [1]);
        assert_eq!(reduce::<bool>(&[], &[0], &[0], ReduceOp::Max), [false]);
    }

    #[test]
    fn dot() {
        let a = [1, 2, 3, 4];
        let b = [5, 6, 7, 8];
        let d = DotDims {
            lhs_contracting: vec![1],
            rhs_contracting: vec![0],
            ..DotDims::default()
        };
        assert_eq!(dot_general(&a, &[2, 2], &b, &[2, 2], &d), [19, 22, 43, 50]);
    }

    #[test]
    fn gather_and_scatter() {
        let x: Vec<i32> = (0..15).collect();
        let rows = GatherDims {
            offset_dims: vec![1],
            collapsed_slice_dims: vec![0],
            start_index_map: vec![0],
            ..GatherDims::default()
        };
        assert_eq!(
            gather(&x, &[5, 3], &[3, 9], &[2, 1], &rows, &[1, 3]),
            [9, 10, 11, 12, 13, 14]
        );
        let d = ScatterDims {
            update_window_dims: vec![1],
            inserted_window_dims: vec![0],
            scatter_dims_to_operand_dims: vec![0],
            ..ScatterDims::default()
        };
        let set = scatter(
            &x,
            &[5, 3],
            &[1, 7],
            &[2, 1],
            &[-1, -1, -1, -2, -2, -2],
            &[2, 3],
            &d,
            GatherScatterMode::FillOrDrop,
            None,
        );
        assert_eq!(&set[..6], [0, 1, 2, -1, -1, -1]);
        assert_eq!(&set[12..], [12, 13, 14]);
        let add = |a: i32, b: i32| a + b;
        let summed = scatter(
            &x,
            &[5, 3],
            &[2, 2],
            &[2, 1],
            &[1; 6],
            &[2, 3],
            &d,
            GatherScatterMode::Clip,
            Some(&add),
        );
        assert_eq!(&summed[6..9], [8, 9, 10]);
    }
}

#[cfg(test)]
mod dot_tests {
    use super::*;

    /// The matrix-product path gives the same bits as the general one.
    #[test]
    fn matrix_products_match_the_general_path() {
        let l: Vec<f32> = (0..3 * 5).map(|i| (i as f32 * 0.37).sin()).collect();
        let r: Vec<f32> = (0..5 * 4).map(|i| (i as f32 * 0.71).cos()).collect();
        let fast = dot_general(
            &l,
            &[3, 5],
            &r,
            &[5, 4],
            &DotDims {
                lhs_contracting: vec![1],
                rhs_contracting: vec![0],
                ..DotDims::default()
            },
        );
        // The same product with the operands transposed takes the general path.
        let lt: Vec<f32> = (0..15).map(|i| l[(i % 3) * 5 + i / 3]).collect();
        let general = dot_general(
            &lt,
            &[5, 3],
            &r,
            &[5, 4],
            &DotDims {
                lhs_contracting: vec![0],
                rhs_contracting: vec![0],
                ..DotDims::default()
            },
        );
        assert_eq!(fast, general);
        let v = dot_general(
            &l,
            &[3, 5],
            &r[..5],
            &[5],
            &DotDims {
                lhs_contracting: vec![1],
                rhs_contracting: vec![0],
                ..DotDims::default()
            },
        );
        let expected: Vec<f32> = (0..3)
            .map(|m| (0..5).fold(0.0f32, |acc, k| acc + l[m * 5 + k] * r[k]))
            .collect();
        assert_eq!(v, expected);
    }
}