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
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
//! Plan types: which scheduler tier, which hardware class, and the
//! `(K_outer, batch_size)` -> tier mapping used by `pick_tier`.
//!
//! Tier boundaries:
//!
//! | Tier | K_outer band | Why |
//! |--------------|-------------------------|-----------------------------------------------|
//! | Inline | K <= 4 (<= 16 limbs) | Sub-microsecond per op; scheduler overhead dominates |
//! | Local | K = 5..7 (32-128 limbs) | Single-NUMA work-steal; rayon-style |
//! | Hierarchical | K = 8..10 (256-1024 limbs) | Per-NUMA arenas + leader-driven cross-arena |
//! | Federated | K >= 11 (>= 2048 limbs) | Multi-pool + tiered storage + constant replication |
//!
//! These defaults can be overridden by a per-host calibration table
//! populated at install time.
use crate::backend::{Backend, BackendRef, cpu_backend};
use crate::dispatch_profile::DispatchProfile;
use crate::foundation::Variant;
use crate::numa_topology::NumaTopology;
/// Per-call selector for one of the in-tree bisect-policy variants.
/// The default behavior (no variant set) uses the
/// continuation-steal-lazy bisect: first level always splits to seed
/// initial fanout (`workers` leaves), subsequent levels run serially
/// inline unless real steal pressure is detected on the dispatching
/// worker's deque.
///
/// Variants exist for the workloads where the default is measurably
/// beaten by a different policy. Routing is automatic when the
/// process-global [`crate::sched::adaptive_variant_routing`] tag is
/// set (which happens at startup via the CPUID-based default table);
/// callers can also pin a variant per-plan via
/// [`JobPlan::with_bisect_variant`].
///
/// Empirical justification (Xeon Cascade Lake 12T / EPYC 9B14 44T /
/// Zen3 5700G 16T, criterion 0.8.2 medians, see
/// `benches/inline_collapse.rs`):
///
/// - `ProducerMaxLenWorkers`: +19.6% Zen3 Compute/100k vs default;
/// tied on Genoa; small +5.7% Xeon Heavy/10k win.
/// - `RayonStyleReplenish`: +37.6% Zen3 Compute/10k vs default;
/// tied on Genoa Compute (both sizes).
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum BisectVariant {
/// **Producer max-len-equals-workers**: clamp the upfront leaf
/// count to `workers * 1` (matching rayon's `LengthSplitter`
/// default initial split count = `current_num_threads()`).
/// Replenish target stays at the default `workers * 1` so the
/// bisect tree is shallower than the production baseline.
///
/// Pareto cell: AMD Compute at large N (>= 50_000). Routed
/// automatically when the CPUID-resolved variant routing is
/// `ComputeBatchAdaptive` and `batch_size >= 50_000`.
ProducerMaxLenWorkers,
/// **Rayon-style replenish**: start with `leaves_per_worker = 1`
/// and, on each observed steal in `bisect`, replenish to
/// `MAX(workers, splits / 2)` instead of the default
/// `max_budget`. Mirrors `rayon-1.12.0`'s `Splitter::try_split`
/// formula (`splits = max(thread_count, splits / 2)`).
///
/// Pareto cell: AMD Compute at small N (< 50_000). Routed
/// automatically when the CPUID-resolved variant routing is
/// `ComputeBatchAdaptive` and `batch_size < 50_000`.
RayonStyleReplenish,
}
// `SchedTier` and `HwClass` live in [`crate::foundation`] so the same
// types travel across an entire dispatch stack: scheduler tier
// classification on the parent side, kernel-variant selection on the
// child side, no namespace churn between them.
pub use crate::foundation::{HwClass, SchedTier};
/// A scheduling plan attached to one job submission. The four-tuple
/// `(k_outer, batch_size, hw_class, variant)` together with the cached
/// NUMA topology produces a [`SchedTier`] via [`pick_tier`].
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct JobPlan {
/// `K_outer = log2(n_limbs)` for the job's operands.
pub k_outer: u8,
/// Batch size: number of independent operations being scheduled
/// together. Important for amortizing tier-dispatch overhead.
pub batch_size: u32,
/// Target hardware class.
///
/// A matrix-extension class ([`HwClass::is_matrix_extension`]) says
/// the item is a tile operation, and the tier selection treats that
/// as heavy per item however small the batch: a plan declaring one
/// runs parallel where the same batch would otherwise fold inline.
/// The vector classes say nothing the batch size does not, and
/// steer nothing.
///
/// What a matrix-extension class asserts is the regime, not that
/// the host has the unit. The cost structure it names is the one
/// [`crate::sched::mode_region::run_in_region`] is built for, where
/// entry costs amortize per region rather than per op, and
/// [`crate::sched::mode_region::ScalarFallback`] exists so that
/// regime runs on a host without the extension. A caller emulating
/// tile ops on vector silicon is describing this regime accurately
/// and should declare it; the class is a claim about the shape of
/// the work, and the arithmetic underneath it is the backend's.
pub hw_class: HwClass,
/// Quality tier.
pub variant: Variant,
/// Optional NUMA node hint. `None` means "current thread's node;"
/// `Some(n)` requests placement on a specific node (e.g., to keep
/// the job on the same node as a referenced buffer).
pub numa_hint: Option<u32>,
/// SMT-sibling activation hint. `false` (default) means this work
/// runs on the primary (physical) workers only; the 8 SMT
/// siblings stay parked. `true` activates the SMT siblings for
/// the duration of this submit so the pool runs at full
/// `logical_threads` width.
///
/// Workload guide:
/// - BigFloat schoolbook / Karatsuba (IMUL pipe saturating): `false`
/// - NTT butterflies (FMA-saturating): `false`
/// - `Tower<T>` combine (Two-Sum FMA): `false`
/// - FP sqrt / div / transcendental chains (latency-bound):
/// `true` (SMT-2 fills dispatch bubbles)
/// - Mixed-shape kernels: prefer `false` unless benchmarked
pub use_smt: bool,
/// Optional caller-supplied estimate of the per-item cost in
/// nanoseconds. Lets dispatchers (e.g. `collect_indexed_heartbeat`)
/// make a static serial-vs-parallel decision at entry without
/// rdtsc-polling the hot loop. `None` means "no estimate;
/// dispatcher falls through to its default heuristic."
///
/// When set, dispatchers compute
/// `estimated_per_item_ns * batch_size` to predict the total
/// compute cost and gate dispatch behavior accordingly:
///
/// - Total below the small-N gate (~50µs, the shared
/// INLINE_COLLAPSE_THRESHOLD_NS): go fully serial, zero
/// scheduling overhead.
/// - Total at or above the gate: SLAW-bisect with full
/// parallelism.
///
/// Per-op typical values (Zen3 / FpN<8> baseline):
/// - `add_slice` / `sub_slice`: ~10ns/elem (SIMD-vectorized)
/// - `mul_slice`: ~10-20ns/elem
/// - `spmv` per row: ~50ns * nnz_per_row
/// - `gemm` per output element: ~32ns * k (k = inner dim)
/// - `Karatsuba` recursive sub-product: O(N^1.585), not flat
pub estimated_per_item_ns: Option<u32>,
/// `true` when [`Self::estimated_per_item_ns`] was set explicitly
/// by the caller via [`Self::with_estimated_per_item_ns`]. `false`
/// when the value is a classifier default from
/// [`Self::new`] / [`Self::set_profile`] (which writes the
/// per-profile default 12 / 50 / 600 ns).
///
/// The probe-and-decide path in `for_each_chunk` consults this
/// flag: classifier defaults are routing hints (good enough for
/// most workloads) but not authoritative per-item-cost truth.
/// When the caller did not give an explicit hint and N is small
/// enough that the wrong default would cost real wall-clock,
/// the probe path measures actual per-element cost and overrides.
pub estimated_per_item_ns_explicit: bool,
/// Per-task overhead in nanoseconds (Tiny-Tasks model from Acar
/// 2013): the cost paid once for every chunk. The scheduler's own
/// share is the deque push, the atomic and the latch init, around
/// 200-500 ns for the join path with the adaptive splitter. Used
/// with `estimated_per_item_ns` to compute the optimal chunk count
/// via `optimal_chunk_count`. `None` lets helpers fall back to the
/// SLAW default.
///
/// A caller whose own per-chunk work is larger than that adds it
/// here. `optimal_chunk_count` minimizes `W/C + O*C`, so what it
/// asks of `O` is that the cost be paid once per chunk, not that
/// the scheduler be the one paying it: a merge across a chunk
/// boundary or a per-chunk setup pass belongs in this number.
///
/// A cost paid once for the whole call does not belong here,
/// however large it is. A constant term cannot move the minimum of
/// that expression, so including it does not bias the chunk count
/// slightly - it inflates `O`, and `C = sqrt(W * P / O)` then comes
/// back too small by the square root of however far off it was. A
/// whole-input prescan against a per-chunk cost in the hundreds of
/// nanoseconds drives the answer to one chunk at every size. Such a
/// cost belongs in the caller's own serial-versus-parallel
/// decision, alongside `inline_collapse_threshold_ns`.
///
/// `None` and `Some(0)` are different answers, and the second is
/// not the one a caller usually means. `None` says the cost is
/// unknown and lets helpers fall back to the SLAW budget
/// heuristic. `Some(0)` says splitting is free, and
/// `optimal_chunk_count` answers it literally: with no cost to
/// balance against, the minimum runs away to the largest split
/// available and it returns the item count, one chunk per item. A
/// caller whose per-chunk cost is real but negligible wants `None`
/// or the scheduler's own share, never zero.
pub task_overhead_ns: Option<u32>,
/// Per-chunk serial span in nanoseconds (Tiny-Tasks model): the
/// part of a chunk that does not shrink when the chunk does, such
/// as a serial prelude before a fan-out or the trunk of a
/// recursive body. For uniform-leaf workloads (matmul, slice ops)
/// it is 0; `None` is read as 0.
///
/// [`Self::optimal_chunk_count`] adds it to
/// [`Self::task_overhead_ns`] to form the fixed cost a chunk pays
/// whatever work it carries, so a larger span yields fewer, coarser
/// chunks: splitting again buys less than the split costs. It is
/// read there and nowhere else.
pub task_span_ns: Option<u32>,
/// Caller-supplied effective task count when the natural item
/// count over-states the parallelism budget. Example: a 1M-item
/// slice op where SIMD packs 16 items per leaf has an effective
/// task count of `1M / 16 = 62.5k`. `optimal_chunk_count`
/// consults this instead of `batch_size` when present.
pub effective_task_count: Option<u32>,
/// BLIS K_inner axis: how many output cells the batched matmul's
/// inner loop carries per k-iteration, as a log2. `Some(log2)`
/// asks for `2^log2` cells, `None` for one.
///
/// Read through [`Self::k_inner_lanes`] by the batched-matmul
/// tandem split, which hands it to the CPU half's lane-blocked
/// inner loop.
// Those two names live under `gpu_peer`, which is a feature. A link
// to them resolves in a build that has it and dangles in one that
// does not, so the sentence naming them is written both ways and
// the prose around it stays single-sourced.
#[cfg_attr(
feature = "gpu-peer",
doc = "Those are [`crate::gpu_peer::linalg::gemm_tandem_batched`]",
doc = "and [`crate::gpu_peer::linalg::cpu::gemm_batched_lanes`]."
)]
#[cfg_attr(
not(feature = "gpu-peer"),
doc = "Those are `gpu_peer::linalg::gemm_tandem_batched` and",
doc = "`gpu_peer::linalg::cpu::gemm_batched_lanes`, which this build",
doc = "does not carry: they are behind the `gpu-peer` feature."
)]
///
/// It steers that loop and nothing else: the device half is
/// untouched, and no other op consults it.
///
/// Every output cell still accumulates over `k` in the same order
/// against the same operands whatever the width, so the result is
/// bit-identical to the one-cell loop. What the width changes is
/// how many accumulators are live at once, which is what allows a
/// group of them to sit in registers rather than one at a time.
///
/// No width is recommended here, because the width that pays is a
/// property of the host's register file and the matrix shape rather
/// than of this crate: measure it with `benches/gemm_k_inner.rs` on
/// the host in question. A width wider than the matrix's column
/// count costs nothing and gains nothing - every column falls to
/// the one-at-a-time tail.
pub k_inner_log2: Option<u8>,
/// Backend hint: which dispatch target to route this job to.
/// `None` means "use the CPU backend"; `Some(b)` requests
/// routing to the matching registered backend (CUDA / ROCm /
/// Metal / TPU / ANE / Custom). [`Self::pick_backend`] honors
/// the hint when a backend with that id is registered, else
/// falls back to the always-available CPU backend.
///
/// Pairs with the extended-Flynn-taxonomy SIMT and MIMT axes:
/// `Some(Backend::Cuda { .. })` etc. routes the job to a SIMT
/// device; [`crate::sched::hybrid::join_hybrid`] reads this
/// hint to decide which half runs where in the MIMT case.
pub backend_hint: Option<Backend>,
/// Direct override of the per-dispatch leaf-count oversubscription
/// factor as `log2(leaves_per_worker)`. `None` falls back to the
/// `DispatchProfile`'s default (or the global split-multiplier
/// when no profile is set).
///
/// Concrete effect: `for_each_chunk`'s bisect targets `workers *
/// 2^oversubscription_log2` leaves. Set to a small value (0 or 1)
/// for uniform-cost ops to reduce per-leaf dispatch overhead;
/// set higher (2 or 3) for variable-cost ops to give the work-
/// stealing pool more leaves to rebalance across.
///
/// Clamps to `[0, 3]` internally (1..8 leaves per worker; a
/// host with 16 workers gets up to 128 leaves at log2=3).
pub oversubscription_log2: Option<u8>,
/// `true` when [`oversubscription_log2`](Self::oversubscription_log2)
/// came from the caller via [`Self::with_oversubscription_log2`]
/// rather than from a profile or a learned class. The dispatch
/// entries read the process-global split observer for their leaf
/// budget; this flag is what makes a caller's own factor win over
/// it, so the override skips that observer entirely.
pub oversubscription_log2_explicit: bool,
/// How long a thread waiting on a half of this dispatch polls the
/// latch before it yields its core, in nanoseconds. `None` lets
/// the scheduler decide from this host's measured collapse
/// threshold and the plan's per-item cost; see
/// [`Self::effective_spin_before_yield_ns`].
///
/// Set it to take that decision away from the scheduler: `0`
/// yields immediately, a larger value spins longer. Read by the
/// in-pool join waiter and by an external caller waiting on its
/// slot job.
pub spin_before_yield_ns: Option<u64>,
/// Direct override of the worker count used for this dispatch.
/// `None` uses the full per-arena worker count (16 logical
/// threads on a typical Zen3 host).
///
/// Concrete effect: caps the `max_budget` passed to the bisect
/// at `workers * oversubscription`. Set to `1` to force serial
/// execution on the calling thread; set to `physical_cores` for
/// IMUL-bound work to skip the SMT siblings even when
/// `use_smt = true`.
pub worker_cap: Option<u32>,
/// Select an alternate `for_each_chunk` policy variant for
/// bench A/B comparison. `None` (default) runs the production
/// probe-and-decide baseline; `Some(v)` routes through the
/// matching variant in [`BisectVariant`].
///
/// Only `for_each_chunk` reads this; other parallel primitives
/// (`for_each_chunk_triple`, `for_each_fixed_chunk`) ignore it.
pub bisect_variant: Option<BisectVariant>,
/// SIMC/MIMC mailbox routing hint. When `true`, the
/// `sched::arena::join` right-half-push attempts to route the
/// right-half job to the SMT sibling worker's mailbox before
/// falling back to a regular tiered deque push. When `false`
/// (default), the right-half always goes to the regular deque
/// so the broad pool can steal.
///
/// Workload guide (Zen+ R7 2700 realistic_bench):
/// - Latency-bound chains (sqrt, div, transcendentals): `false`.
/// These benefit from broad work-stealing across all primaries;
/// pinning the right-half to one SMT pair concentrates load
/// and starves the other 6 physical cores.
/// - IMUL-saturated compute (Karatsuba, schoolbook mul,
/// port-saturating Compute): `false`. Same reason; broad
/// distribution wins.
/// - Fine-grain locality-friendly ops (Light: tight inner
/// loops with shared SIMD registers, small per-element work):
/// `true`. The SMT-sibling pin keeps the right-half's
/// captured state in the L1d the pair shares.
/// - Mixed / unknown: `false`.
///
/// The mailbox path is FURTHER gated at the call site on the
/// sibling's mailbox and SmtLocal deque both being empty - so
/// even with `true`, a backlogged sibling never gets routed to.
pub use_mailbox_routing: bool,
/// Caller's leaf-shape hint, set via [`Self::with_leaf_shape`].
/// Read by the static initial classifier
/// (`infer_class_static_with_shape`) to skip the (ns + K + N)
/// heuristics when the caller knows the leaf-level character
/// of the work (compute-bound, gather-bound, streaming, etc.).
/// Default `Unknown` lets the classifier fall back to
/// heuristics.
pub leaf_shape: crate::sched::adaptive_profile::LeafShape,
/// Per-call deque-tier override for the right-half push in
/// `sched::arena::join`. `None` (default) routes the right-half
/// to the default tier
/// ([`crate::sched::deque_tier::DequeTier::Public`] - any peer
/// reachable; broad steal). `Some(tier)` pins the push to the
/// caller-specified tier.
///
/// Workload guide (paired with the steal discipline in
/// [`crate::sched::deque_tier::thief_may_steal`]):
///
/// - `Some(DequeTier::SmtLocal)`: pin to SMT-sibling local
/// deque. Only the SMT sibling can steal. Use when the
/// right-half captured state is L1d-warm and the sibling is
/// expected to be the consumer (recursive splits handing off
/// to the same physical core).
/// - `Some(DequeTier::IntraCcx)`: pin to intra-CCX. Cluster
/// peers (same Zen CCX / Intel module) can steal. Use for
/// moderate-locality work that should stay within one cache
/// cluster but tolerate non-sibling-CCX-peer pickup.
/// - `Some(DequeTier::CrossCcx)`: pin to cross-CCX. Most peers
/// reachable; reserves the Public deque for cross-NUMA work.
/// - `Some(DequeTier::Public)`: explicit default. Broad steal.
/// - `None`: broad steal (same as Public). Recommended for
/// unhinted ops.
///
/// This is the call-site half of the unified dispatcher; the
/// cross-process side is the `WorkloadShape` type in
/// `crate::backend::shared_mem::variant_dispatch` (gated on
/// the `shared-memory-worker-reference` feature).
pub deque_tier_hint: Option<crate::sched::deque_tier::DequeTier>,
/// Per-call cooperative-routing override consumed by
/// [`crate::sched::cooperative::cooperative_join_n`]. `Auto`
/// (the default) defers to the process-global tag via
/// [`crate::sched::adaptive_cooperative::active_cooperative_routing`];
/// when that is also `Auto`, the call falls through to the
/// population heuristic (`N < n_workers` -> tree, `N >= n_workers`
/// -> mailbox). Non-`Auto` values pin the dispatch shape for
/// this plan only.
///
/// Workload guide:
/// - `ForceTree`: short closures (sub-100us) where the
/// tree's amortized setup wins over flat fan-out's
/// per-StackJob cost.
/// - `ForceMailbox`: uniform-cost closures sized to the
/// worker pool (N >= n_workers) where each closure should
/// land on a specific peer's mailbox.
/// - `ForceDeque`: heterogeneous-cost closures where broad
/// random peer-steal load balance is preferred over
/// owner-directed mailbox routing.
pub cooperative_routing: crate::sched::adaptive_cooperative::CooperativeRouting,
/// Per-call-site adaptive state
/// ([`crate::sched::call_site::CallSiteState`]) this dispatch
/// records into and reads learned decisions from. Generic
/// dispatch entries attach the state resolved from the caller's
/// source location (`track_caller` chain +
/// [`crate::sched::call_site::caller_site`]) via
/// [`Self::with_site_if_none`]; callers can pin an explicit
/// identity via [`Self::with_site`]. `None` means the dispatch
/// only feeds the process-global observer.
pub site: Option<crate::sched::call_site::SiteRef>,
/// `true` when the profile-derived knobs came from an explicit
/// caller decision ([`Self::set_profile`] / [`Self::for_op_generic`])
/// rather than the adaptive default path ([`Self::new`] /
/// [`Self::bare`]). The per-site class override in
/// [`Self::apply_site_class`] respects explicit callers and
/// never overrides them.
pub profile_explicit: bool,
}
impl JobPlan {
/// Builder: install a `deque_tier_hint` and return the modified
/// plan. Use to pin the right-half of an in-worker `join` to a
/// specific coherence tier; see [`Self::deque_tier_hint`] for
/// the workload guide.
pub fn with_deque_tier_hint(
mut self,
tier: crate::sched::deque_tier::DequeTier,
) -> Self {
self.deque_tier_hint = Some(tier);
self
}
/// Builder: opt this plan into SIMC/MIMC mailbox routing for
/// the right-half of `join`. See [`Self::use_mailbox_routing`]
/// for the workload guide.
pub fn with_mailbox_routing(mut self, enable: bool) -> Self {
self.use_mailbox_routing = enable;
self
}
/// Builder: override the cooperative-routing axis for this
/// dispatch. See [`Self::cooperative_routing`] for the
/// workload guide. The default ([`crate::sched::adaptive_cooperative::CooperativeRouting::Auto`])
/// defers to the process-global tag (set via
/// [`crate::sched::adaptive_cooperative::migrate_cooperative_routing`])
/// and, when that is also `Auto`, to the population heuristic.
pub fn with_cooperative_routing(
mut self,
routing: crate::sched::adaptive_cooperative::CooperativeRouting,
) -> Self {
self.cooperative_routing = routing;
self
}
/// Builder: install a declarative [`crate::sched::workload_shape::WorkloadShape`]
/// hint. Resolves to a bundle of low-level K-axis hints
/// ([`Self::use_mailbox_routing`],
/// [`Self::oversubscription_log2`]) via
/// [`crate::sched::workload_shape::WorkloadShape::hints`]. The
/// shape API is the convenience surface for callers that
/// describe their workload in Flynn-axis terms instead of
/// learning every K-axis knob individually.
///
/// The `use_burst` hint inside
/// [`crate::sched::workload_shape::WorkloadShapeHints`] is
/// informational at the plan level: cooperative fan-out sites
/// (cooperative_join_n_flat) always run in burst mode;
/// single-push sites (`sched::join`) always run in auto-flush
/// mode. The shape hint helps the user pick which user-facing
/// primitive to call, not which internal flag the plan carries.
///
/// Power users that have already set specific knobs via other
/// `with_*` builders should call this ahead of those builders -
/// this method overwrites use_mailbox_routing and
/// oversubscription_log2 with shape-derived values.
///
/// Both steer: the mailbox flag gates the right-half push in
/// `join`, and the oversubscription factor sets the split budget.
pub fn with_workload_shape(
mut self,
shape: crate::sched::workload_shape::WorkloadShape,
) -> Self {
let h = shape.hints();
self.use_mailbox_routing = h.use_mailbox_routing;
// A declared shape is the caller describing the workload, so
// its factor counts as theirs: the dispatch entries take it
// over the split observer's measured multiplier, exactly as
// they take a factor from `with_oversubscription_log2`.
if let Some(over) = h.oversubscription_log2 {
self.oversubscription_log2 = Some(over);
self.oversubscription_log2_explicit = true;
}
self
}
/// Construct an **adaptive default** plan. The static initial
/// classifier ([`crate::sched::adaptive_profile::infer_class_static`])
/// picks a [`crate::sched::adaptive_profile::WorkloadClass`]
/// from `(k_outer, batch_size)` and pre-populates `use_smt`,
/// `estimated_per_item_ns`, `oversubscription_log2`,
/// `use_mailbox_routing`, and `deque_tier_hint` from that
/// class's profile. Construction also resolves the process-
/// global cooperative-routing and bisect-variant tags (one
/// Acquire-load each, ~1 ns).
///
/// Refinement after call 1 is per call site: the generic
/// dispatch entries attach a [`crate::sched::call_site::CallSiteState`]
/// and [`Self::apply_site_class`] re-derives an unpinned
/// plan's knobs from that site's learned class. The process-
/// global active class
/// ([`crate::sched::adaptive_profile::migrate_workload_class`]
/// / the observer's `tick_auto_classify`) drives the
/// [`crate::sched::dispatch::AdaptiveDispatcher`] surface.
///
/// To pin the profile for a single call, use
/// [`Self::set_profile`] or [`Self::with_workload_shape`]
/// instead. To get bare defaults (no `use_smt`, no cost
/// estimate, no oversubscription), use [`Self::bare`] or
/// `JobPlan::set_profile(K, batch, DispatchProfile::Unspecified)`.
pub fn new(k_outer: u8, batch_size: u32) -> Self {
// Static initial classifier: pick a WorkloadClass from
// (k_outer, batch_size) at construction time so the first
// dispatch already uses the right routing. The observer
// refines via atomic migration if the classifier guessed
// wrong; static gets us call-1 correctness, observer
// handles call-N correction.
//
// The static guess takes precedence over the active global
// profile because the caller's JobPlan parameters carry
// workload-specific information that the global atomic
// (which reflects the LAST workload's observation) does
// not. Cross-workload contamination of the global was the
// main failure mode of the observer-only architecture for
// workloads that ran one-after-another with different
// shapes (e.g., criterion bench cells).
let class = crate::sched::adaptive_profile::infer_class_static(
k_outer, batch_size, None,
);
let mut plan =
Self::set_profile_with(k_outer, batch_size, class.to_dispatch_profile(), false);
plan.leaf_shape = crate::sched::adaptive_profile::LeafShape::Unknown;
plan
}
/// Builder: tag the plan with the caller's leaf-shape hint.
/// The shape is the strongest static signal: when set it maps
/// directly to a [`crate::sched::adaptive_profile::WorkloadClass`]
/// and the (ns, K, N) heuristics are bypassed.
///
/// Use this when you know your workload's leaf character at
/// compile time:
/// - `Streaming` for byte scans, image kernels, sequential reduce
/// - `Gather` for sparse matvec, graph adjacency, hash probes
/// - `PortCompute` for FMA-bound, IMUL-bound, integer-pipeline work
/// - `LatencyCompute` for sqrt chains, Newton iterations, branchy FP
///
/// The static classifier picks the right [`DispatchProfile`]
/// from the shape on call 1; the observer remains active as
/// a safety net if the workload changes shape mid-run.
///
/// The shape reaches the entries that fan out: the chunk, indexed,
/// collect, reduce and token-bucket paths, which read the knobs it
/// derives. It does not reach
/// [`crate::sched::hybrid::join_hybrid`], which takes only the
/// backend hint and runs its CPU half on the calling thread, so a
/// shape set on a plan built for that call is unread.
pub fn with_leaf_shape(
mut self,
shape: crate::sched::adaptive_profile::LeafShape,
) -> Self {
self.leaf_shape = shape;
// Re-classify using the shape as the strongest signal.
//
// Only an estimate the caller supplied is offered to the
// classifier. `new` seeds this field from the process-active
// profile, and that default describes no particular call, so
// letting it reach the fine-grain corner would drop a shape the
// caller named in favor of a number the caller never wrote.
let caller_estimate = if self.estimated_per_item_ns_explicit {
self.estimated_per_item_ns
} else {
None
};
let class = crate::sched::adaptive_profile::infer_class_static_with_shape(
self.k_outer,
self.batch_size,
caller_estimate,
shape,
);
let profile = class.to_dispatch_profile();
self.use_smt = profile.is_latency_bound();
self.oversubscription_log2 = Some(profile.default_oversubscription_log2());
self.use_mailbox_routing = profile.use_mailbox_routing();
self.deque_tier_hint = profile.deque_tier_hint();
// estimated_per_item_ns updated only if shape-derived
// profile has a default and caller hadn't pinned one.
if self.estimated_per_item_ns.is_none() {
self.estimated_per_item_ns = profile.default_ns_per_elem();
}
self
}
/// Construct a bare default plan (no profile consultation):
/// scalar hw_class, faithful variant, no NUMA hint, no SMT
/// activation, no cost estimate, no oversubscription, K_gating
/// = Auto. Used by call sites that explicitly want
/// profile-independent defaults (most callers should use
/// [`Self::new`] which reads the active dispatch profile).
pub fn bare(k_outer: u8, batch_size: u32) -> Self {
Self {
k_outer,
batch_size,
hw_class: HwClass::Scalar,
variant: Variant::Faithful,
numa_hint: None,
use_smt: false,
estimated_per_item_ns: None,
estimated_per_item_ns_explicit: false,
task_overhead_ns: None,
task_span_ns: None,
effective_task_count: None,
k_inner_log2: None,
backend_hint: None,
oversubscription_log2: None,
oversubscription_log2_explicit: false,
spin_before_yield_ns: None,
worker_cap: None,
bisect_variant: None,
use_mailbox_routing: false,
leaf_shape: crate::sched::adaptive_profile::LeafShape::Unknown,
deque_tier_hint: None,
cooperative_routing: crate::sched::adaptive_cooperative::CooperativeRouting::Auto,
site: None,
profile_explicit: false,
}
}
/// Construct a plan from a [`DispatchProfile`]. The profile sets
/// SMT activation, per-element cost estimate, and oversubscription
/// together so the scheduler has the inputs it needs for per-call
/// tuning. Use this at any call site where the work fits a known
/// profile; the SMT routing + leaf-count cap are derived
/// automatically.
///
/// Override any specific knob via the `with_*` builders after
/// construction (e.g. `set_profile(K, batch, LatencyBound)
/// .with_cost_ns_per_elem(measured_ns)`).
pub fn set_profile(k_outer: u8, batch_size: u32, profile: DispatchProfile) -> Self {
Self::set_profile_with(k_outer, batch_size, profile, true)
}
/// Shared constructor behind [`Self::set_profile`] (explicit =
/// true) and [`Self::new`] (explicit = false). The flag lands in
/// [`Self::profile_explicit`] so the per-site class override
/// knows whether the caller expressed an opinion about the
/// profile or accepted the adaptive default.
pub(crate) fn set_profile_with(
k_outer: u8,
batch_size: u32,
profile: DispatchProfile,
explicit: bool,
) -> Self {
Self {
k_outer,
batch_size,
hw_class: HwClass::Scalar,
variant: Variant::Faithful,
numa_hint: None,
use_smt: profile.is_latency_bound(),
estimated_per_item_ns: profile.default_ns_per_elem(),
estimated_per_item_ns_explicit: false,
task_overhead_ns: None,
task_span_ns: None,
effective_task_count: None,
k_inner_log2: None,
backend_hint: None,
oversubscription_log2: Some(profile.default_oversubscription_log2()),
oversubscription_log2_explicit: false,
spin_before_yield_ns: None,
worker_cap: None,
// Resolve the bisect-variant routing from the process-global
// adaptive tag (initial value: CPUID-resolved per vendor).
// AMD + PortBound + batch >= 50_000 -> ProducerMaxLenWorkers
// AMD + PortBound + batch < 50_000 -> RayonStyleReplenish
// Otherwise None (default lazy-steal bisect). The flip is
// free on the per-op path; only one AtomicU8 Acquire-load
// here at construction time.
bisect_variant:
crate::sched::adaptive_variant_routing::pick_variant_for_profile(
profile, batch_size,
),
// Auto-routing from profile classification: the scheduler
// picks the locality knobs for the caller. Power users can
// still override via the with_* builders.
use_mailbox_routing: profile.use_mailbox_routing(),
leaf_shape: crate::sched::adaptive_profile::LeafShape::Unknown,
deque_tier_hint: profile.deque_tier_hint(),
// Resolve from the process-global active tag at construction
// time (one AtomicU8 Acquire-load, ~1 ns). When the global
// is also Auto (the default), the call falls through to the
// population heuristic inside cooperative_join_n.
cooperative_routing:
crate::sched::adaptive_cooperative::active_cooperative_routing(),
site: None,
profile_explicit: explicit,
}
}
/// Generic constructor over any [`crate::op_class::OpClass`].
/// Accepts [`DispatchProfile`] as well as any domain-specific
/// op enum a downstream crate defines (string substrates, GPU
/// dispatch, signal-processing kernels, ...). The classification
/// (`is_latency_bound`) drives `use_smt`; downstream enums that
/// map to a `DispatchProfile` get the full cost / oversubscription
/// defaults by wrapping `set_profile`.
pub fn for_op_generic<O>(k_outer: u8, batch_size: u32, op: O) -> Self
where
O: crate::op_class::OpClass,
{
Self {
k_outer,
batch_size,
hw_class: HwClass::Scalar,
variant: Variant::Faithful,
numa_hint: None,
use_smt: op.is_latency_bound(),
estimated_per_item_ns: None,
estimated_per_item_ns_explicit: false,
task_overhead_ns: None,
task_span_ns: None,
effective_task_count: None,
k_inner_log2: None,
backend_hint: None,
oversubscription_log2: None,
oversubscription_log2_explicit: false,
spin_before_yield_ns: None,
worker_cap: None,
bisect_variant: None,
use_mailbox_routing: false,
leaf_shape: crate::sched::adaptive_profile::LeafShape::Unknown,
deque_tier_hint: None,
cooperative_routing:
crate::sched::adaptive_cooperative::active_cooperative_routing(),
site: None,
// The op classification is a caller-supplied signal, so
// the per-site override must not second-guess it.
profile_explicit: true,
}
}
/// Builder: attach a per-call-site adaptive state, replacing any
/// prior attachment. Power-user surface: declare a
/// `static SITE: CallSiteState = CallSiteState::new();` and
/// attach it to every plan that should share one learned
/// identity. Most callers rely on the generic dispatch entries
/// attaching the caller-location-resolved state
/// ([`crate::sched::call_site::caller_site`]) via
/// [`Self::with_site_if_none`] instead.
pub fn with_site(mut self, site: crate::sched::call_site::SiteRef) -> Self {
self.site = Some(site);
self
}
/// Attach `site` only when no site is present yet. Used by the
/// generic dispatch entries so an outer attachment (a caller's
/// explicit [`Self::with_site`], or an outer entry like
/// `collect_indexed_heartbeat` delegating to `collect_indexed`)
/// always wins over the inner entry's own static.
pub fn with_site_if_none(mut self, site: crate::sched::call_site::SiteRef) -> Self {
if self.site.is_none() {
self.site = Some(site);
}
self
}
/// True when the caller pinned authoritative tuning on this plan:
/// an explicit profile ([`Self::set_profile`] /
/// [`Self::for_op_generic`]), an explicit per-item cost hint, or
/// a leaf-shape declaration. The per-site class override defers
/// to pinned callers.
#[inline]
pub fn caller_pinned(&self) -> bool {
self.profile_explicit
|| self.estimated_per_item_ns_explicit
|| self.leaf_shape != crate::sched::adaptive_profile::LeafShape::Unknown
}
/// Re-derive the profile-driven knobs from this plan's site's
/// learned class, when (a) the caller pinned nothing and (b) the
/// site has classified itself. Returns the plan unchanged
/// otherwise, so repeat dispatches from the same call site can run
/// with that site's own learned routing instead of the
/// process-global prior.
///
/// The generic dispatch entries reach this through
/// [`Self::apply_site_class_measured`] rather than calling it
/// directly: it is that choice's Default arm, taken when the site's
/// measurements say the class-derived routing is the faster of the
/// two. A caller applying it on its own gets the class every time,
/// measured against nothing.
pub fn apply_site_class(mut self) -> Self {
if self.caller_pinned() {
return self;
}
let Some(site) = self.site else { return self };
let Some(class) = site.get().learned_class() else {
return self;
};
let profile = class.to_dispatch_profile();
self.use_smt = profile.is_latency_bound();
self.oversubscription_log2 = Some(profile.default_oversubscription_log2());
self.use_mailbox_routing = profile.use_mailbox_routing();
self.deque_tier_hint = profile.deque_tier_hint();
// Keep any existing classifier-default estimate unless the
// learned profile carries one; the caller gave no explicit
// hint (caller_pinned checked above).
if let Some(ns) = profile.default_ns_per_elem() {
self.estimated_per_item_ns = Some(ns);
}
self
}
/// [`Self::apply_site_class`] under the site's routing A/B, with the
/// arm it ran so the caller can report what that dispatch cost.
///
/// The class is a description of the workload; this is the check on
/// what acting on it is worth. On
/// [`crate::sched::call_site::PolicyArm::Default`] the class
/// re-derives the plan as before; on `Alternative` the plan stands
/// as the caller built it. The site explores both, keeps the faster
/// by EWMA, and re-tests on a cadence, so a class that has stopped
/// describing the work costs at most the trial rate rather than
/// every dispatch until something notices.
///
/// Returns `None` for the arm when there is no site to measure
/// against or the caller pinned the plan, which are the cases where
/// nothing was chosen and so nothing should be recorded.
pub fn apply_site_class_measured(
self,
) -> (Self, Option<crate::sched::call_site::PolicyArm>) {
use crate::sched::call_site::PolicyArm;
if self.caller_pinned() {
return (self, None);
}
let Some(site) = self.site else {
return (self, None);
};
if site.get().learned_class().is_none() {
return (self, None);
}
let arm = site.get().choose_routing_arm();
match arm {
PolicyArm::Default => (self.apply_site_class(), Some(arm)),
PolicyArm::Alternative => (self, Some(arm)),
}
}
/// Builder: set the hardware class. See [`Self::hw_class`] for what
/// a matrix-extension class steers.
pub fn with_hw_class(mut self, hw: HwClass) -> Self {
self.hw_class = hw;
self
}
/// Builder: set the variant.
pub fn with_variant(mut self, v: Variant) -> Self {
self.variant = v;
self
}
/// Builder: set the NUMA hint.
pub fn with_numa_hint(mut self, node: u32) -> Self {
self.numa_hint = Some(node);
self
}
/// Builder: activate the SMT sibling workers for this submit.
/// See [`Self::use_smt`] for the workload-classification guide.
pub fn with_smt(mut self) -> Self {
self.use_smt = true;
self
}
/// Builder: tag the plan with a caller-supplied estimate of the
/// per-item cost in nanoseconds. Dispatchers consult this via
/// [`Self::estimated_total_ns`] to make static serial-vs-parallel
/// decisions at entry, bypassing rdtsc-polling in the hot loop.
///
/// This alone does not size a leaf. It steers the tier pick, the
/// inline-collapse decision, the adaptive leaf floor and the seed
/// depth, all from the cost by itself. The Tiny-Tasks leaf width in
/// [`Self::optimal_chunk_count_for`] needs a per-task overhead as
/// well, so add [`Self::with_task_overhead_ns`] to reach it. A plan
/// stating only the cost is not inert; it simply splits by the SLAW
/// budget rather than by the model.
///
/// Also re-runs the static initial classifier
/// ([`crate::sched::adaptive_profile::infer_class_static`]) with
/// the new hint and updates the plan's `use_smt` /
/// `oversubscription_log2` / `bisect_variant` based on the
/// new classification. The caller's hint is authoritative -- it
/// overrides the (k_outer, batch_size)-only guess that
/// [`Self::new`] made before the hint was available.
///
/// A profile the caller named is not that guess, so a plan built
/// through [`Self::set_profile`] or [`Self::for_op_generic`] keeps
/// its profile and takes only the estimate. Both are the caller
/// speaking, and re-classifying would answer one by discarding the
/// other.
pub fn with_estimated_per_item_ns(mut self, ns_per_item: u32) -> Self {
self.estimated_per_item_ns = Some(ns_per_item);
self.estimated_per_item_ns_explicit = true;
if self.profile_explicit {
return self;
}
let class = crate::sched::adaptive_profile::infer_class_static_with_shape(
self.k_outer,
self.batch_size,
Some(ns_per_item),
self.leaf_shape,
);
let profile = class.to_dispatch_profile();
// Re-apply the profile-derived knobs but preserve the new
// ns hint (set_profile would overwrite estimated_per_item_ns
// with the profile default).
self.use_smt = profile.is_latency_bound();
self.oversubscription_log2 = Some(profile.default_oversubscription_log2());
self.use_mailbox_routing = profile.use_mailbox_routing();
self.deque_tier_hint = profile.deque_tier_hint();
self
}
/// Compute the predicted total compute cost in nanoseconds from
/// `estimated_per_item_ns * batch_size`. Returns `None` if no
/// per-item estimate has been set. Used by
/// `collect_indexed_heartbeat` and similar dispatchers to gate
/// serial-vs-parallel at entry without rdtsc-polling.
#[inline]
pub fn estimated_total_ns(&self) -> Option<u64> {
self.estimated_per_item_ns
.map(|per_item| (per_item as u64).saturating_mul(self.batch_size as u64))
}
/// Builder: per-task scheduler overhead (Tiny-Tasks). See field
/// docs on [`Self::task_overhead_ns`].
///
/// Inert on its own. It is read only by
/// [`Self::optimal_chunk_count_for`], which needs a per-item cost
/// as well, so a plan setting this and nothing else routes exactly
/// as a plan setting neither. Pair it with
/// [`Self::with_estimated_per_item_ns`], or leave the entry probe
/// to measure the cost, and the chunked walks size their leaf from
/// the model.
pub fn with_task_overhead_ns(mut self, overhead_ns: u32) -> Self {
self.task_overhead_ns = Some(overhead_ns);
self
}
/// Builder: per-task critical-path span (Tiny-Tasks). See field
/// docs on [`Self::task_span_ns`].
pub fn with_task_span_ns(mut self, span_ns: u32) -> Self {
self.task_span_ns = Some(span_ns);
self
}
/// Builder: caller-supplied effective task count (Tiny-Tasks).
/// See field docs on [`Self::effective_task_count`].
pub fn with_effective_task_count(mut self, count: u32) -> Self {
self.effective_task_count = Some(count);
self
}
/// Builder: SIMD lane fanout for matmul kernels (BLIS K_inner).
/// See field docs on [`Self::k_inner_log2`].
pub fn with_k_inner_log2(mut self, log2: u8) -> Self {
self.k_inner_log2 = Some(log2);
self
}
/// Output cells a matmul inner loop carries per k-iteration:
/// `2^k_inner_log2`, and 1 when the hint is unset.
///
/// The shift is capped at the pointer width, so no `log2` a caller
/// can pass overflows it. A width wider than the matrix's column
/// count is not an error: the blocked loop takes no whole group and
/// every column falls to the one-at-a-time tail, which is the same
/// arithmetic as a width of 1.
#[inline]
pub fn k_inner_lanes(&self) -> usize {
match self.k_inner_log2 {
None => 1,
Some(log2) => 1usize << u32::from(log2).min(usize::BITS - 1),
}
}
/// Builder: route this job to a specific backend. See field
/// docs on [`Self::backend_hint`].
pub fn with_backend(mut self, backend: Backend) -> Self {
self.backend_hint = Some(backend);
self
}
/// Builder: caller-supplied per-element cost estimate. The
/// canonical name in the scheduler-tuning vocabulary for
/// [`Self::with_estimated_per_item_ns`], and the same call:
/// `for_each_chunk` reads it to derive the optimal leaf count
/// (cap dispatch overhead at a fraction of per-leaf work) and the
/// inline-collapse threshold, and it re-runs the classifier on the
/// same terms.
pub fn with_cost_ns_per_elem(self, ns_per_elem: u32) -> Self {
self.with_estimated_per_item_ns(ns_per_elem)
}
/// Builder: how long a thread waiting on a half of this dispatch
/// polls the latch before yielding its core, in nanoseconds. See
/// [`Self::spin_before_yield_ns`]; `0` yields immediately. Setting
/// it takes the decision away from the classifier and from this
/// host's measured profile.
pub fn with_spin_before_yield_ns(mut self, ns: u64) -> Self {
self.spin_before_yield_ns = Some(ns);
self
}
/// The spin budget a waiter on this dispatch uses: the caller's
/// own value when set, else this host's measured collapse
/// threshold, which is the span a short dispatched call completes
/// within, else zero while that has not been measured.
///
/// The budget drops to zero when one item is expected to outlast
/// it. A waiter spins because the half it waits on is about to
/// finish; when a single item runs longer than the whole spin,
/// that premise is false and the spin only denies a core to the
/// thief being waited on. The per-item estimate decides this, not
/// [`Self::use_smt`]: that flag says siblings help hide stalls on
/// this workload, which is a claim about execution ports and is
/// unrelated to how long a waiter should poll.
#[inline]
pub fn effective_spin_before_yield_ns(&self) -> u64 {
if let Some(ns) = self.spin_before_yield_ns {
return ns;
}
let budget = crate::sched::par_iter::measured_collapse_threshold_ns().unwrap_or(0);
match self.effective_ns_per_elem() {
Some(per) if u64::from(per) >= budget => 0,
_ => budget,
}
}
/// Builder: override the leaf-count oversubscription factor as
/// `log2(leaves_per_worker)`. Clamps to `[0, 3]` internally
/// (1..8 leaves per worker). Set to 0 to force one leaf per
/// worker (no oversubscription), 1 for the default 2x, 2 for
/// 4x (latency-bound default), 3 for 8x (maximum steal headroom).
pub fn with_oversubscription_log2(mut self, log2: u8) -> Self {
self.oversubscription_log2 = Some(log2.min(3));
self.oversubscription_log2_explicit = true;
self
}
/// Builder: cap the worker count for this dispatch. `1` forces
/// serial execution on the calling thread; `physical_cores`
/// keeps the SMT siblings parked even when `use_smt = true`;
/// the default (None) uses the full per-arena worker count.
pub fn with_workers(mut self, workers: u32) -> Self {
self.worker_cap = Some(workers.max(1));
self
}
/// Builder: select an experimental `for_each_chunk` policy
/// variant for bench A/B comparison. See [`BisectVariant`]
/// for the variant catalog.
pub fn with_bisect_variant(mut self, variant: BisectVariant) -> Self {
self.bisect_variant = Some(variant);
self
}
/// Effective per-element cost in nanoseconds: returns the
/// explicit override if set, else `None`. `for_each_chunk`
/// uses this for oversubscription tuning when set, falling
/// back to the global split-multiplier when unset.
#[inline]
pub fn effective_ns_per_elem(&self) -> Option<u32> {
self.estimated_per_item_ns
}
/// Effective leaf-count oversubscription `log2` for this plan.
/// Returns the explicit override when set, otherwise the
/// conservative default (`1` = 2x oversubscription).
#[inline]
pub fn effective_oversubscription_log2(&self) -> u8 {
self.oversubscription_log2.unwrap_or(1)
}
/// Leaves per worker for this dispatch's split budget. A factor
/// the caller set with [`Self::with_oversubscription_log2`] wins
/// and the process-global split observer is not consulted at all;
/// otherwise the observer's measured multiplier applies, which is
/// what a profile-derived or learned factor defers to.
#[inline]
pub fn effective_leaves_per_worker(&self) -> usize {
if self.oversubscription_log2_explicit {
return 1usize << self.effective_oversubscription_log2();
}
(crate::sched::split_observer::split_multiplier() as usize).max(1)
}
/// The worker count this dispatch may spread over: the pool's
/// width, capped by [`Self::worker_cap`] when the caller set one.
/// A cap of 1 leaves a single worker, which is how a caller asks
/// for serial execution.
#[inline]
pub fn effective_workers(&self, arena_workers: usize) -> usize {
self.worker_cap
.map(|cap| (cap as usize).min(arena_workers))
.unwrap_or(arena_workers)
.max(1)
}
/// True when the caller capped this dispatch to a single worker,
/// which [`Self::with_workers`] documents as serial execution on
/// the calling thread. Read from the plan alone, so a dispatch
/// surface can take the serial path before it reads the pool's
/// width or starts the pool.
#[inline]
pub(crate) fn capped_to_caller(&self) -> bool {
self.worker_cap == Some(1)
}
/// A copy of this plan with no worker cap, for a fork whose arms
/// must run at once whatever the caller capped: a race's arms.
#[inline]
pub(crate) fn without_worker_cap(&self) -> Self {
Self {
worker_cap: None,
..*self
}
}
/// Variance-corrected SMT activation decision. Combines the
/// plan's `use_smt` prior with the observer's measured per-
/// leaf execution-time variance:
///
/// - If the plan explicitly sets `use_smt = false`, returns
/// `false` (no observer signal re-enables SMT).
/// - If the plan sets `use_smt = true` and the observer has
/// recorded measured per-leaf time variance with low cv^2
/// (below the class thresholds' `cv2_low_per_mille`, 50 per
/// mille by default, i.e. nearly uniform leaves), returns
/// `false`. SMT siblings contest the same execution unit
/// on uniform-cost work and produce no gain.
/// - Otherwise returns `true`, trusting the plan's prior. That
/// includes leaves too short for their spread to be read, a mean
/// under the 256 ns unit it is kept in: no reading is not a low
/// one.
///
/// The variance signal prefers this plan's per-call-site
/// history when a site is attached and has recorded at least 4
/// leaves, so a uniform-cost closure gets SMT suppressed from
/// its own evidence even when other closures in the process are
/// high-variance. Site-less plans consult the process-wide
/// counters. The first call at any site sees no variance
/// history and pays the SMT cost; subsequent calls converge
/// within a few samples.
///
/// The site's figure is the window its classifier last read, the
/// same quantity `cv2_low_per_mille` bounds when a class is
/// decided, and it ages: a stretch of spread leaves the window as
/// later windows replace it. The site's lifetime cv^2 answers only
/// until a window has been classified. That figure is an
/// equal-weight average over every leaf the site has ever run, so a
/// period of contention can only be diluted by running enough later
/// leaves to outweigh it, and a decision resting on it does not come
/// back when the host goes quiet.
#[inline]
pub fn effective_use_smt(&self) -> bool {
if !self.use_smt {
return false;
}
let threshold = crate::sched::adaptive_profile::class_thresholds()
.cv2_low_per_mille
.load(core::sync::atomic::Ordering::Relaxed);
if let Some(site) = self.site {
let state = site.get();
// The window ages out and the lifetime figure does not, so
// the switch chooses between a decision that can come back
// and one that cannot.
let from_window = crate::sched::levers::smt_from_window();
let cv2 = if from_window {
state.window_cv2_per_mille().or_else(|| state.cv2_per_mille())
} else {
state.cv2_per_mille()
};
if let Some(cv2) = cv2 {
let decided = cv2 >= threshold;
// Only while the lever is on, so the shipped path pays a
// predictable branch and no atomic. The window figure is
// one classifier tick and moves between dispatches, so
// this decision is not constant over a run and a single
// reading of it describes one dispatch.
if from_window {
SMT_WINDOW_DECISIONS[decision_slot(decided)]
.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
}
return decided;
}
}
let stats = crate::sched::split_observer::snapshot_leaf_stats();
!matches!(
crate::sched::split_observer::leaf_cv_squared_per_mille(stats),
Some(cv2) if cv2 < threshold
)
}
/// Resolve the backend this plan should dispatch to. If
/// [`Self::backend_hint`] is `Some(b)` and a matching backend
/// is registered, returns that. Otherwise returns the always-
/// available CPU backend.
///
/// This is the single resolution point every routing helper
/// goes through; consumers do not need to handle the hint /
/// fallback logic themselves.
pub fn pick_backend(&self) -> BackendRef {
if let Some(hint) = self.backend_hint
&& let Some(backend) = crate::backend::backend_by_id(&hint)
{
return backend;
}
cpu_backend()
}
/// Optimal chunk count via the Tiny-Tasks model (Acar 2013):
///
/// ```text
/// C_opt = clamp(sqrt(W * P / (O + S)), 1, N)
/// ```
///
/// where `W` is total estimated work in ns, `P` is worker count,
/// `O` is per-task overhead, `S` is the per-chunk serial span
/// ([`Self::task_span_ns`], zero when unset), and `N` is the
/// effective task count (`effective_task_count` if set, else
/// `batch_size`).
///
/// Returns `None` if `estimated_per_item_ns` or `task_overhead_ns`
/// are unset - callers must fall back to the SLAW splitter's
/// budget heuristic.
///
/// Sizes against this plan's own task count. For a run of some
/// other length, [`Self::optimal_chunk_count_for`] takes the count.
///
/// Derivation sketch: total-time = serial_work / C + (O + S) * C.
/// A chunk pays the scheduler's overhead and its own serial span
/// once each, whatever work it carries, so the two enter the
/// optimization as one per-chunk fixed cost. d/dC = -W/C^2 +
/// (O + S) = 0 ⇒ C = sqrt(W / (O + S)). Including parallelism
/// (P workers running in parallel) bumps the optimal C up by a
/// factor of sqrt(P) because each worker's fixed cost is paid
/// once but the work is divided P-ways. A larger span therefore
/// yields fewer, coarser chunks: the serial part is paid per
/// chunk and splitting further buys less than it costs.
#[inline]
pub fn optimal_chunk_count(&self, workers: usize) -> Option<u32> {
let n = self.effective_task_count.unwrap_or(self.batch_size) as usize;
self.optimal_chunk_count_for(workers, n)
}
/// [`Self::optimal_chunk_count`] over `n` items instead of over
/// the count this plan carries. Same model and same `None`; the
/// result is at least one chunk and at most `n`, saturating at
/// `u32::MAX` rather than wrapping.
///
/// Reads `estimated_per_item_ns` as a field. A profile fills it
/// with a default, so a plan that states only `task_overhead_ns`
/// gets an answer here computed from a cost its caller never wrote.
/// The chunked walks require the cost to have been stated or
/// probed, and consult `estimated_per_item_ns_explicit` first.
#[inline]
pub fn optimal_chunk_count_for(&self, workers: usize, n: usize) -> Option<u32> {
let per_item = self.estimated_per_item_ns? as u64;
let overhead = self.task_overhead_ns? as u64;
let n = n as u64;
// The span is the other half of a chunk's fixed cost; unset
// means zero, which leaves the formula as overhead alone.
let fixed = overhead.saturating_add(self.task_span_ns.unwrap_or(0) as u64);
let as_count = |c: u64| c.min(u32::MAX as u64) as u32;
if n == 0 || fixed == 0 || per_item == 0 {
return Some(as_count(n));
}
let w_total = per_item.saturating_mul(n);
let p = (workers as u64).max(1);
// C = sqrt(W * P / (O + S)). Use isqrt to stay in integer space.
let radicand = w_total.saturating_mul(p).checked_div(fixed).unwrap_or(0);
let c_opt = integer_sqrt(radicand);
Some(as_count(c_opt.max(1).min(n)))
}
/// The workers that will actually run this plan's work: the
/// process arena's primaries, plus its SMT siblings when this plan
/// wakes them, capped by [`Self::worker_cap`].
///
/// Under the default worker sizing this equals the arena's whole
/// width: the per-node count defaults to the node's logical
/// threads, and no SMT extension is spawned when the primaries
/// already cover them, so a 24-thread host reads 24 whatever the
/// plan says about SMT.
///
/// It diverges from `NumaArena::total_workers` only where the
/// primaries are fewer than the logical threads:
/// `FLYNNEL_SCHED_PHYSICAL_ONLY=on`, `FLYNNEL_SCHED_SMT=off`, or an
/// explicit `FLYNNEL_SCHED_WORKERS` below the logical count. There
/// the siblings exist and park unless a dispatch with `use_smt` is
/// in flight, so `total_workers` counts threads that exist rather
/// than threads that run, and this is the count to divide work by.
///
/// It is also capped by the CPUs this process is allowed to use
/// right now, from
/// [`crate::sched::host_width::allowed_parallelism`]. The pool is
/// spawned once and its threads outlive a change to the process
/// affinity mask or the cgroup quota, so on a host that has narrowed
/// since startup the arena counts workers that can no longer reach a
/// core. Chunking against that count divides the work among threads
/// that will not run it.
///
/// Starts the arena if it is not already running.
#[inline]
#[must_use]
pub fn resolved_workers(&self) -> usize {
let arena = crate::sched::arena::global_local_arena();
let running = if self.effective_use_smt() {
arena.total_workers()
} else {
arena.primary_workers()
};
// The query is a syscall and a cgroup read, cached on a cadence;
// a caller that turns the lever off takes it off this path
// entirely.
let running = capped_by_allowed_width(
running,
crate::sched::levers::allowed_width(),
crate::sched::host_width::allowed_parallelism,
);
self.effective_workers(running)
}
}
/// Dispatches the window-driven SMT switch decided each way, indexed by
/// the decision: `[0]` counts false, `[1]` counts true.
///
/// Counted only while the lever is on. The switch reads one classifier
/// tick and that figure moves between dispatches, so its decision is not
/// constant over a run and a reading taken once reports one dispatch.
static SMT_WINDOW_DECISIONS: [core::sync::atomic::AtomicU64; 2] = [
core::sync::atomic::AtomicU64::new(0),
core::sync::atomic::AtomicU64::new(0),
];
/// The slot a decision is counted in: `1` when SMT was allowed, `0`
/// when it was declined, matching the `(declined, allowed)` order
/// [`smt_window_decisions`] publishes.
#[inline]
fn decision_slot(decided: bool) -> usize {
usize::from(decided)
}
/// How many dispatches the window-driven SMT switch sent each way, as
/// `(declined, allowed)`. Both zero while the lever is off, which is
/// distinct from a lever that ran and always answered the same way.
pub fn smt_window_decisions() -> (u64, u64) {
(
SMT_WINDOW_DECISIONS[0].load(core::sync::atomic::Ordering::Relaxed),
SMT_WINDOW_DECISIONS[1].load(core::sync::atomic::Ordering::Relaxed),
)
}
/// `running` narrowed to the CPUs the process may currently use.
///
/// The probe is a closure so the switch short-circuits it: with the
/// lever off the syscall and cgroup read never happen.
///
/// Narrows only. The arena's threads are spawned once, so a width above
/// the spawned count names threads that do not exist and the pool
/// cannot grow into it.
fn capped_by_allowed_width<P>(running: usize, lever_on: bool, allowed: P) -> usize
where
P: FnOnce() -> usize,
{
if lever_on { running.min(allowed()) } else { running }
}
/// Integer square root for u64. Used by `optimal_chunk_count` to
/// stay out of f64 (which loses precision past 2^53). Newton's
/// method bottoms out in O(log log W) iterations from the seed.
#[inline]
fn integer_sqrt(n: u64) -> u64 {
if n < 2 {
return n;
}
// Seed with f64 sqrt for the initial guess; refine via Newton.
let mut x = (n as f64).sqrt() as u64;
// Two Newton steps are enough at u64 scale.
for _ in 0..2 {
if x == 0 { return 0; }
let y = (x + n / x) >> 1;
if y >= x { break; }
x = y;
}
while x * x > n { x -= 1; }
while (x + 1) * (x + 1) <= n { x += 1; }
x
}
/// Whether a declared tile class promotes out of Inline on its item
/// count alone.
///
/// A matrix-extension class says the item is a tile operation, and the
/// smallest AMX or tensor-core tile is a multiply-accumulate over a
/// 16x16 block. One tile never promotes: one item is one leaf, so there
/// is nothing to split and a dispatch can only add its own cost.
///
/// Above one tile the count is a poor proxy. A consumer sweep at depth
/// 16 has a 2x2 grid at 0.94x and a 4x4 at 2.71x, so some count between
/// four and sixteen tiles is the crossing. A caller that declares what
/// an item costs does not need it located: `estimated_per_item_ns`
/// times the batch, against this host's own collapse threshold, is the
/// same question asked in work rather than in tiles, and it yields a
/// different tile count on every host. So the count only decides for a
/// caller who declared no cost.
///
/// `explicit_estimate` is the caller's own figure rather than a
/// classifier default, which is a routing hint and not a claim about
/// this item.
pub fn promotes_on_tile_count(
is_matrix_extension: bool,
batch_size: u32,
explicit_estimate: bool,
) -> bool {
is_matrix_extension && batch_size > 1 && !explicit_estimate
}
/// Classify a K_outer into its tier band before considering
/// batch-size or NUMA topology. Returns the tier the job would land
/// at if batch_size and topology were "typical."
///
/// - K <= 4 -> Inline
/// - K = 5..7 -> Local
/// - K = 8..10 -> Hierarchical
/// - K >= 11 -> Federated
pub fn kband_for(k_outer: u8) -> SchedTier {
match k_outer {
0..=4 => SchedTier::Inline,
5..=7 => SchedTier::Local,
8..=10 => SchedTier::Hierarchical,
_ => SchedTier::Federated,
}
}
/// Pick the scheduler tier for a job given its plan and the host's
/// NUMA topology. Honors the K-band classification with two
/// adjustments:
///
/// 1. Local / Hierarchical work with `batch_size < 32` falls back to
/// Inline because tier-dispatch overhead dominates one or two
/// items.
/// 2. K_outer in the Hierarchical band collapses to Local when the
/// host is single-NUMA (no benefit from per-node arenas).
///
/// Marked `#[inline(always)]` so the tier dispatch collapses at
/// every call site where `k_outer` or `batch_size` is a compile-time
/// constant (typical for `FpN<const N: usize>` const-generic call
/// chains). LLVM eliminates the kband_for match + the
/// batch_size threshold branches via const propagation.
#[inline(always)]
pub fn pick_tier(plan: &JobPlan, topo: &NumaTopology) -> SchedTier {
// Caller-explicit parallelism opt-in: if the caller has set a
// leaf-shape hint (LeafShape::PortCompute, LatencyCompute,
// etc.) via the `with_leaf_shape` builder, the workload is
// not a BigFloat-tier op for which K_outer characterizes per-
// op cost. Treat the leaf-shape signal as authoritative:
// route to the worker pool whenever the batch can plausibly
// amortize dispatch (>= 8 items as a floor; per-item shape
// signals the actual cost) regardless of K_outer. Without
// this, callers that supply K=0 because their workload has no
// number-system precision tier (lexers, generic data-parallel
// ops) are silently routed to inline serial execution,
// defeating the entire point of constructing the plan via the
// closing-loop classifier.
//
// We deliberately check only `leaf_shape`. The other plan
// fields that look like they signal intent (`bisect_variant`,
// `estimated_per_item_ns`) are auto-populated by
// `JobPlan::new` via the static classifier and the per-arch
// variant routing; they reflect classifier defaults rather
// than caller assertion. `with_leaf_shape` is the only
// builder that sets `leaf_shape` to a non-`Unknown` value, so
// it is the unambiguous opt-in signal.
let has_explicit_shape =
plan.leaf_shape != crate::sched::adaptive_profile::LeafShape::Unknown;
if has_explicit_shape && plan.batch_size >= 8 {
// Caller said "this is parallel work." Honor it; fall
// through to the per-tier batch-size adjustments below
// by re-binding base to Local for the K=0..=4 case so the
// tier-fallback chain still respects the multi-NUMA
// promotion logic for Hierarchical-band K values.
let base = match kband_for(plan.k_outer) {
SchedTier::Inline => SchedTier::Local,
other => other,
};
return match base {
SchedTier::Local => SchedTier::Local,
SchedTier::Hierarchical => {
if topo.is_multi_node() {
SchedTier::Hierarchical
} else {
SchedTier::Local
}
}
SchedTier::Federated => SchedTier::Federated,
// Unreachable: the match above promoted Inline to Local.
SchedTier::Inline => SchedTier::Local,
};
}
// Heavy-per-item small-N override: when the caller has supplied a
// per-item cost hint and predicted total work exceeds the
// dispatch breakeven (~50us), promote out of Inline regardless of
// batch_size. The N >= 256 / N >= 32 floors below were tuned for
// workloads where per_item ~ 10ns to ~1us. For per_item ~ 10us+
// (BigFloat verify, sqrt-chains, FMA-heavy kernels) even N=4 is
// worth dispatching. Without this check `pick_tier` would route
// 4-item-of-10ms-each workloads to Inline, the join would
// serialize the bisect, and `for_each_chunk`'s adaptive
// min_leaf would never get a chance to fire.
//
// The threshold is this host's measured collapse threshold
// (`par_iter::inline_collapse_threshold_ns`), so the tier pick
// and the data-parallel entries agree on the least work that
// counts as "worth the pool" on the running host. Read only
// behind the explicit-estimate check: the calibration's own joins
// carry no explicit estimate and must not re-enter it.
//
// Only trust the per-item-cost estimate when the caller marked it
// authoritative (via with_estimated_per_item_ns or the probe-path
// amended_plan). Classifier defaults are routing hints and would
// produce false positives (12ns * 32 = 384ns -> never fires) or
// miss false negatives in the heavy direction without measurement.
let heavy_override = plan.estimated_per_item_ns_explicit
&& plan.estimated_per_item_ns.is_some_and(|ns| {
(ns as u64).saturating_mul(plan.batch_size as u64)
>= crate::sched::par_iter::inline_collapse_threshold_ns()
});
// A declared matrix-extension target is the caller saying the item
// is a tile operation: the smallest AMX or tensor-core tile is a
// multiply-accumulate over a 16x16 block. The vector classes say
// nothing a batch size does not already say, so only the matrix
// ones promote.
//
// One tile is never promoted: one item is one leaf, so there is
// nothing to split and the dispatch can only add its own cost. On
// an AMX-emulating strip a one-tile grid measures 2,388 ns serial
// against 2,827 ns dispatched.
//
// Above one tile the count alone is too eager: the same sweep has a
// 2x2 grid at 0.94x and a 4x4 at 2.71x. Where the caller has
// declared what an item costs, `heavy_override` above already
// decides that on measured work against this host's own collapse
// threshold, so the count steps aside and the crossover is a
// relation rather than a constant to locate.
let tile_override = promotes_on_tile_count(
plan.hw_class.is_matrix_extension(),
plan.batch_size,
plan.estimated_per_item_ns_explicit,
);
let base = kband_for(plan.k_outer);
match base {
SchedTier::Inline => {
// K <= 4 (n_limbs <= 16) per-op cost is ~50ns-2us.
// Promote to Local when the batch is large enough that
// aggregate parallel-iteration work amortizes dispatch,
// OR when the caller's heavy-per-item override fires.
//
// The 256 threshold assumes the in-worker fast path's
// ~50ns per-join dispatch (WorkerThread fast path +
// adaptive splitter + pin-default-off + adaptive
// peer-probe together); the breakeven is ~256 items
// for BigFloat-sized ops. Below 256 the per-call
// wrapper-inject cost (~10us) still exceeds the
// work-time savings; above, parallel wins. At ~60us
// per-join dispatch the breakeven measures ~1024.
//
// For lighter ops (e.g., u32 limb-add at sub-100ns
// per item) the breakeven is higher, but the per-call
// cost is small enough that 256-with-serial-fallback
// is the right default for hint-less callers.
//
// use_smt promotes for the same reason as in the Local
// band below: with_smt, set_profile(LatencyBound), and
// the hint-less batch <= 32 classifier all set it for
// heavy-per-item work. The par_iter probes reclassify
// light hint-less work to FineGrain (use_smt off), so
// tiny light batches stay inline.
if plan.batch_size >= 256 || heavy_override || tile_override || plan.use_smt {
SchedTier::Local
} else {
SchedTier::Inline
}
}
SchedTier::Local => {
// Small batch falls back to Inline unless one of:
// - heavy_override fired (explicit ns hint says total
// work >= 50us)
// - classifier set use_smt=true (LatencyBound profile,
// which means "heavy per-item with long FP chains" --
// for K=5..7 with no ns hint, the no-hint fallback
// route in infer_class_static maps batch_size<=32 to
// LatencyBound on the assumption that small-batch
// hint-less calls are usually NMFD-shape heavy items)
//
// Without the use_smt gate, NMFD-like 5-item-x-100ms
// workloads from JobPlan::new (no ns hint) route to
// Inline -> serial 500ms instead of parallel ~125ms,
// measured as 2x rayon-slowdown on cold_workloads bench
// `flynnel_def` column. Adding the use_smt check makes
// the static classifier's class choice authoritative
// for the inline-vs-parallel decision.
if plan.batch_size < 32 && !heavy_override && !tile_override && !plan.use_smt {
SchedTier::Inline
} else {
SchedTier::Local
}
}
SchedTier::Hierarchical => {
if !topo.is_multi_node() {
if plan.batch_size < 32 && !heavy_override && !tile_override && !plan.use_smt {
SchedTier::Inline
} else {
SchedTier::Local
}
} else {
SchedTier::Hierarchical
}
}
SchedTier::Federated => SchedTier::Federated,
}
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
use crate::foundation::Variant;
use crate::numa_topology::NumaTopology;
#[test]
fn for_profile_sets_smt_cost_and_oversubscription_together() {
// LatencyBound: SMT on, 600 ns/elem, 4x oversubscription.
let plan = JobPlan::set_profile(8, 1024, DispatchProfile::LatencyBound);
assert!(plan.use_smt);
assert_eq!(plan.estimated_per_item_ns, Some(600));
assert_eq!(plan.oversubscription_log2, Some(2));
// PortBound: SMT off, 12 ns/elem, 2x oversubscription.
let plan = JobPlan::set_profile(8, 1024, DispatchProfile::PortBound);
assert!(!plan.use_smt);
assert_eq!(plan.estimated_per_item_ns, Some(12));
assert_eq!(plan.oversubscription_log2, Some(1));
// MemoryBound: SMT on, 50 ns/elem, 2x oversubscription.
let plan = JobPlan::set_profile(8, 1024, DispatchProfile::MemoryBound);
assert!(plan.use_smt);
assert_eq!(plan.estimated_per_item_ns, Some(50));
assert_eq!(plan.oversubscription_log2, Some(1));
// Unspecified: SMT off, no cost estimate, 2x oversubscription.
let plan = JobPlan::set_profile(8, 1024, DispatchProfile::Unspecified);
assert!(!plan.use_smt);
assert_eq!(plan.estimated_per_item_ns, None);
assert_eq!(plan.oversubscription_log2, Some(1));
}
#[test]
fn direct_knobs_override_profile_defaults() {
let plan = JobPlan::set_profile(8, 1024, DispatchProfile::LatencyBound)
.with_cost_ns_per_elem(42)
.with_oversubscription_log2(0)
.with_workers(4);
assert_eq!(plan.estimated_per_item_ns, Some(42));
assert_eq!(plan.oversubscription_log2, Some(0));
assert_eq!(plan.worker_cap, Some(4));
// use_smt still inherited from the profile (LatencyBound).
assert!(plan.use_smt);
}
#[test]
fn with_workers_enforces_minimum_of_one() {
let plan = JobPlan::new(8, 1024).with_workers(0);
assert_eq!(plan.worker_cap, Some(1));
}
#[test]
fn with_oversubscription_log2_clamps_to_max_three() {
let plan = JobPlan::new(8, 1024).with_oversubscription_log2(99);
assert_eq!(plan.oversubscription_log2, Some(3));
}
#[test]
fn effective_use_smt_respects_plan_off_regardless_of_variance() {
// When the plan explicitly says SMT off, no variance
// measurement can re-enable it. Use `bare` because
// `JobPlan::new` now runs the static initial classifier
// which may pick a SMT-on profile (LatencyBound for K>=7).
let plan = JobPlan::bare(8, 1024);
assert!(!plan.use_smt);
assert!(!plan.effective_use_smt());
}
#[test]
fn sched_tier_all_covers_four_tiers() {
assert_eq!(SchedTier::ALL.len(), 4);
// Every variant appears exactly once.
for &t in &SchedTier::ALL {
assert_eq!(SchedTier::ALL.iter().filter(|&&x| x == t).count(), 1);
}
}
#[test]
fn spin_rounds_match_tier_design() {
assert_eq!(SchedTier::Inline.spin_rounds(), 0);
assert_eq!(SchedTier::Local.spin_rounds(), 8);
assert_eq!(SchedTier::Hierarchical.spin_rounds(), 32);
assert_eq!(SchedTier::Federated.spin_rounds(), 0);
}
#[test]
fn kband_inline_covers_micro_sizes() {
for k in 0..=4u8 {
assert_eq!(kband_for(k), SchedTier::Inline, "K={k} should be Inline");
}
}
#[test]
fn kband_local_covers_small_sizes() {
for k in 5..=7u8 {
assert_eq!(kband_for(k), SchedTier::Local, "K={k} should be Local");
}
}
#[test]
fn kband_hierarchical_covers_mid_sizes() {
for k in 8..=10u8 {
assert_eq!(kband_for(k), SchedTier::Hierarchical, "K={k} should be Hierarchical");
}
}
#[test]
fn kband_federated_covers_large_sizes() {
for k in 11..=20u8 {
assert_eq!(kband_for(k), SchedTier::Federated, "K={k} should be Federated");
}
}
#[test]
fn hw_class_matrix_extension_classification() {
// Vector-SIMD regime: K_R = 0..6
assert!(!HwClass::Scalar.is_matrix_extension());
assert!(!HwClass::Sse2.is_matrix_extension());
assert!(!HwClass::Avx2.is_matrix_extension());
assert!(!HwClass::Avx512f.is_matrix_extension());
assert!(!HwClass::Avx512Bf16.is_matrix_extension());
assert!(!HwClass::Avx512Vnni.is_matrix_extension());
assert!(!HwClass::Neon.is_matrix_extension());
// Matrix-extension regime: K_R = 10..16
assert!(HwClass::Sme.is_matrix_extension());
assert!(HwClass::AmxBf16.is_matrix_extension());
assert!(HwClass::AmxInt8.is_matrix_extension());
assert!(HwClass::AmxFp16.is_matrix_extension());
assert!(HwClass::TensorCoreHopper.is_matrix_extension());
assert!(HwClass::TensorCoreBlackwell.is_matrix_extension());
}
#[test]
fn the_tally_indexes_allowed_and_declined_the_right_way_round() {
// A reversed index would swap the two counts and report a lever
// that always allowed SMT as one that always declined it, which
// reads as a result rather than as a defect.
//
// Counted into a local pair rather than SMT_WINDOW_DECISIONS. A
// delta across two reads of those is this test's only while
// nothing else moves them in between, and any other test in this
// binary that reaches the `from_window` branch does.
let mut slots = [0u64; 2];
slots[decision_slot(true)] += 1;
assert_eq!(slots, [0, 1], "an allowed decision lands in slot one");
slots[decision_slot(false)] += 1;
assert_eq!(slots, [1, 1], "and a declined one in slot zero");
}
#[test]
fn a_narrowed_process_chunks_for_the_cpus_it_still_has() {
// The case the lever exists for: the arena spawned sixteen and
// the process may now use four.
assert_eq!(capped_by_allowed_width(16, true, || 4), 4);
assert_eq!(
capped_by_allowed_width(16, false, || 4),
16,
"with the switch off the shipped width stands whatever the host allows"
);
}
#[test]
fn the_cap_narrows_and_never_widens_past_the_spawned_pool() {
// A quota raised above the count the arena was spawned with
// names threads that do not exist. host_width tracks the
// widening; the pool cannot grow into it, and the minimum is
// what keeps a dispatch from chunking for absent workers.
assert_eq!(capped_by_allowed_width(16, true, || 64), 16);
assert_eq!(capped_by_allowed_width(16, true, || 16), 16);
}
#[test]
fn the_switch_short_circuits_the_probe() {
// The probe is a syscall and a cgroup read. With the lever off
// it must not run at all, which is what keeps the cost off a
// host that turned the lever off.
let mut probed = false;
let width = capped_by_allowed_width(16, false, || {
probed = true;
4
});
assert_eq!(width, 16);
assert!(!probed, "the lever is off, so the host was never asked");
}
#[test]
fn a_declared_cost_takes_the_tile_count_out_of_the_decision() {
// Pure, so the host's own collapse threshold is not needed to
// assert it. What happens once the count steps aside is
// `heavy_override`'s, which reads that threshold and cannot be
// pinned from inside a test.
assert!(
promotes_on_tile_count(true, 4, false),
"four tiles and no declared cost: the count is all there is"
);
assert!(
!promotes_on_tile_count(true, 4, true),
"four tiles with a declared cost: the work decides, not the count"
);
assert!(
!promotes_on_tile_count(true, 1, false),
"one item is one leaf, so there is nothing to split"
);
assert!(
!promotes_on_tile_count(false, 64, false),
"a vector class says nothing a batch size does not already say"
);
}
#[test]
fn job_plan_builder_chains() {
let p = JobPlan::new(8, 100)
.with_hw_class(HwClass::Avx2)
.with_variant(Variant::Correct)
.with_numa_hint(1);
assert_eq!(p.k_outer, 8);
assert_eq!(p.batch_size, 100);
assert_eq!(p.hw_class, HwClass::Avx2);
assert_eq!(p.variant, Variant::Correct);
assert_eq!(p.numa_hint, Some(1));
}
#[test]
fn pick_tier_inline_for_micro_k_small_batch() {
let topo = NumaTopology::fallback();
// Small K + small batch: serial wins.
let plan = JobPlan::new(2, 100);
assert_eq!(pick_tier(&plan, &topo), SchedTier::Inline);
}
#[test]
fn pick_tier_inline_k_promotes_to_local_on_large_batch() {
let topo = NumaTopology::fallback();
// Small K but huge batch: aggregate work dominates;
// parallel iteration pays off.
let plan = JobPlan::new(2, 1_000_000);
assert_eq!(pick_tier(&plan, &topo), SchedTier::Local);
}
#[test]
fn pick_tier_inline_for_small_batch_local_k() {
let topo = NumaTopology::fallback();
// PortBound profile rather than LatencyBound, so the small-batch
// inline-fallback fires. JobPlan::new(6, 16) without an ns
// hint now routes through the no-hint classifier fallback
// which maps batch_size<=32 to LatencyBound on the
// assumption that small-batch hint-less calls are usually
// NMFD-shape heavy items; LatencyBound disables the
// inline-fallback gate (use_smt=true). To exercise the
// fallback path, use an explicit PortBound profile that
// sets use_smt=false.
let plan = JobPlan::set_profile(6, 16, DispatchProfile::PortBound);
assert_eq!(pick_tier(&plan, &topo), SchedTier::Inline,
"PortBound + batch_size 16 in Local-K band should fall back to Inline");
}
#[test]
fn pick_tier_local_for_small_batch_latency_bound_no_hint() {
let topo = NumaTopology::fallback();
// JobPlan::new(6, 5) without ns hint -- the no-hint
// classifier routes batch_size<=32 to LatencyBound, which
// sets use_smt=true and bypasses the small-batch inline
// fallback. NMFD-shape workloads (5 heavy items) get the
// parallel worker pool on call 1 without any caller-supplied
// ns hint, avoiding the 2x slowdown measured on the
// cold_workloads flynnel_def NMFD-like cells when such
// workloads route to Inline.
let plan = JobPlan::new(6, 5);
assert_eq!(pick_tier(&plan, &topo), SchedTier::Local,
"small-batch LatencyBound (classifier no-hint default) stays Local");
}
#[test]
fn a_matrix_extension_class_promotes_a_batch_that_would_fold_inline() {
let topo = NumaTopology::fallback();
// PortBound so use_smt is off and the cost estimate is not
// explicit: with batch 8 the only thing that can move this off
// Inline is the declared class.
let vector = JobPlan::set_profile(2, 8, DispatchProfile::PortBound)
.with_hw_class(HwClass::Avx512f);
assert!(!vector.use_smt, "the arrangement under test has SMT off");
assert_eq!(
pick_tier(&vector, &topo),
SchedTier::Inline,
"a vector class says nothing the batch size does not"
);
let tiled = JobPlan::set_profile(2, 8, DispatchProfile::PortBound)
.with_hw_class(HwClass::AmxBf16);
assert_eq!(
pick_tier(&tiled, &topo),
SchedTier::Local,
"a tile batch with something to split promotes"
);
}
#[test]
fn a_single_tile_is_not_promoted_because_one_item_cannot_be_split() {
let topo = NumaTopology::fallback();
let one = JobPlan::set_profile(2, 1, DispatchProfile::PortBound)
.with_hw_class(HwClass::AmxBf16);
assert!(!one.use_smt, "the arrangement under test has SMT off");
assert_eq!(
pick_tier(&one, &topo),
SchedTier::Inline,
"one item is one leaf, so a dispatch adds its cost and splits nothing"
);
// Two is the smallest batch with anything to split, and the
// class is the only thing that can move it off Inline here.
let two = JobPlan::set_profile(2, 2, DispatchProfile::PortBound)
.with_hw_class(HwClass::AmxBf16);
assert_eq!(pick_tier(&two, &topo), SchedTier::Local);
}
#[test]
fn pick_tier_local_for_normal_batch_local_k() {
let topo = NumaTopology::fallback();
let plan = JobPlan::new(6, 1024);
assert_eq!(pick_tier(&plan, &topo), SchedTier::Local);
}
#[test]
fn pick_tier_hierarchical_k_collapses_to_local_on_single_node() {
let topo = NumaTopology::fallback();
// Single-NUMA host: Hierarchical band should collapse to Local.
let plan = JobPlan::new(9, 1024);
assert_eq!(pick_tier(&plan, &topo), SchedTier::Local);
}
#[test]
fn pick_tier_hierarchical_k_stays_hierarchical_on_multi_node() {
// Build a synthetic 2-node topology.
let mut topo = NumaTopology::fallback();
topo.num_nodes = 2;
topo.node_of_cpu = vec![0, 0, 1, 1];
topo.distances = vec![vec![10, 20], vec![20, 10]];
let plan = JobPlan::new(9, 1024);
assert_eq!(pick_tier(&plan, &topo), SchedTier::Hierarchical);
}
#[test]
fn integer_sqrt_matches_f64_for_small_values() {
for n in 0u64..1000 {
let s = super::integer_sqrt(n);
assert!(s * s <= n);
assert!((s + 1) * (s + 1) > n);
}
}
#[test]
fn integer_sqrt_at_pow2_boundaries() {
for shift in 0..63 {
let n = 1u64 << shift;
let s = super::integer_sqrt(n);
assert!(s * s <= n, "n=2^{shift} integer_sqrt={s} squared exceeds n");
assert!(
(s + 1) * (s + 1) > n,
"n=2^{shift} integer_sqrt={s}+1 squared below n",
);
}
}
#[test]
fn optimal_chunk_count_none_without_estimates() {
let p = JobPlan::new(6, 1024);
assert!(p.optimal_chunk_count(8).is_none());
let p2 = JobPlan::new(6, 1024).with_estimated_per_item_ns(50);
// task_overhead_ns still None.
assert!(p2.optimal_chunk_count(8).is_none());
}
#[test]
fn optimal_chunk_count_scales_with_workers_and_inversely_with_overhead() {
let base = JobPlan::new(6, 1024)
.with_estimated_per_item_ns(50)
.with_task_overhead_ns(500);
let c1 = base.optimal_chunk_count(1).unwrap();
let c8 = base.optimal_chunk_count(8).unwrap();
// More workers means more chunks make sense.
assert!(c8 >= c1, "c8={c8} should be >= c1={c1}");
// Higher overhead -> fewer chunks (each chunk costs more).
let heavy_overhead = JobPlan::new(6, 1024)
.with_estimated_per_item_ns(50)
.with_task_overhead_ns(5000);
let c_heavy = heavy_overhead.optimal_chunk_count(8).unwrap();
assert!(c_heavy <= c8, "heavier overhead should reduce chunks");
}
#[test]
fn a_serial_span_coarsens_the_split_and_no_span_leaves_it_alone() {
let base = || JobPlan::new(6, 4096).with_estimated_per_item_ns(50).with_task_overhead_ns(500);
let none = base().optimal_chunk_count(8).expect("estimates are set");
// Unset and zero are the same answer: the span enters as an
// added fixed cost, and zero adds nothing.
assert_eq!(
base().with_task_span_ns(0).optimal_chunk_count(8),
Some(none),
"a zero span must not move the split"
);
// A span the size of the overhead doubles the per-chunk fixed
// cost, so the chunk count falls.
let equal = base().with_task_span_ns(500).optimal_chunk_count(8).expect("set");
assert!(equal < none, "span 500 gave {equal} chunks, no span gave {none}");
// Monotone: more span, never more chunks.
let mut prev = none;
for span in [100u32, 500, 2_000, 10_000, 100_000] {
let c = base().with_task_span_ns(span).optimal_chunk_count(8).expect("set");
assert!(c <= prev, "span {span} gave {c} chunks after {prev}");
prev = c;
}
assert!(prev >= 1, "the split never collapses below one chunk");
}
#[test]
fn k_inner_lanes_is_two_to_the_hint_and_one_when_unset() {
assert_eq!(JobPlan::new(6, 64).k_inner_lanes(), 1, "unset is one cell");
for log2 in 0u8..8 {
assert_eq!(
JobPlan::new(6, 64).with_k_inner_log2(log2).k_inner_lanes(),
1usize << log2,
"log2 {log2}"
);
}
// A width no pointer can hold is capped rather than shifted
// past the type, so no caller value is undefined behavior.
assert!(JobPlan::new(6, 64).with_k_inner_log2(u8::MAX).k_inner_lanes() > 0);
}
#[test]
fn optimal_chunk_count_clamps_to_effective_task_count() {
let p = JobPlan::new(6, 1_000_000)
.with_estimated_per_item_ns(1)
.with_task_overhead_ns(1_000_000_000)
.with_effective_task_count(16);
// With huge overhead the formula collapses to "1 chunk";
// clamp to effective_task_count=16.
let c = p.optimal_chunk_count(8).unwrap();
assert!(c <= 16, "chunk count must clamp at effective_task_count");
}
#[test]
fn spin_budget_prefers_the_caller_then_the_item_cost_then_the_host() {
// A caller's own budget wins outright, on any plan.
let pinned = JobPlan::new(6, 10_000).with_spin_before_yield_ns(1234);
assert_eq!(pinned.effective_spin_before_yield_ns(), 1234);
let pinned_heavy = JobPlan::new(6, 8)
.with_estimated_per_item_ns(100_000_000)
.with_spin_before_yield_ns(4321);
assert_eq!(pinned_heavy.effective_spin_before_yield_ns(), 4321,
"an explicit budget wins even where the item cost would zero it");
// The host's own measured budget, which every branch below is
// read against.
let host = crate::sched::par_iter::host_dispatch_profile().collapse_threshold_ns;
assert!(host > 0, "the profile is measured by the query above");
// An item that outlasts the whole spin: the half being waited
// on is not about to finish, so the waiter yields at once.
let heavy = JobPlan::new(6, 8).with_estimated_per_item_ns(u32::MAX);
assert_eq!(heavy.effective_spin_before_yield_ns(), 0);
// An item far shorter than the budget: spin for the budget.
let light = JobPlan::new(6, 10_000).with_estimated_per_item_ns(1);
assert_eq!(light.effective_spin_before_yield_ns(), host);
// The SMT flag is a claim about execution ports and says
// nothing about how long to poll, so it must not move this.
let smt_light = JobPlan::new(6, 10_000).with_estimated_per_item_ns(1).with_smt();
assert!(smt_light.use_smt);
assert_eq!(smt_light.effective_spin_before_yield_ns(), host,
"with_smt must not zero the spin budget of a short-item plan");
}
#[test]
fn pick_tier_federated_for_large_k() {
let topo = NumaTopology::fallback();
let plan = JobPlan::new(13, 1);
// Federated does not collapse on batch_size; large K is its
// own concern (single op may take milliseconds).
assert_eq!(pick_tier(&plan, &topo), SchedTier::Federated);
}
#[test]
fn the_no_argument_chunk_count_is_the_item_count_form_over_its_own_count() {
let p = JobPlan::new(6, 4096)
.with_estimated_per_item_ns(50)
.with_task_overhead_ns(500);
assert_eq!(p.optimal_chunk_count(8), p.optimal_chunk_count_for(8, 4096));
// effective_task_count is the count the no-argument form uses
// when set, so the item-count form reproduces it by being
// handed that number and not batch_size.
let counted = p.with_effective_task_count(256);
assert_eq!(
counted.optimal_chunk_count(8),
counted.optimal_chunk_count_for(8, 256)
);
assert_ne!(
counted.optimal_chunk_count_for(8, 4096),
counted.optimal_chunk_count_for(8, 256),
"a different item count must give a different answer, or the parameter does nothing"
);
}
#[test]
fn a_chunk_count_needs_both_hints_and_never_exceeds_the_item_count() {
let n = 4096usize;
assert!(JobPlan::new(6, 4096).optimal_chunk_count_for(8, n).is_none());
assert!(
JobPlan::new(6, 4096)
.with_estimated_per_item_ns(50)
.optimal_chunk_count_for(8, n)
.is_none(),
"a per-item cost without an overhead has no fixed cost to divide by"
);
// Unspecified is the profile that supplies no default cost.
// JobPlan::new takes one from its profile, so a plan built that
// way and given an overhead does reach the model.
let no_cost =
JobPlan::set_profile(6, 4096, crate::dispatch_profile::DispatchProfile::Unspecified);
assert!(no_cost.estimated_per_item_ns.is_none());
assert!(
no_cost.with_task_overhead_ns(500).optimal_chunk_count_for(8, n).is_none(),
"an overhead without a per-item cost has no work to spread"
);
assert!(
JobPlan::new(6, 4096)
.with_task_overhead_ns(500)
.optimal_chunk_count_for(8, n)
.is_some(),
"a profile-default cost is still a cost to this method"
);
// Cheap items against a tiny overhead ask for far more chunks
// than there are items; the clamp is what stops it.
let c = JobPlan::new(6, 4096)
.with_estimated_per_item_ns(u32::MAX)
.with_task_overhead_ns(1)
.optimal_chunk_count_for(64, n)
.expect("both hints are set");
assert!(c as usize <= n, "chunk count must clamp at the item count");
}
#[test]
#[cfg(target_pointer_width = "64")]
fn an_item_count_past_the_return_type_saturates_rather_than_wrapping() {
// Zero fixed cost returns the item count itself, which is the
// path a count wider than the return type reaches.
let huge = u32::MAX as usize + 1024;
let p = JobPlan::new(6, 4096)
.with_estimated_per_item_ns(50)
.with_task_overhead_ns(0);
assert_eq!(p.optimal_chunk_count_for(8, huge), Some(u32::MAX));
}
#[test]
fn a_worker_cap_reaches_the_resolved_count() {
let uncapped = JobPlan::new(6, 4096).resolved_workers();
assert!(uncapped >= 1, "a pool is at least one worker wide");
assert_eq!(
JobPlan::new(6, 4096).with_workers(1).resolved_workers(),
1,
"a cap of one is how a caller asks for serial execution"
);
let capped = JobPlan::new(6, 4096).with_workers(2).resolved_workers();
assert_eq!(capped, uncapped.min(2));
}
#[test]
fn the_resolved_count_is_threads_that_run_not_threads_that_exist() {
let arena = crate::sched::arena::global_local_arena();
let primaries = arena.primary_workers();
let total = arena.total_workers();
assert!(primaries <= total);
// Under the default sizing the two are equal, because the
// per-node count is the node's logical threads and no SMT
// extension is spawned when the primaries already cover them.
// The assertions below hold either way; only the last has
// anything to compare when they differ.
assert_eq!(
arena.smt_extension_workers(),
total - primaries,
"the extension is whatever the primaries do not cover"
);
let mut parked = JobPlan::new(6, 4096);
parked.use_smt = false;
assert_eq!(
parked.resolved_workers(),
primaries,
"a plan that leaves the siblings parked is sized to the primaries"
);
assert!(
parked.resolved_workers() <= total,
"the running count can never exceed the threads that exist"
);
// Where the host has siblings, the two counts differ, and a
// plan sized to the wrong one overstates its parallelism.
if total > primaries {
assert!(
parked.resolved_workers() < total,
"sizing a non-SMT plan to {total} threads counts {} parked ones",
total - primaries
);
}
}
}