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
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
//! The exact-Newton joint evaluation methods on the family: GPU flex
//! dispatch, dense/gradient dynamic-q evaluation, time-wiggle and
//! flex-no-wiggle directional derivatives, and the blockwise exact-Newton
//! dispatchers (rigid / per-z / flexible / time-wiggle / mixed / dense /
//! sparse).
use super::*;
impl SurvivalMarginalSlopeFamily {
/// Unified dense joint Hessian assembly for flex and timewiggle paths.
/// Both paths use q-geometry Jacobians via accumulate_dynamic_q_joint_row.
/// The rigid path (no flex, no timewiggle) uses the RowKernel fast path.
/// Owned scratch buffers backing a [`SurvivalFlexGpuRowInputs`]
/// descriptor for one fit-evaluation call.
///
/// Held by-value across the GPU `try_*` entry so the borrowed slices
/// in `as_inputs` live as long as the dispatcher invocation.
pub(crate) fn build_survival_flex_gpu_row_batch(
&self,
block_states: &[ParameterBlockState],
slices: &BlockSlices,
) -> Result<Option<SurvivalFlexGpuRowBatch>, String> {
// Only the scalar-score path is currently representable in
// `SurvivalFlexGpuRowInputs::score_dim == 1`. Vector-score
// and any per-row composition outside the canonical 3-block
// (time, marginal, logslope) layout must take the CPU path.
if self.score_dim() != 1 {
return Ok(None);
}
// The absorbed Stage-1 influence channel (#461) adds a per-row index
// offset `o_infl = Z̃_infl[row,:]·γ` to η₁ that the GPU flex kernel does
// not yet carry (the on-device kernel emits a fixed 4-primary jet). Until
// the survival flex GPU kernel grows the `o_infl` primary coordinate,
// force CPU for absorber-active fits so the device path can never silently
// drop the channel; the CPU path is the source of truth.
if self.influence_absorber.is_some() {
return Ok(None);
}
let n = self.n;
let g_eta: &Array1<f64> = &block_states[2].eta;
if g_eta.len() != n {
return Ok(None);
}
let mut q0 = vec![0.0_f64; n];
let mut q1 = vec![0.0_f64; n];
let mut qd1 = vec![0.0_f64; n];
let mut z = vec![0.0_f64; n];
let mut g = vec![0.0_f64; n];
// Per-row q-values reuse the canonical `row_dynamic_q_values`
// helper so the GPU descriptor sees exactly the same q-geometry
// the CPU per-row primary path consumes (timewiggle-aware when
// active).
for row in 0..n {
let qv = self.row_dynamic_q_values(row, block_states)?;
q0[row] = qv.q0;
q1[row] = qv.q1;
qd1[row] = qv.qd1;
z[row] = self.z[[row, 0]];
g[row] = g_eta[row];
}
let p = slices.total;
// Materialize the joint-β vector in joint-block order. Length
// must equal `p = slices.total` to satisfy the GPU descriptor's
// shape contract; mismatches force CPU fallback.
let mut beta = vec![0.0_f64; p];
// Returns `false` when the block β width does not match its joint
// slice. That invariant (`block_states[i].beta.len() ==
// design_i.ncols() == slice.len()`) holds for every well-formed inner
// state; if it is ever violated the CPU per-row path hard-errors (e.g.
// the `beta.len() != design_derivative_exit.ncols()` check). Silently
// leaving the block as zeros would feed the GPU kernel a corrupted β
// with no error and no fallback, so a mismatch forces CPU instead.
let copy_block =
|dst: &mut [f64], range: &std::ops::Range<usize>, src: &Array1<f64>| -> bool {
if src.len() != range.len() {
return false;
}
if let Some(slice) = src.as_slice() {
dst[range.clone()].copy_from_slice(slice);
} else {
// Non-contiguous Array1 — copy element-wise so the GPU
// descriptor still sees the canonical joint-block β.
for (offset, value) in src.iter().enumerate() {
dst[range.start + offset] = *value;
}
}
true
};
let mut block_widths_match = copy_block(&mut beta, &slices.time, &block_states[0].beta)
&& copy_block(&mut beta, &slices.marginal, &block_states[1].beta)
&& copy_block(&mut beta, &slices.logslope, &block_states[2].beta);
if let Some(range) = slices.score_warp.as_ref() {
block_widths_match =
block_widths_match && copy_block(&mut beta, range, &block_states[3].beta);
}
if let Some(range) = slices.link_dev.as_ref() {
let block_index = 3 + usize::from(self.score_warp.is_some());
block_widths_match =
block_widths_match && copy_block(&mut beta, range, &block_states[block_index].beta);
}
if !block_widths_match {
return Ok(None);
}
Ok(Some(SurvivalFlexGpuRowBatch {
n,
p,
q0,
q1,
qd1,
z,
g,
beta,
weights: self.weights.to_vec(),
event: self.event.to_vec(),
}))
}
/// Step-6 dispatcher for the joint-β gradient. Builds the
/// `SurvivalFlexGpuRowInputs` descriptor, runs the GPU policy
/// `decide`, and routes through
/// [`crate::survival::marginal_slope::gpu::try_survival_flex_gradient`].
///
/// Returns:
///
/// * `Ok(None)` when the GPU path is gated off (policy, shape,
/// backend-not-compiled, or runtime declined) — callers fall back
/// to the existing CPU per-row sweep.
/// * `Ok(Some((nll, grad)))` when the GPU produced a usable answer.
/// * `Err(_)` only when `gpu=force` was requested but the kernel is
/// not supported, mirroring the convention in `gpu::decide`.
pub(crate) fn try_survival_flex_joint_dispatch_gradient(
&self,
block_states: &[ParameterBlockState],
slices: &BlockSlices,
) -> Result<Option<(f64, Array1<f64>)>, String> {
let decision = crate::survival::marginal_slope::gpu::row_primary_hessian_decision(
self.n, N_PRIMARY,
);
decision.clone().log();
if !decision.use_gpu {
decision.require_supported()?;
return Ok(None);
}
let batch = match self.build_survival_flex_gpu_row_batch(block_states, slices)? {
Some(b) => b,
None => {
decision.require_supported()?;
return Ok(None);
}
};
let inputs = batch.as_inputs(self);
match crate::survival::marginal_slope::gpu::try_survival_flex_gradient(
inputs, None, None,
)
.map_err(|e| e.to_string())?
{
Some((nll, grad)) => {
if grad.len() != slices.total {
return Err(format!(
"survival-flex GPU gradient returned len={} but joint p={}",
grad.len(),
slices.total
));
}
Ok(Some((nll, grad)))
}
None => {
decision.require_supported()?;
Ok(None)
}
}
}
/// Step-6 dispatcher for the joint Hessian × vector product. See
/// [`Self::try_survival_flex_joint_dispatch_gradient`] for the
/// `decide`/fallback semantics.
pub(crate) fn try_survival_flex_joint_dispatch_hvp(
&self,
block_states: &[ParameterBlockState],
slices: &BlockSlices,
v: &Array1<f64>,
) -> Result<Option<Array1<f64>>, String> {
let decision = crate::survival::marginal_slope::gpu::row_primary_hessian_decision(
self.n, N_PRIMARY,
);
decision.clone().log();
if !decision.use_gpu {
decision.require_supported()?;
return Ok(None);
}
if v.len() != slices.total {
return Ok(None);
}
let batch = match self.build_survival_flex_gpu_row_batch(block_states, slices)? {
Some(b) => b,
None => {
decision.require_supported()?;
return Ok(None);
}
};
let inputs = batch.as_inputs(self);
let v_slice = v
.as_slice()
.ok_or_else(|| "survival-flex GPU HVP requires contiguous v".to_string())?;
match crate::survival::marginal_slope::gpu::try_survival_flex_hvp(
inputs, v_slice, None,
)
.map_err(|e| e.to_string())?
{
Some(hv) => {
if hv.len() != slices.total {
return Err(format!(
"survival-flex GPU HVP returned len={} but joint p={}",
hv.len(),
slices.total
));
}
Ok(Some(hv))
}
None => {
decision.require_supported()?;
Ok(None)
}
}
}
/// Step-6 dispatcher for the dense joint Hessian. Returns
/// `Ok(Some(H))` on a successful device assembly, `Ok(None)` for the
/// CPU fallback, and `Err(_)` only for `gpu=force` shape mismatches.
pub(crate) fn try_survival_flex_joint_dispatch_dense_hessian(
&self,
block_states: &[ParameterBlockState],
slices: &BlockSlices,
) -> Result<Option<Array2<f64>>, String> {
let decision = crate::survival::marginal_slope::gpu::row_primary_hessian_decision(
self.n, N_PRIMARY,
);
decision.clone().log();
if !decision.use_gpu {
decision.require_supported()?;
return Ok(None);
}
let batch = match self.build_survival_flex_gpu_row_batch(block_states, slices)? {
Some(b) => b,
None => {
decision.require_supported()?;
return Ok(None);
}
};
let inputs = batch.as_inputs(self);
match crate::survival::marginal_slope::gpu::try_survival_flex_dense_hessian(
inputs, None, None,
)
.map_err(|e| e.to_string())?
{
Some(h) => {
let p = slices.total;
if h.shape() != [p, p] {
return Err(format!(
"survival-flex GPU dense H returned shape {:?} but joint p={}",
h.shape(),
p
));
}
Ok(Some(h))
}
None => {
decision.require_supported()?;
Ok(None)
}
}
}
pub(crate) fn evaluate_exact_newton_joint_dynamic_q_dense(
&self,
block_states: &[ParameterBlockState],
) -> Result<(f64, Array1<f64>, Array2<f64>), String> {
let flex_active = self.effective_flex_active(block_states)?;
if flex_active {
self.validate_exact_monotonicity(block_states)?;
}
let slices = block_slices(self, block_states);
// ── Step-6 dispatcher: try GPU dense H + gradient first ──────────
//
// The two `try_survival_flex_joint_dispatch_*` entries route the
// joint-β work through
// [`crate::survival::marginal_slope::gpu::try_survival_flex_dense_hessian`]
// and [`crate::survival::marginal_slope::gpu::try_survival_flex_gradient`]
// respectively, with the standard `gpu::decide` policy.
//
// State of the seam (#1133): the host-side Step-5 primary G/H
// assembly (`try_device_step5_primary_assembly`) and the Step-6
// joint-β pullback (`pullback_step6_joint_beta`) are both LANDED as
// pure host algebra and CPU-verified — Step 5 is already the hot
// per-row path in `compute_row_flex_primary_gradient_hessian_from_parts`
// (the CPU sweep below routes every row through it). What remains is
// ONLY the device substrate: an NVRTC/CUDA kernel that produces the
// per-row jets + folds the Step-6 contraction on-device. Until that
// kernel exists these batch entry points are called with `step6 =
// None` and return `Ok(None)`, so the CPU per-row sweep below is the
// production path. Threading assembled Step-5/Step-6 rows through the
// batch entry points here would only duplicate the already-complete
// per-block pullback in `accumulate_dynamic_q_joint_row` on the host,
// so it is deliberately deferred to the device-kernel work.
if flex_active && !self.flex_timewiggle_active() {
if let Some(h) =
self.try_survival_flex_joint_dispatch_dense_hessian(block_states, &slices)?
{
let (nll, grad) =
match self.try_survival_flex_joint_dispatch_gradient(block_states, &slices)? {
Some(pair) => pair,
None => {
return Err(
"survival-flex GPU dense H succeeded but gradient declined; \
prep dispatchers must compose consistently"
.to_string(),
);
}
};
return Ok((nll, grad, h));
}
}
let primary = flex_primary_slices(self);
let p_total = slices.total;
let identity_blocks = if flex_active {
flex_identity_block_pairs(&primary, &slices)
} else {
vec![]
};
type Acc = (f64, Array1<f64>, Array2<f64>);
// Per-thread accumulator carries a `SurvivalMarginalSlopeDynamicRow`
// workspace alongside the (nll, gradient, hessian) tuple so the nine
// Array2/Array1 buffers inside it are reused across all rows assigned
// to a single rayon worker. At large scale this eliminates the
// ~80 GB-per-sweep allocator traffic the fresh-allocation path used.
type AccWithWs = (Acc, SurvivalMarginalSlopeDynamicRow);
let make_acc = || -> AccWithWs {
(
(
0.0,
Array1::zeros(p_total),
Array2::zeros((p_total, p_total)),
),
SurvivalMarginalSlopeDynamicRow::empty_workspace(),
)
};
let final_acc = (0..self.n)
.into_par_iter()
.try_fold(make_acc, |mut acc, row| -> Result<_, String> {
let (state, q_geom) = &mut acc;
self.row_dynamic_q_geometry_into(row, block_states, q_geom)?;
let (row_nll, f_pi, f_pipi) = if flex_active {
self.compute_row_flex_primary_gradient_hessian_exact(
row,
block_states,
q_geom,
&primary,
)?
} else {
self.compute_row_primary_gradient_hessian_uncached(row, block_states)?
};
state.0 -= row_nll;
self.accumulate_dynamic_q_joint_row(
row,
&slices,
q_geom,
f_pi.view(),
f_pipi.view(),
&identity_blocks,
&mut state.1,
&mut state.2,
)?;
Ok(acc)
})
.try_reduce(make_acc, |mut left, right| -> Result<_, String> {
left.0.0 += right.0.0;
left.0.1 += &right.0.1;
left.0.2 += &right.0.2;
Ok(left)
})?;
Ok(final_acc.0)
}
pub(crate) fn evaluate_exact_newton_joint_dense(
&self,
block_states: &[ParameterBlockState],
) -> Result<(f64, Array1<f64>, Array2<f64>), String> {
if self.effective_flex_active(block_states)? || self.flex_timewiggle_active() {
self.evaluate_exact_newton_joint_dynamic_q_dense(block_states)
} else {
let kern = SurvivalMarginalSlopeRowKernel::new(self.clone(), block_states.to_vec());
let rows = crate::row_kernel::RowSet::All;
let cache = build_row_kernel_cache(&kern, &rows)?;
Ok((
row_kernel_log_likelihood(&cache, &rows),
-row_kernel_gradient(&kern, &cache, &rows),
row_kernel_hessian_dense(&kern, &cache, &rows),
))
}
}
pub(crate) fn evaluate_exact_newton_joint_gradient_dynamic_q(
&self,
block_states: &[ParameterBlockState],
) -> Result<(f64, Array1<f64>), String> {
let flex_active = self.effective_flex_active(block_states)?;
let slices = block_slices(self, block_states);
// ── Step-6 dispatcher: try GPU joint-β gradient first ────────────
//
// Routes through
// [`crate::survival::marginal_slope::gpu::try_survival_flex_gradient`] via
// the `gpu::decide` policy. Returns `Ok(None)` until the device
// CUDA kernel lands: the host-side Step-5 assembly + Step-6 joint-β
// pullback are already LANDED + CPU-verified (Step 5 is the hot
// per-row path), so only the on-device jet/contraction substrate is
// outstanding (#1133). Until then the CPU per-row sweep below is the
// production path and this dispatch is a no-op fast-fail.
if flex_active && !self.flex_timewiggle_active() {
if let Some(pair) =
self.try_survival_flex_joint_dispatch_gradient(block_states, &slices)?
{
return Ok(pair);
}
}
let primary = flex_primary_slices(self);
let identity_blocks = if flex_active {
flex_identity_block_pairs(&primary, &slices)
} else {
vec![]
};
type Acc = (f64, Array1<f64>);
let make_acc = || -> Acc { (0.0, Array1::zeros(slices.total)) };
(0..self.n)
.into_par_iter()
.try_fold(make_acc, |mut acc, row| -> Result<_, String> {
let q_geom = self.row_dynamic_q_gradient(row, block_states)?;
let (row_nll, f_pi) = if flex_active {
self.compute_row_flex_primary_gradient_exact(
row,
block_states,
&q_geom,
&primary,
)?
} else {
let (nll, grad, _) =
self.compute_row_primary_gradient_hessian_uncached(row, block_states)?;
(nll, grad)
};
acc.0 -= row_nll;
self.accumulate_dynamic_q_core_gradient_first_order(
row,
&slices,
&q_geom,
f_pi.slice(s![0..N_PRIMARY]),
&mut acc.1,
)?;
for (primary_range, joint_range) in &identity_blocks {
for local in 0..primary_range.len() {
acc.1[joint_range.start + local] -= f_pi[primary_range.start + local];
}
}
Ok(acc)
})
.try_reduce(make_acc, |mut left, right| -> Result<_, String> {
left.0 += right.0;
left.1 += &right.1;
Ok(left)
})
}
/// Shared per-row pullback of the timewiggle q-map Jacobian/curvature
/// derivatives into the joint Hessian accumulator. Used by both the
/// cached `_inner` path (with an empty `identity_blocks`) and the flex
/// path (with non-empty `identity_blocks`); the only behavioural
/// difference between those callers is whether the identity-block cross
/// terms are added, which is driven entirely by `identity_blocks`.
pub(crate) fn accumulate_timewiggle_directional_row(
&self,
row: usize,
block_states: &[ParameterBlockState],
slices: &BlockSlices,
q_geom: &SurvivalMarginalSlopeDynamicRow,
f_pi: &Array1<f64>,
h_pi: ArrayView2<'_, f64>,
d_time: ndarray::ArrayView1<'_, f64>,
d_marginal: ndarray::ArrayView1<'_, f64>,
beta_time: &Array1<f64>,
beta_time_w: ndarray::ArrayView1<'_, f64>,
identity_blocks: &[(std::ops::Range<usize>, std::ops::Range<usize>)],
acc: &mut Array2<f64>,
) -> Result<(), String> {
let time_tail = self.time_wiggle_range();
let p_base = time_tail.start;
let p_time = slices.time.len();
let p_marginal = slices.marginal.len();
// ── Timewiggle Jacobian derivatives ────────────────
let ec = self
.design_entry
.try_row_chunk(row..row + 1)
.map_err(|e| format!("design_entry try_row_chunk: {e}"))?;
let xc = self
.design_exit
.try_row_chunk(row..row + 1)
.map_err(|e| format!("design_exit try_row_chunk: {e}"))?;
let dc = self
.design_derivative_exit
.try_row_chunk(row..row + 1)
.map_err(|e| format!("design_derivative_exit try_row_chunk: {e}"))?;
let xe = ec.row(0).slice(s![..p_base]).to_owned();
let xx = xc.row(0).slice(s![..p_base]).to_owned();
let xd = dc.row(0).slice(s![..p_base]).to_owned();
let mc = self
.marginal_design
.try_row_chunk(row..row + 1)
.map_err(|e| format!("marginal_design try_row_chunk: {e}"))?;
let mr = mc.row(0).to_owned();
let dh0 = xe.dot(&d_time.slice(s![..p_base])) + mr.dot(&d_marginal);
let dh1 = xx.dot(&d_time.slice(s![..p_base])) + mr.dot(&d_marginal);
let ddr = xd.dot(&d_time.slice(s![..p_base]));
let bm = block_states[1].eta[row];
let h0 = xe.dot(&beta_time.slice(s![..p_base])) + self.offset_entry[row] + bm;
let h1 = xx.dot(&beta_time.slice(s![..p_base])) + self.offset_exit[row] + bm;
let dr = xd.dot(&beta_time.slice(s![..p_base])) + self.derivative_offset_exit[row];
let eg = self
.time_wiggle_geometry(Array1::from_vec(vec![h0]).view(), beta_time_w)?
.ok_or_else(|| "timewiggle geometry missing at entry".to_string())?;
let xg = self
.time_wiggle_geometry(Array1::from_vec(vec![h1]).view(), beta_time_w)?
.ok_or_else(|| "timewiggle geometry missing at exit".to_string())?;
let (m2e, m3e) = (eg.d2q_dq02[0], eg.d3q_dq03[0]);
let (m2x, m3x, m4x) = (xg.d2q_dq02[0], xg.d3q_dq03[0], xg.d4q_dq04[0]);
// dJ_{q,time}[a] / dβ[d]
let mut dj0t = vec![0.0f64; p_time];
let mut dj1t = vec![0.0f64; p_time];
let mut djdt = vec![0.0f64; p_time];
for a in 0..p_base {
dj0t[a] = m2e * dh0 * xe[a];
dj1t[a] = m2x * dh1 * xx[a];
djdt[a] = m3x * dh1 * dr * xx[a] + m2x * ddr * xx[a] + m2x * dh1 * xd[a];
}
for li in 0..time_tail.len() {
let ci = time_tail.start + li;
dj0t[ci] = eg.basis_d1[[0, li]] * dh0;
dj1t[ci] = xg.basis_d1[[0, li]] * dh1;
djdt[ci] = xg.basis_d2[[0, li]] * dh1 * dr + xg.basis_d1[[0, li]] * ddr;
}
let djt = [&dj0t[..], &dj1t[..], &djdt[..]];
let mut dj0m = vec![0.0f64; p_marginal];
let mut dj1m = vec![0.0f64; p_marginal];
let mut djdm = vec![0.0f64; p_marginal];
for a in 0..p_marginal {
dj0m[a] = m2e * dh0 * mr[a];
dj1m[a] = m2x * dh1 * mr[a];
djdm[a] = m3x * dh1 * dr * mr[a] + m2x * ddr * mr[a];
}
let djm = [&dj0m[..], &dj1m[..], &djdm[..]];
let jt: [&Array1<f64>; 3] = [&q_geom.dq0_time, &q_geom.dq1_time, &q_geom.dqd1_time];
let jm: [&Array1<f64>; 3] = [
&q_geom.dq0_marginal,
&q_geom.dq1_marginal,
&q_geom.dqd1_marginal,
];
// Term 2: (dJ/d)^T H J + J^T H (dJ/d)
for a in 0..p_time {
for b in 0..p_time {
let mut v = 0.0;
for qu in 0..3 {
for qv in 0..3 {
v += h_pi[[qu, qv]] * (djt[qu][a] * jt[qv][b] + jt[qu][a] * djt[qv][b]);
}
}
acc[[slices.time.start + a, slices.time.start + b]] += v;
}
}
for a in 0..p_marginal {
for b in 0..p_marginal {
let mut v = 0.0;
for qu in 0..3 {
for qv in 0..3 {
v += h_pi[[qu, qv]] * (djm[qu][a] * jm[qv][b] + jm[qu][a] * djm[qv][b]);
}
}
acc[[slices.marginal.start + a, slices.marginal.start + b]] += v;
}
}
for a in 0..p_time {
for b in 0..p_marginal {
let mut v = 0.0;
for qu in 0..3 {
for qv in 0..3 {
v += h_pi[[qu, qv]] * (djt[qu][a] * jm[qv][b] + jt[qu][a] * djm[qv][b]);
}
}
acc[[slices.time.start + a, slices.marginal.start + b]] += v;
acc[[slices.marginal.start + b, slices.time.start + a]] += v;
}
}
let gc = self
.logslope_design
.try_row_chunk(row..row + 1)
.map_err(|e| format!("logslope_design try_row_chunk: {e}"))?;
let gr = gc.row(0);
for a in 0..p_time {
let mut w = 0.0;
for qu in 0..3 {
w += h_pi[[qu, 3]] * djt[qu][a];
}
for b in 0..slices.logslope.len() {
let v = w * gr[b];
acc[[slices.time.start + a, slices.logslope.start + b]] += v;
acc[[slices.logslope.start + b, slices.time.start + a]] += v;
}
}
for a in 0..p_marginal {
let mut w = 0.0;
for qu in 0..3 {
w += h_pi[[qu, 3]] * djm[qu][a];
}
for b in 0..slices.logslope.len() {
let v = w * gr[b];
acc[[slices.marginal.start + a, slices.logslope.start + b]] += v;
acc[[slices.logslope.start + b, slices.marginal.start + a]] += v;
}
}
for (primary_range, joint_range) in identity_blocks {
for local in 0..primary_range.len() {
let primary_idx = primary_range.start + local;
let joint_idx = joint_range.start + local;
for a in 0..p_time {
let mut value = 0.0;
for qu in 0..3 {
value += h_pi[[qu, primary_idx]] * djt[qu][a];
}
acc[[slices.time.start + a, joint_idx]] += value;
acc[[joint_idx, slices.time.start + a]] += value;
}
for a in 0..p_marginal {
let mut value = 0.0;
for qu in 0..3 {
value += h_pi[[qu, primary_idx]] * djm[qu][a];
}
acc[[slices.marginal.start + a, joint_idx]] += value;
acc[[joint_idx, slices.marginal.start + a]] += value;
}
}
}
// Term 4: Σ_r f_r dK_r/d
for a in 0..p_base {
for b in 0..p_base {
let dk0 = m3e * dh0 * xe[a] * xe[b];
let dk1 = m3x * dh1 * xx[a] * xx[b];
let dkd = m4x * dh1 * dr * xx[a] * xx[b]
+ m3x * ddr * xx[a] * xx[b]
+ m3x * dh1 * (xx[a] * xd[b] + xd[a] * xx[b]);
acc[[slices.time.start + a, slices.time.start + b]] +=
f_pi[0] * dk0 + f_pi[1] * dk1 + f_pi[2] * dkd;
}
}
for li in 0..time_tail.len() {
let ci = time_tail.start + li;
for a in 0..p_base {
let dk0 = eg.basis_d2[[0, li]] * dh0 * xe[a];
let dk1 = xg.basis_d2[[0, li]] * dh1 * xx[a];
let dkd = xg.basis_d3[[0, li]] * dh1 * dr * xx[a]
+ xg.basis_d2[[0, li]] * ddr * xx[a]
+ xg.basis_d2[[0, li]] * dh1 * xd[a];
let v = f_pi[0] * dk0 + f_pi[1] * dk1 + f_pi[2] * dkd;
acc[[slices.time.start + a, slices.time.start + ci]] += v;
acc[[slices.time.start + ci, slices.time.start + a]] += v;
}
}
for a in 0..p_base {
for b in 0..p_marginal {
let dk0 = m3e * dh0 * xe[a] * mr[b];
let dk1 = m3x * dh1 * xx[a] * mr[b];
let dkd = m4x * dh1 * dr * xx[a] * mr[b]
+ m3x * ddr * xx[a] * mr[b]
+ m3x * dh1 * xd[a] * mr[b];
let v = f_pi[0] * dk0 + f_pi[1] * dk1 + f_pi[2] * dkd;
acc[[slices.time.start + a, slices.marginal.start + b]] += v;
acc[[slices.marginal.start + b, slices.time.start + a]] += v;
}
}
for li in 0..time_tail.len() {
let ci = time_tail.start + li;
for b in 0..p_marginal {
let dk0 = eg.basis_d2[[0, li]] * dh0 * mr[b];
let dk1 = xg.basis_d2[[0, li]] * dh1 * mr[b];
let dkd =
xg.basis_d3[[0, li]] * dh1 * dr * mr[b] + xg.basis_d2[[0, li]] * ddr * mr[b];
let v = f_pi[0] * dk0 + f_pi[1] * dk1 + f_pi[2] * dkd;
acc[[slices.time.start + ci, slices.marginal.start + b]] += v;
acc[[slices.marginal.start + b, slices.time.start + ci]] += v;
}
}
for a in 0..p_marginal {
for b in 0..p_marginal {
let dk0 = m3e * dh0 * mr[a] * mr[b];
let dk1 = m3x * dh1 * mr[a] * mr[b];
let dkd = m4x * dh1 * dr * mr[a] * mr[b] + m3x * ddr * mr[a] * mr[b];
acc[[slices.marginal.start + a, slices.marginal.start + b]] +=
f_pi[0] * dk0 + f_pi[1] * dk1 + f_pi[2] * dkd;
}
}
Ok(())
}
/// Exact directional derivative of the joint Hessian for timewiggle-only
/// models (no score-warp / link-deviation). Computes the derivative by
/// differentiating the J^T H J + f·K pullback through the timewiggle
/// q-map geometry (equation 47 of the unified pullback framework).
pub(crate) fn exact_newton_joint_hessian_directional_derivative_timewiggle_inner(
&self,
block_states: &[ParameterBlockState],
d_beta_flat: &Array1<f64>,
cache: Option<&EvalCache>,
) -> Result<Array2<f64>, String> {
let slices = block_slices(self, block_states);
let p_total = slices.total;
let time_tail = self.time_wiggle_range();
let d_time = d_beta_flat.slice(s![slices.time.clone()]);
let d_marginal = d_beta_flat.slice(s![slices.marginal.clone()]);
let beta_time = &block_states[0].beta;
let beta_time_w = beta_time.slice(s![time_tail.clone()]);
let result = (0..self.n)
.into_par_iter()
.try_fold(
|| Array2::<f64>::zeros((p_total, p_total)),
|mut acc, row| -> Result<Array2<f64>, String> {
let q_geom = self.row_dynamic_q_geometry(row, block_states)?;
let primary_owned;
let (f_pi, h_pi) = if let Some(cached) = cache {
self.row_primary_gradient_hessian(row, cached)
} else {
primary_owned =
self.compute_row_primary_gradient_hessian_uncached(row, block_states)?;
(&primary_owned.1, &primary_owned.2)
};
// Inline primary direction from already-computed q_geom
// (avoids redundant row_dynamic_q_geometry call)
let d_logslope = d_beta_flat.slice(s![slices.logslope.clone()]);
let u_d = Array1::from_vec(vec![
q_geom.dq0_time.dot(&d_time) + q_geom.dq0_marginal.dot(&d_marginal),
q_geom.dq1_time.dot(&d_time) + q_geom.dq1_marginal.dot(&d_marginal),
q_geom.dqd1_time.dot(&d_time) + q_geom.dqd1_marginal.dot(&d_marginal),
self.logslope_design.dot_row_view(row, d_logslope),
]);
let t_ud = self.row_primary_third_contracted(row, block_states, u_d.view())?;
let h_ud = h_pi.dot(&u_d);
// Term 1 + 3: reuse core accumulator with (H·u^d, T[u^d])
self.accumulate_dynamic_q_core_hessian(
row,
&slices,
&q_geom,
h_ud.view(),
t_ud.view(),
&mut acc,
)?;
self.accumulate_timewiggle_directional_row(
row,
block_states,
&slices,
&q_geom,
f_pi,
h_pi.view(),
d_time,
d_marginal,
beta_time,
beta_time_w,
&[],
&mut acc,
)?;
Ok(acc)
},
)
.try_reduce(
|| Array2::<f64>::zeros((p_total, p_total)),
|mut a, b| -> Result<_, String> {
a += &b;
Ok(a)
},
)?;
Ok(result)
}
/// Exact directional derivative of the joint Hessian for simultaneous
/// timewiggle + flexible score/link warps.
///
/// This extends the timewiggle-only transport by keeping the full flexible
/// primary Hessian/third contraction live while only differentiating the
/// q-geometry Jacobian and K tensors for the dynamic q coordinates. The
/// score/link primary coordinates remain identity-mapped, so their
/// contribution enters through the shared pullback term plus cross-columns
/// against the dJ correction.
pub(crate) fn exact_newton_joint_hessian_directional_derivative_timewiggle_flex(
&self,
block_states: &[ParameterBlockState],
d_beta_flat: &Array1<f64>,
) -> Result<Array2<f64>, String> {
let slices = block_slices(self, block_states);
let primary = flex_primary_slices(self);
let identity_blocks = flex_identity_block_pairs(&primary, &slices);
let p_total = slices.total;
let time_tail = self.time_wiggle_range();
let d_time = d_beta_flat.slice(s![slices.time.clone()]);
let d_marginal = d_beta_flat.slice(s![slices.marginal.clone()]);
let beta_time = &block_states[0].beta;
let beta_time_w = beta_time.slice(s![time_tail.clone()]);
let result = (0..self.n)
.into_par_iter()
.try_fold(
|| Array2::<f64>::zeros((p_total, p_total)),
|mut acc, row| -> Result<Array2<f64>, String> {
let q_geom = self.row_dynamic_q_geometry(row, block_states)?;
let (_, f_pi, h_pi) = self.compute_row_flex_primary_gradient_hessian_exact(
row,
block_states,
&q_geom,
&primary,
)?;
let u_d = self.row_primary_direction_from_flat_dynamic_with_q_geometry(
row,
block_states,
&slices,
&q_geom,
d_beta_flat,
)?;
let t_ud =
self.row_flex_primary_third_contracted_exact(row, block_states, &u_d)?;
let h_ud = h_pi.dot(&u_d);
self.accumulate_dynamic_q_joint_row(
row,
&slices,
&q_geom,
h_ud.view(),
t_ud.view(),
&identity_blocks,
&mut Array1::zeros(p_total),
&mut acc,
)?;
self.accumulate_timewiggle_directional_row(
row,
block_states,
&slices,
&q_geom,
&f_pi,
h_pi.view(),
d_time,
d_marginal,
beta_time,
beta_time_w,
&identity_blocks,
&mut acc,
)?;
Ok(acc)
},
)
.try_reduce(
|| Array2::<f64>::zeros((p_total, p_total)),
|mut a, b| -> Result<_, String> {
a += &b;
Ok(a)
},
)?;
Ok(result)
}
pub(crate) fn exact_newton_joint_hessian_directional_derivative_timewiggle_cached(
&self,
block_states: &[ParameterBlockState],
d_beta_flat: &Array1<f64>,
cache: &EvalCache,
) -> Result<Array2<f64>, String> {
self.exact_newton_joint_hessian_directional_derivative_timewiggle_inner(
block_states,
d_beta_flat,
Some(cache),
)
}
pub(crate) fn exact_newton_joint_hessian_directional_derivative_timewiggle(
&self,
block_states: &[ParameterBlockState],
d_beta_flat: &Array1<f64>,
) -> Result<Array2<f64>, String> {
self.exact_newton_joint_hessian_directional_derivative_timewiggle_inner(
block_states,
d_beta_flat,
None,
)
}
/// Fully exact second directional derivative D²H[d,e] for timewiggle-only.
/// Differentiates DH[e] along d analytically using m₂–m₅ scalars.
///
/// D²H[d,e] = J^T Ψ J + Σ γ_r K_r
/// + Σ bilinear(W_k, left_k, right_k) for k in {T_e×dJ_d, T_d×dJ_e, H×d²J, H×dJ_d×dJ_e}
/// + dK cross-terms: (Hu_d)·dK_e + (Hu_e)·dK_d + f·d²K
///
/// where Ψ = Q[u_d,u_e] + T[du_e/dd], γ = T_d·u_e + H·du_e/dd.
pub(crate) fn exact_newton_joint_hessiansecond_directional_derivative_timewiggle(
&self,
block_states: &[ParameterBlockState],
d_u: &Array1<f64>,
d_v: &Array1<f64>,
) -> Result<Array2<f64>, String> {
let slices = block_slices(self, block_states);
let p_total = slices.total;
let p_time = slices.time.len();
let p_marginal = slices.marginal.len();
let time_tail = self.time_wiggle_range();
let p_base = time_tail.start;
let du_t = d_u.slice(s![slices.time.clone()]);
let du_m = d_u.slice(s![slices.marginal.clone()]);
let du_g = d_u.slice(s![slices.logslope.clone()]);
let dv_t = d_v.slice(s![slices.time.clone()]);
let dv_m = d_v.slice(s![slices.marginal.clone()]);
let dv_g = d_v.slice(s![slices.logslope.clone()]);
let beta_time = &block_states[0].beta;
let beta_tw = beta_time.slice(s![time_tail.clone()]);
let result = (0..self.n)
.into_par_iter()
.try_fold(
|| Array2::<f64>::zeros((p_total, p_total)),
|mut acc, row| -> Result<Array2<f64>, String> {
let q_geom = self.row_dynamic_q_geometry(row, block_states)?;
let (_, f_pi, h_pi) =
self.compute_row_primary_gradient_hessian_uncached(row, block_states)?;
// Primary directions
let ud = Array1::from_vec(vec![
q_geom.dq0_time.dot(&du_t) + q_geom.dq0_marginal.dot(&du_m),
q_geom.dq1_time.dot(&du_t) + q_geom.dq1_marginal.dot(&du_m),
q_geom.dqd1_time.dot(&du_t) + q_geom.dqd1_marginal.dot(&du_m),
self.logslope_design.dot_row_view(row, du_g),
]);
let ue = Array1::from_vec(vec![
q_geom.dq0_time.dot(&dv_t) + q_geom.dq0_marginal.dot(&dv_m),
q_geom.dq1_time.dot(&dv_t) + q_geom.dq1_marginal.dot(&dv_m),
q_geom.dqd1_time.dot(&dv_t) + q_geom.dqd1_marginal.dot(&dv_m),
self.logslope_design.dot_row_view(row, dv_g),
]);
let t_d = self.row_primary_third_contracted(row, block_states, ud.view())?;
let t_e = self.row_primary_third_contracted(row, block_states, ue.view())?;
let q_de = self.row_primary_fourth_contracted(
row,
block_states,
ud.view(),
ue.view(),
)?;
let h_ud = h_pi.dot(&ud);
let h_ue = h_pi.dot(&ue);
// ── Timewiggle geometry ─────────────────────────────
let ec = self
.design_entry
.try_row_chunk(row..row + 1)
.map_err(|e| format!("design_entry try_row_chunk: {e}"))?;
let xc = self
.design_exit
.try_row_chunk(row..row + 1)
.map_err(|e| format!("design_exit try_row_chunk: {e}"))?;
let dc = self
.design_derivative_exit
.try_row_chunk(row..row + 1)
.map_err(|e| format!("design_derivative_exit try_row_chunk: {e}"))?;
let xe = ec.row(0).slice(s![..p_base]).to_owned();
let xx = xc.row(0).slice(s![..p_base]).to_owned();
let xd = dc.row(0).slice(s![..p_base]).to_owned();
let mc = self
.marginal_design
.try_row_chunk(row..row + 1)
.map_err(|e| format!("marginal_design try_row_chunk: {e}"))?;
let mr = mc.row(0).to_owned();
let bm = block_states[1].eta[row];
let h0 = xe.dot(&beta_time.slice(s![..p_base])) + self.offset_entry[row] + bm;
let h1 = xx.dot(&beta_time.slice(s![..p_base])) + self.offset_exit[row] + bm;
let dr =
xd.dot(&beta_time.slice(s![..p_base])) + self.derivative_offset_exit[row];
let eg = self
.time_wiggle_geometry(Array1::from_vec(vec![h0]).view(), beta_tw)?
.ok_or_else(|| "timewiggle geometry missing".to_string())?;
let xg = self
.time_wiggle_geometry(Array1::from_vec(vec![h1]).view(), beta_tw)?
.ok_or_else(|| "timewiggle geometry missing".to_string())?;
let m2_en = eg.d2q_dq02[0];
let m3_en = eg.d3q_dq03[0];
let m4_en = eg.d4q_dq04[0];
let m2_ex = xg.d2q_dq02[0];
let m3_ex = xg.d3q_dq03[0];
let m4_ex = xg.d4q_dq04[0];
let m5_ex = xg.d5q_dq05[0];
// Direction scalars (h linear in β ⇒ d²h/ded = 0)
let dh0d = xe.dot(&du_t.slice(s![..p_base])) + mr.dot(&du_m);
let dh1d = xx.dot(&du_t.slice(s![..p_base])) + mr.dot(&du_m);
let ddrd = xd.dot(&du_t.slice(s![..p_base]));
let dh0e = xe.dot(&dv_t.slice(s![..p_base])) + mr.dot(&dv_m);
let dh1e = xx.dot(&dv_t.slice(s![..p_base])) + mr.dot(&dv_m);
let ddre = xd.dot(&dv_t.slice(s![..p_base]));
// du_e/dd = (dJ/dd)·e_v — primary direction of e perturbed by d
// dJ[q0,time_a]/dd = m2_en*dh0d*xe[a] for base, basis_d1*dh0d for wiggle
let due_d = {
let mut v = [0.0f64; 4];
for a in 0..p_base {
v[0] += m2_en * dh0d * xe[a] * dv_t[a];
v[1] += m2_ex * dh1d * xx[a] * dv_t[a];
v[2] += (m3_ex * dh1d * dr * xx[a]
+ m2_ex * ddrd * xx[a]
+ m2_ex * dh1d * xd[a])
* dv_t[a];
}
for li in 0..time_tail.len() {
let ci = time_tail.start + li;
v[0] += eg.basis_d1[[0, li]] * dh0d * dv_t[ci];
v[1] += xg.basis_d1[[0, li]] * dh1d * dv_t[ci];
v[2] += (xg.basis_d2[[0, li]] * dh1d * dr
+ xg.basis_d1[[0, li]] * ddrd)
* dv_t[ci];
}
for a in 0..p_marginal {
v[0] += m2_en * dh0d * mr[a] * dv_m[a];
v[1] += m2_ex * dh1d * mr[a] * dv_m[a];
v[2] += (m3_ex * dh1d * dr * mr[a] + m2_ex * ddrd * mr[a]) * dv_m[a];
}
// v[3] = 0 (logslope J is constant)
Array1::from_vec(v.to_vec())
};
// Ψ = Q[ud,ue] + T[due_d]
let t_due =
self.row_primary_third_contracted(row, block_states, due_d.view())?;
let psi = &q_de + &t_due;
// γ = T_d·ue + H·due_d
let gamma = &t_d.dot(&ue) + &h_pi.dot(&due_d);
// ── Term A: J^T Ψ J + γ·K ─────────────────────────
self.accumulate_dynamic_q_core_hessian(
row,
&slices,
&q_geom,
gamma.view(),
psi.view(),
&mut acc,
)?;
let jt = [&q_geom.dq0_time, &q_geom.dq1_time, &q_geom.dqd1_time];
let jm = [
&q_geom.dq0_marginal,
&q_geom.dq1_marginal,
&q_geom.dqd1_marginal,
];
let gc = self
.logslope_design
.try_row_chunk(row..row + 1)
.map_err(|e| format!("logslope_design try_row_chunk: {e}"))?;
let gr = gc.row(0);
// ── Helper: accumulate a symmetrized bilinear term ──
// Adds Σ W[qu,qv] * (left[qu,a]*right[qv,b] + right[qu,a]*left[qv,b])
// for all block pairs into acc.
macro_rules! accum_bilinear {
($w:expr, $lt:expr, $lm:expr, $rt:expr, $rm:expr) => {
for a in 0..p_time {
for b in 0..p_time {
let mut v = 0.0;
for qu in 0..3 {
for qv in 0..3 {
v += $w[[qu, qv]]
* ($lt[qu][a] * $rt[qv][b]
+ $rt[qu][a] * $lt[qv][b]);
}
}
acc[[slices.time.start + a, slices.time.start + b]] += v;
}
}
for a in 0..p_marginal {
for b in 0..p_marginal {
let mut v = 0.0;
for qu in 0..3 {
for qv in 0..3 {
v += $w[[qu, qv]]
* ($lm[qu][a] * $rm[qv][b]
+ $rm[qu][a] * $lm[qv][b]);
}
}
acc[[slices.marginal.start + a, slices.marginal.start + b]] +=
v;
}
}
for a in 0..p_time {
for b in 0..p_marginal {
let mut v = 0.0;
for qu in 0..3 {
for qv in 0..3 {
v += $w[[qu, qv]]
* ($lt[qu][a] * $rm[qv][b]
+ $rt[qu][a] * $lm[qv][b]);
}
}
acc[[slices.time.start + a, slices.marginal.start + b]] += v;
acc[[slices.marginal.start + b, slices.time.start + a]] += v;
}
}
for a in 0..p_time {
let mut w2 = 0.0;
for qu in 0..3 {
w2 += $w[[qu, 3]] * $lt[qu][a];
}
for b in 0..slices.logslope.len() {
let v = w2 * gr[b];
acc[[slices.time.start + a, slices.logslope.start + b]] += v;
acc[[slices.logslope.start + b, slices.time.start + a]] += v;
}
}
for a in 0..p_marginal {
let mut w2 = 0.0;
for qu in 0..3 {
w2 += $w[[qu, 3]] * $lm[qu][a];
}
for b in 0..slices.logslope.len() {
let v = w2 * gr[b];
acc[[slices.marginal.start + a, slices.logslope.start + b]] +=
v;
acc[[slices.logslope.start + b, slices.marginal.start + a]] +=
v;
}
}
};
}
// ── Build dJ arrays for both directions ────────────
// (same code as first directional, for d and e)
type DjArrays = (Vec<f64>, Vec<f64>, Vec<f64>, Vec<f64>, Vec<f64>, Vec<f64>);
let build_dj = |dh0: f64, dh1: f64, ddr_val: f64| -> DjArrays {
let mut j0t = vec![0.0f64; p_time];
let mut j1t = vec![0.0f64; p_time];
let mut jdt = vec![0.0f64; p_time];
for a in 0..p_base {
j0t[a] = m2_en * dh0 * xe[a];
j1t[a] = m2_ex * dh1 * xx[a];
jdt[a] = m3_ex * dh1 * dr * xx[a]
+ m2_ex * ddr_val * xx[a]
+ m2_ex * dh1 * xd[a];
}
for li in 0..time_tail.len() {
let ci = time_tail.start + li;
j0t[ci] = eg.basis_d1[[0, li]] * dh0;
j1t[ci] = xg.basis_d1[[0, li]] * dh1;
jdt[ci] =
xg.basis_d2[[0, li]] * dh1 * dr + xg.basis_d1[[0, li]] * ddr_val;
}
let mut j0m = vec![0.0f64; p_marginal];
let mut j1m = vec![0.0f64; p_marginal];
let mut jdm = vec![0.0f64; p_marginal];
for a in 0..p_marginal {
j0m[a] = m2_en * dh0 * mr[a];
j1m[a] = m2_ex * dh1 * mr[a];
jdm[a] = m3_ex * dh1 * dr * mr[a] + m2_ex * ddr_val * mr[a];
}
(j0t, j1t, jdt, j0m, j1m, jdm)
};
let (djd0t, djd1t, djddt, djd0m, djd1m, djddm) = build_dj(dh0d, dh1d, ddrd);
let djd_t = [&djd0t[..], &djd1t[..], &djddt[..]];
let djd_m = [&djd0m[..], &djd1m[..], &djddm[..]];
let (dje0t, dje1t, djedt, dje0m, dje1m, djedm) = build_dj(dh0e, dh1e, ddre);
let dje_t = [&dje0t[..], &dje1t[..], &djedt[..]];
let dje_m = [&dje0m[..], &dje1m[..], &djedm[..]];
// ── d²J/ded (cross derivative, h linear ⇒ d²h=0) ──
let mut d2j0t = vec![0.0f64; p_time];
let mut d2j1t = vec![0.0f64; p_time];
let mut d2jdt = vec![0.0f64; p_time];
for a in 0..p_base {
d2j0t[a] = m3_en * dh0d * dh0e * xe[a];
d2j1t[a] = m3_ex * dh1d * dh1e * xx[a];
d2jdt[a] = m4_ex * dh1d * dh1e * dr * xx[a]
+ m3_ex * (dh1d * ddre + dh1e * ddrd) * xx[a]
+ m3_ex * dh1d * dh1e * xd[a];
}
for li in 0..time_tail.len() {
let ci = time_tail.start + li;
d2j0t[ci] = eg.basis_d2[[0, li]] * dh0d * dh0e;
d2j1t[ci] = xg.basis_d2[[0, li]] * dh1d * dh1e;
d2jdt[ci] = xg.basis_d3[[0, li]] * dh1d * dh1e * dr
+ xg.basis_d2[[0, li]] * (dh1d * ddre + dh1e * ddrd);
}
let d2j_t = [&d2j0t[..], &d2j1t[..], &d2jdt[..]];
let mut d2j0m = vec![0.0f64; p_marginal];
let mut d2j1m = vec![0.0f64; p_marginal];
let mut d2jdm = vec![0.0f64; p_marginal];
for a in 0..p_marginal {
d2j0m[a] = m3_en * dh0d * dh0e * mr[a];
d2j1m[a] = m3_ex * dh1d * dh1e * mr[a];
d2jdm[a] = m4_ex * dh1d * dh1e * dr * mr[a]
+ m3_ex * (dh1d * ddre + dh1e * ddrd) * mr[a];
}
let d2j_m = [&d2j0m[..], &d2j1m[..], &d2jdm[..]];
let jt_s: [&[f64]; 3] = [
jt[0].as_slice().unwrap(),
jt[1].as_slice().unwrap(),
jt[2].as_slice().unwrap(),
];
let jm_s: [&[f64]; 3] = [
jm[0].as_slice().unwrap(),
jm[1].as_slice().unwrap(),
jm[2].as_slice().unwrap(),
];
// ── Term B: bilinear cross-terms ────────────────────
// (dJ_d)^T T_e J + J^T T_e (dJ_d) — differentiated from Term 1
accum_bilinear!(t_e, djd_t, djd_m, jt_s, jm_s);
// (dJ_e)^T T_d J + J^T T_d (dJ_e) — symmetry partner
accum_bilinear!(t_d, dje_t, dje_m, jt_s, jm_s);
// (d²J)^T H J + J^T H (d²J) — from Term 2
accum_bilinear!(h_pi, d2j_t, d2j_m, jt_s, jm_s);
// (dJ_d)^T H (dJ_e) + (dJ_e)^T H (dJ_d) — from Term 2
accum_bilinear!(h_pi, djd_t, djd_m, dje_t, dje_m);
// ── Term C: dK cross-terms ──────────────────────────
// (H·ud)_r dK_r/de + (H·ue)_r dK_r/dd + f_r d²K_r/ded
//
// dK[q,a,b]/dd = d(K[q,a,b])/dd where K = m_{k}*product-of-design-rows
// d²K[q,a,b]/ded = m_{k+2}*dh_d*dh_e*(...) since d²h/ded=0
//
// For q0 base×base: K = m2_en*xe[a]*xe[b]
// dK/dd = m3_en*dh0d*xe[a]*xe[b]
// d²K/ded = m4_en*dh0d*dh0e*xe[a]*xe[b]
// For q1 base×base: K = m2_ex*xx[a]*xx[b]
// dK/dd = m3_ex*dh1d*xx[a]*xx[b]
// d²K/ded = m4_ex*dh1d*dh1e*xx[a]*xx[b]
// For qd1 base×base: K = m3_ex*dr*xx[a]*xx[b] + m2_ex*(xx[a]*xd[b]+xd[a]*xx[b])
// dK/dd = m4_ex*dh1d*dr*xx[a]*xx[b] + m3_ex*ddrd*xx[a]*xx[b]
// + m3_ex*dh1d*(xx[a]*xd[b]+xd[a]*xx[b])
// d²K/ded = m5_ex*dh1d*dh1e*dr*xx[a]*xx[b]
// + m4_ex*(dh1d*ddre+dh1e*ddrd)*xx[a]*xx[b]
// + m4_ex*dh1d*dh1e*(xx[a]*xd[b]+xd[a]*xx[b])
// base×base time×time
for a in 0..p_base {
for b in 0..p_base {
let dke_0 = m3_en * dh0e * xe[a] * xe[b];
let dke_1 = m3_ex * dh1e * xx[a] * xx[b];
let dke_d = m4_ex * dh1e * dr * xx[a] * xx[b]
+ m3_ex * ddre * xx[a] * xx[b]
+ m3_ex * dh1e * (xx[a] * xd[b] + xd[a] * xx[b]);
let dkd_0 = m3_en * dh0d * xe[a] * xe[b];
let dkd_1 = m3_ex * dh1d * xx[a] * xx[b];
let dkd_d = m4_ex * dh1d * dr * xx[a] * xx[b]
+ m3_ex * ddrd * xx[a] * xx[b]
+ m3_ex * dh1d * (xx[a] * xd[b] + xd[a] * xx[b]);
let d2k_0 = m4_en * dh0d * dh0e * xe[a] * xe[b];
let d2k_1 = m4_ex * dh1d * dh1e * xx[a] * xx[b];
let d2k_d = m5_ex * dh1d * dh1e * dr * xx[a] * xx[b]
+ m4_ex * (dh1d * ddre + dh1e * ddrd) * xx[a] * xx[b]
+ m4_ex * dh1d * dh1e * (xx[a] * xd[b] + xd[a] * xx[b]);
acc[[slices.time.start + a, slices.time.start + b]] += h_ud[0] * dke_0
+ h_ud[1] * dke_1
+ h_ud[2] * dke_d
+ h_ue[0] * dkd_0
+ h_ue[1] * dkd_1
+ h_ue[2] * dkd_d
+ f_pi[0] * d2k_0
+ f_pi[1] * d2k_1
+ f_pi[2] * d2k_d;
}
}
// base×wiggle time×time
for li in 0..time_tail.len() {
let ci = time_tail.start + li;
for a in 0..p_base {
// K[q0] for base×wiggle: d2q0/dβ_base[a] dβ_wiggle[li]
// = basis_d1[li]*xe[a] at entry (m2 * x * basis is wrong; correct is basis_d1*x)
// Actually from q_geom: d2q0_time_time[[a, ci]] = basis_d1_entry[li]*xe[a]
// dK/dd = basis_d2[li]*dh0d*xe[a]
// d²K/ded = basis_d3[li]*dh0d*dh0e*xe[a]
let dke_0 = eg.basis_d2[[0, li]] * dh0e * xe[a];
let dke_1 = xg.basis_d2[[0, li]] * dh1e * xx[a];
let dke_d = xg.basis_d3[[0, li]] * dh1e * dr * xx[a]
+ xg.basis_d2[[0, li]] * ddre * xx[a]
+ xg.basis_d2[[0, li]] * dh1e * xd[a];
let dkd_0 = eg.basis_d2[[0, li]] * dh0d * xe[a];
let dkd_1 = xg.basis_d2[[0, li]] * dh1d * xx[a];
let dkd_d = xg.basis_d3[[0, li]] * dh1d * dr * xx[a]
+ xg.basis_d2[[0, li]] * ddrd * xx[a]
+ xg.basis_d2[[0, li]] * dh1d * xd[a];
let d2k_0 = eg.basis_d3[[0, li]] * dh0d * dh0e * xe[a];
let d2k_1 = xg.basis_d3[[0, li]] * dh1d * dh1e * xx[a];
let d2k_d = xg.basis_d4[[0, li]] * dh1d * dh1e * dr * xx[a]
+ xg.basis_d3[[0, li]] * (dh1d * ddre + dh1e * ddrd) * xx[a]
+ xg.basis_d3[[0, li]] * dh1d * dh1e * xd[a];
let v = h_ud[0] * dke_0
+ h_ud[1] * dke_1
+ h_ud[2] * dke_d
+ h_ue[0] * dkd_0
+ h_ue[1] * dkd_1
+ h_ue[2] * dkd_d
+ f_pi[0] * d2k_0
+ f_pi[1] * d2k_1
+ f_pi[2] * d2k_d;
acc[[slices.time.start + a, slices.time.start + ci]] += v;
acc[[slices.time.start + ci, slices.time.start + a]] += v;
}
}
// base×marginal time×marginal
for a in 0..p_base {
for b in 0..p_marginal {
let dke_0 = m3_en * dh0e * xe[a] * mr[b];
let dke_1 = m3_ex * dh1e * xx[a] * mr[b];
let dke_d = m4_ex * dh1e * dr * xx[a] * mr[b]
+ m3_ex * ddre * xx[a] * mr[b]
+ m3_ex * dh1e * xd[a] * mr[b];
let dkd_0 = m3_en * dh0d * xe[a] * mr[b];
let dkd_1 = m3_ex * dh1d * xx[a] * mr[b];
let dkd_d = m4_ex * dh1d * dr * xx[a] * mr[b]
+ m3_ex * ddrd * xx[a] * mr[b]
+ m3_ex * dh1d * xd[a] * mr[b];
let d2k_0 = m4_en * dh0d * dh0e * xe[a] * mr[b];
let d2k_1 = m4_ex * dh1d * dh1e * xx[a] * mr[b];
let d2k_d = m5_ex * dh1d * dh1e * dr * xx[a] * mr[b]
+ m4_ex * (dh1d * ddre + dh1e * ddrd) * xx[a] * mr[b]
+ m4_ex * dh1d * dh1e * xd[a] * mr[b];
let v = h_ud[0] * dke_0
+ h_ud[1] * dke_1
+ h_ud[2] * dke_d
+ h_ue[0] * dkd_0
+ h_ue[1] * dkd_1
+ h_ue[2] * dkd_d
+ f_pi[0] * d2k_0
+ f_pi[1] * d2k_1
+ f_pi[2] * d2k_d;
acc[[slices.time.start + a, slices.marginal.start + b]] += v;
acc[[slices.marginal.start + b, slices.time.start + a]] += v;
}
}
// wiggle×marginal
for li in 0..time_tail.len() {
let ci = time_tail.start + li;
for b in 0..p_marginal {
let dke_0 = eg.basis_d2[[0, li]] * dh0e * mr[b];
let dke_1 = xg.basis_d2[[0, li]] * dh1e * mr[b];
let dke_d = xg.basis_d3[[0, li]] * dh1e * dr * mr[b]
+ xg.basis_d2[[0, li]] * ddre * mr[b];
let dkd_0 = eg.basis_d2[[0, li]] * dh0d * mr[b];
let dkd_1 = xg.basis_d2[[0, li]] * dh1d * mr[b];
let dkd_d = xg.basis_d3[[0, li]] * dh1d * dr * mr[b]
+ xg.basis_d2[[0, li]] * ddrd * mr[b];
let d2k_0 = eg.basis_d3[[0, li]] * dh0d * dh0e * mr[b];
let d2k_1 = xg.basis_d3[[0, li]] * dh1d * dh1e * mr[b];
let d2k_d = xg.basis_d4[[0, li]] * dh1d * dh1e * dr * mr[b]
+ xg.basis_d3[[0, li]] * (dh1d * ddre + dh1e * ddrd) * mr[b];
let v = h_ud[0] * dke_0
+ h_ud[1] * dke_1
+ h_ud[2] * dke_d
+ h_ue[0] * dkd_0
+ h_ue[1] * dkd_1
+ h_ue[2] * dkd_d
+ f_pi[0] * d2k_0
+ f_pi[1] * d2k_1
+ f_pi[2] * d2k_d;
acc[[slices.time.start + ci, slices.marginal.start + b]] += v;
acc[[slices.marginal.start + b, slices.time.start + ci]] += v;
}
}
// marginal×marginal
for a in 0..p_marginal {
for b in 0..p_marginal {
let dke_0 = m3_en * dh0e * mr[a] * mr[b];
let dke_1 = m3_ex * dh1e * mr[a] * mr[b];
let dke_d =
m4_ex * dh1e * dr * mr[a] * mr[b] + m3_ex * ddre * mr[a] * mr[b];
let dkd_0 = m3_en * dh0d * mr[a] * mr[b];
let dkd_1 = m3_ex * dh1d * mr[a] * mr[b];
let dkd_d =
m4_ex * dh1d * dr * mr[a] * mr[b] + m3_ex * ddrd * mr[a] * mr[b];
let d2k_0 = m4_en * dh0d * dh0e * mr[a] * mr[b];
let d2k_1 = m4_ex * dh1d * dh1e * mr[a] * mr[b];
let d2k_d = m5_ex * dh1d * dh1e * dr * mr[a] * mr[b]
+ m4_ex * (dh1d * ddre + dh1e * ddrd) * mr[a] * mr[b];
acc[[slices.marginal.start + a, slices.marginal.start + b]] += h_ud[0]
* dke_0
+ h_ud[1] * dke_1
+ h_ud[2] * dke_d
+ h_ue[0] * dkd_0
+ h_ue[1] * dkd_1
+ h_ue[2] * dkd_d
+ f_pi[0] * d2k_0
+ f_pi[1] * d2k_1
+ f_pi[2] * d2k_d;
}
}
Ok(acc)
},
)
.try_reduce(
|| Array2::<f64>::zeros((p_total, p_total)),
|mut a, b| -> Result<_, String> {
a += &b;
Ok(a)
},
)?;
Ok(result)
}
/// Exact first directional derivative for flex without timewiggle.
/// J is constant (no wiggle), so DH[d] = J^T T[u^d] J + Σ (Hu^d)_r K_r.
/// Scatter one row's directional-derivative primary quantities
/// (`primary_gradient` = directional change of the primary gradient, i.e.
/// `H_primary · u`; `primary_hessian` = directional change of the primary
/// Hessian) through the q-geometry / identity-block pullback into the joint
/// `acc`. This is the per-row inner body shared by both the
/// first-directional (`t_ud`, `h_ud`) and second-directional (`q_de`,
/// `gamma`) flex-no-wiggle paths, and by the batched all-axes Jeffreys
/// override — so the three callers cannot drift.
pub(crate) fn accumulate_directional_joint_hessian_row(
&self,
row: usize,
slices: &BlockSlices,
q_geom: &SurvivalMarginalSlopeDynamicRow,
identity_blocks: &[(std::ops::Range<usize>, std::ops::Range<usize>)],
primary_gradient: ndarray::ArrayView1<'_, f64>,
primary_hessian: ndarray::ArrayView2<'_, f64>,
acc: &mut Array2<f64>,
) -> Result<(), String> {
// Core q-geometry pullback (Hessian only)
self.accumulate_dynamic_q_core_hessian(
row,
slices,
q_geom,
primary_gradient,
primary_hessian,
acc,
)?;
// Identity block Hessian: cross + diagonal + cross-cross
for (primary_range, joint_range) in identity_blocks {
for local in 0..primary_range.len() {
self.accumulate_identity_primary_cross_hessian(
row,
slices,
q_geom,
primary_hessian.slice(s![0..N_PRIMARY, primary_range.start + local]),
joint_range,
local,
acc,
)?;
}
self.add_dense_submatrix(
acc,
joint_range,
joint_range,
primary_hessian.slice(s![primary_range.clone(), primary_range.clone()]),
);
}
for li in 0..identity_blocks.len() {
for ri in li + 1..identity_blocks.len() {
let (lp, lj) = &identity_blocks[li];
let (rp, rj) = &identity_blocks[ri];
self.add_dense_symmetric_cross_submatrix(
acc,
lj,
rj,
primary_hessian.slice(s![lp.clone(), rp.clone()]),
);
}
}
Ok(())
}
pub(crate) fn exact_newton_joint_hessian_directional_derivative_flex_no_wiggle(
&self,
block_states: &[ParameterBlockState],
d_beta_flat: &Array1<f64>,
) -> Result<Array2<f64>, String> {
let slices = block_slices(self, block_states);
let primary = flex_primary_slices(self);
let p_total = slices.total;
let identity_blocks = flex_identity_block_pairs(&primary, &slices);
let result = (0..self.n)
.into_par_iter()
.try_fold(
|| Array2::<f64>::zeros((p_total, p_total)),
|mut acc, row| -> Result<Array2<f64>, String> {
let q_geom = self.row_dynamic_q_geometry(row, block_states)?;
let h_pi = self
.compute_row_flex_primary_gradient_hessian_exact(
row,
block_states,
&q_geom,
&primary,
)?
.2;
let u_d = self.row_primary_direction_from_flat_dynamic_with_q_geometry(
row,
block_states,
&slices,
&q_geom,
d_beta_flat,
)?;
let t_ud =
self.row_flex_primary_third_contracted_exact(row, block_states, &u_d)?;
let h_ud = h_pi.dot(&u_d);
self.accumulate_directional_joint_hessian_row(
row,
&slices,
&q_geom,
&identity_blocks,
h_ud.view(),
t_ud.view(),
&mut acc,
)?;
Ok(acc)
},
)
.try_reduce(
|| Array2::<f64>::zeros((p_total, p_total)),
|mut a, b| -> Result<_, String> {
a += &b;
Ok(a)
},
)?;
Ok(result)
}
/// Build-once all-axes variant of
/// [`Self::exact_newton_joint_hessian_directional_derivative_flex_no_wiggle`].
///
/// The Jeffreys all-axes sweep needs the directional joint-Hessian for each
/// of the `p` coordinate axes. Calling the single-direction routine `p`
/// times rebuilds, per row and per axis, the direction-independent flex
/// geometry (`q`-geometry, primary Hessian, intercept solves, cached
/// partitions, exact base timepoints) — a `p`-fold redundant cost that is
/// the #979 flex marginal-slope hot path. This variant builds that geometry
/// once per row (`FlexThirdRowBase` + the primary Hessian) and contracts it
/// against each axis, so only the per-axis directional pieces are repeated.
/// Each output matrix routes through the same per-row assemblers as the
/// corresponding single-axis call (`row_flex_third_contract_from_base` +
/// `accumulate_directional_joint_hessian_row`), so it equals that call up to
/// the cross-row rayon reduction order.
pub(crate) fn exact_newton_joint_hessian_directional_derivative_flex_no_wiggle_all_axes(
&self,
block_states: &[ParameterBlockState],
) -> Result<Vec<Array2<f64>>, String> {
let slices = block_slices(self, block_states);
let primary = flex_primary_slices(self);
let p_total = slices.total;
let identity_blocks = flex_identity_block_pairs(&primary, &slices);
let zeros = || vec![Array2::<f64>::zeros((p_total, p_total)); p_total];
let result = (0..self.n)
.into_par_iter()
.try_fold(zeros, |mut acc, row| -> Result<Vec<Array2<f64>>, String> {
// Direction-independent per-row geometry, built once.
let q_geom = self.row_dynamic_q_geometry(row, block_states)?;
let h_pi = self
.compute_row_flex_primary_gradient_hessian_exact(
row,
block_states,
&q_geom,
&primary,
)?
.2;
let base =
self.build_row_flex_third_base_with_states(row, block_states, &primary)?;
// Per-axis: only the primary-direction pullback, the third
// contraction against it, and the row accumulation are repeated.
for axis_idx in 0..p_total {
let mut axis = Array1::<f64>::zeros(p_total);
axis[axis_idx] = 1.0;
let u_d = self.row_primary_direction_from_flat_dynamic_with_q_geometry(
row,
block_states,
&slices,
&q_geom,
&axis,
)?;
let t_ud = self.row_flex_third_contract_from_base(&base, &u_d)?;
let h_ud = h_pi.dot(&u_d);
self.accumulate_directional_joint_hessian_row(
row,
&slices,
&q_geom,
&identity_blocks,
h_ud.view(),
t_ud.view(),
&mut acc[axis_idx],
)?;
}
Ok(acc)
})
.try_reduce(zeros, |mut a, b| -> Result<_, String> {
for (ai, bi) in a.iter_mut().zip(b.into_iter()) {
*ai += &bi;
}
Ok(a)
})?;
Ok(result)
}
/// Exact second directional derivative for flex without timewiggle.
/// J constant ⇒ D²H[d,e] = J^T Q[u^d,u^e] J + Σ (T_d·u^e)_r K_r.
pub(crate) fn exact_newton_joint_hessiansecond_directional_derivative_flex_no_wiggle(
&self,
block_states: &[ParameterBlockState],
d_u: &Array1<f64>,
d_v: &Array1<f64>,
) -> Result<Array2<f64>, String> {
let slices = block_slices(self, block_states);
let primary = flex_primary_slices(self);
let p_total = slices.total;
let identity_blocks = flex_identity_block_pairs(&primary, &slices);
let result = (0..self.n)
.into_par_iter()
.try_fold(
|| Array2::<f64>::zeros((p_total, p_total)),
|mut acc, row| -> Result<Array2<f64>, String> {
let q_geom = self.row_dynamic_q_geometry(row, block_states)?;
let ud = self.row_primary_direction_from_flat_dynamic_with_q_geometry(
row,
block_states,
&slices,
&q_geom,
d_u,
)?;
let ue = self.row_primary_direction_from_flat_dynamic_with_q_geometry(
row,
block_states,
&slices,
&q_geom,
d_v,
)?;
let q_de =
self.row_flex_primary_fourth_contracted_exact(row, block_states, &ud, &ue)?;
let t_d =
self.row_flex_primary_third_contracted_exact(row, block_states, &ud)?;
let gamma = t_d.dot(&ue);
// Hessian-only: accumulate q-core + identity block Hessian
self.accumulate_directional_joint_hessian_row(
row,
&slices,
&q_geom,
&identity_blocks,
gamma.view(),
q_de.view(),
&mut acc,
)?;
Ok(acc)
},
)
.try_reduce(
|| Array2::<f64>::zeros((p_total, p_total)),
|mut a, b| -> Result<_, String> {
a += &b;
Ok(a)
},
)?;
Ok(result)
}
pub(crate) fn evaluate_blockwise_exact_newton(
&self,
block_states: &[ParameterBlockState],
) -> Result<FamilyEvaluation, String> {
if self.per_z_logslope_active() {
return self.evaluate_blockwise_exact_newton_per_z(block_states);
}
if self.effective_flex_active(block_states)? {
return self.evaluate_blockwise_exact_newton_flexible(block_states);
}
if self.flex_timewiggle_active() {
return self.evaluate_blockwise_exact_newton_timewiggle(block_states);
}
// For all non-flex, non-timewiggle modes: use the dense joint path
// when p is small enough. This guarantees block Hessians are
// principal blocks of the joint Hessian regardless of whether the
// underlying designs happen to be sparse.
let slices = block_slices(self, block_states);
if slices.total < 512 {
return self.evaluate_blockwise_exact_newton_dense(block_states);
}
// Large p (>= 512): joint dense Hessian is too expensive.
// Fall back to blockwise sparse/mixed assembly for memory efficiency.
let time_csrs = match (
self.design_entry.as_sparse(),
self.design_exit.as_sparse(),
self.design_derivative_exit.as_sparse(),
) {
(Some(e), Some(x), Some(d)) => Some((
e.to_csr_arc().expect("entry CSR"),
x.to_csr_arc().expect("exit CSR"),
d.to_csr_arc().expect("deriv CSR"),
)),
_ => None,
};
let marginal_csr = self
.marginal_design
.as_sparse()
.and_then(|s| s.to_csr_arc());
let logslope_csr = self
.logslope_design
.as_sparse()
.and_then(|s| s.to_csr_arc());
let time_sparse = time_csrs.is_some();
let marginal_sparse = marginal_csr.is_some();
let logslope_sparse = logslope_csr.is_some();
if time_sparse && marginal_sparse && logslope_sparse {
self.evaluate_blockwise_exact_newton_sparse(
block_states,
&time_csrs.unwrap(),
&marginal_csr.unwrap(),
&logslope_csr.unwrap(),
)
} else if !time_sparse && !marginal_sparse && !logslope_sparse {
self.evaluate_blockwise_exact_newton_dense(block_states)
} else {
self.evaluate_blockwise_exact_newton_mixed(
block_states,
time_csrs.as_ref(),
marginal_csr.as_ref(),
logslope_csr.as_ref(),
)
}
}
pub(crate) fn evaluate_blockwise_exact_newton_per_z(
&self,
block_states: &[ParameterBlockState],
) -> Result<FamilyEvaluation, String> {
if self.effective_flex_active(block_states)? || self.flex_timewiggle_active() {
return Err(
"survival marginal-slope per-z logslope surfaces currently require the rigid row kernel"
.to_string(),
);
}
let slices = block_slices(self, block_states);
let p_t = slices.time.len();
let p_m = slices.marginal.len();
let p_g = slices.logslope.len();
let beta_time = &block_states[0].beta;
let beta_logslope = &block_states[2].beta;
let probit_scale = self.probit_frailty_scale();
type PerZBlockAcc = (
f64,
Array1<f64>,
Array1<f64>,
Array1<f64>,
Array2<f64>,
Array2<f64>,
Array2<f64>,
);
let (ll, grad_t, grad_m, grad_g, hess_t, hess_m, hess_g): PerZBlockAcc = (0..self.n)
.into_par_iter()
.try_fold(
|| {
(
0.0,
Array1::<f64>::zeros(p_t),
Array1::<f64>::zeros(p_m),
Array1::<f64>::zeros(p_g),
Array2::<f64>::zeros((p_t, p_t)),
Array2::<f64>::zeros((p_m, p_m)),
Array2::<f64>::zeros((p_g, p_g)),
)
},
|mut acc, row| -> Result<_, String> {
let q0 = self.design_entry.dot_row(row, beta_time)
+ self.offset_entry[row]
+ block_states[1].eta[row];
let q1 = self.design_exit.dot_row(row, beta_time)
+ self.offset_exit[row]
+ block_states[1].eta[row];
let qd1 = self.design_derivative_exit.dot_row(row, beta_time)
+ self.derivative_offset_exit[row];
let slopes = self.logslope_surface_values_for_row(row, beta_logslope)?;
let z = self.z.row(row).to_vec();
let (nll, f_pi, f_pipi) = row_primary_closed_form_vector(
q0,
q1,
qd1,
&slopes,
&z,
&self.score_covariance,
self.weights[row],
self.event[row],
self.derivative_guard,
probit_scale,
)?;
acc.0 -= nll;
self.design_entry
.axpy_row_into(row, -f_pi[0], &mut acc.1.view_mut())?;
self.design_exit
.axpy_row_into(row, -f_pi[1], &mut acc.1.view_mut())?;
self.design_derivative_exit.axpy_row_into(
row,
-f_pi[2],
&mut acc.1.view_mut(),
)?;
self.marginal_design.axpy_row_into(
row,
-(f_pi[0] + f_pi[1]),
&mut acc.2.view_mut(),
)?;
let g_row = self.logslope_surface_row(row)?;
for (coord, range) in self.logslope_surface_ranges.iter().enumerate() {
let alpha = -f_pi[3 + coord];
for col in range.clone() {
acc.3[col] += alpha * g_row[col];
}
}
let time_designs = [
&self.design_entry,
&self.design_exit,
&self.design_derivative_exit,
];
for a in 0..3 {
for b in 0..3 {
time_designs[a].row_outer_into(
row,
time_designs[b],
f_pipi[[a, b]],
&mut acc.4,
)?;
}
}
let alpha_mm =
f_pipi[[0, 0]] + f_pipi[[0, 1]] + f_pipi[[1, 0]] + f_pipi[[1, 1]];
self.marginal_design
.syr_row_into(row, alpha_mm, &mut acc.5)?;
for (a, range_a) in self.logslope_surface_ranges.iter().enumerate() {
for (b, range_b) in self.logslope_surface_ranges.iter().enumerate() {
let alpha = f_pipi[[3 + a, 3 + b]];
if alpha == 0.0 {
continue;
}
for ca in range_a.clone() {
let va = g_row[ca] * alpha;
for cb in range_b.clone() {
acc.6[[ca, cb]] += va * g_row[cb];
}
}
}
}
Ok(acc)
},
)
.try_reduce(
|| {
(
0.0,
Array1::<f64>::zeros(p_t),
Array1::<f64>::zeros(p_m),
Array1::<f64>::zeros(p_g),
Array2::<f64>::zeros((p_t, p_t)),
Array2::<f64>::zeros((p_m, p_m)),
Array2::<f64>::zeros((p_g, p_g)),
)
},
|mut a, b| -> Result<_, String> {
a.0 += b.0;
a.1 += &b.1;
a.2 += &b.2;
a.3 += &b.3;
a.4 += &b.4;
a.5 += &b.5;
a.6 += &b.6;
Ok(a)
},
)?;
Ok(FamilyEvaluation {
log_likelihood: ll,
blockworking_sets: vec![
BlockWorkingSet::ExactNewton {
gradient: grad_t,
hessian: SymmetricMatrix::Dense(hess_t),
},
BlockWorkingSet::ExactNewton {
gradient: grad_m,
hessian: SymmetricMatrix::Dense(hess_m),
},
BlockWorkingSet::ExactNewton {
gradient: grad_g,
hessian: SymmetricMatrix::Dense(hess_g),
},
],
})
}
pub(crate) fn evaluate_exact_newton_joint_dense_per_z(
&self,
block_states: &[ParameterBlockState],
) -> Result<(f64, Array1<f64>, Array2<f64>), String> {
let slices = block_slices(self, block_states);
let total = slices.total;
let k = self.score_dim();
let dim = 3 + k;
let beta_time = &block_states[0].beta;
let beta_logslope = &block_states[2].beta;
let probit_scale = self.probit_frailty_scale();
type PerZJointAcc = (f64, Array1<f64>, Array2<f64>);
let (ll, grad, hess): PerZJointAcc = (0..self.n)
.into_par_iter()
.try_fold(
|| {
(
0.0,
Array1::<f64>::zeros(total),
Array2::<f64>::zeros((total, total)),
)
},
|mut acc, row| -> Result<_, String> {
let q0 = self.design_entry.dot_row(row, beta_time)
+ self.offset_entry[row]
+ block_states[1].eta[row];
let q1 = self.design_exit.dot_row(row, beta_time)
+ self.offset_exit[row]
+ block_states[1].eta[row];
let qd1 = self.design_derivative_exit.dot_row(row, beta_time)
+ self.derivative_offset_exit[row];
let slopes = self.logslope_surface_values_for_row(row, beta_logslope)?;
let z = self.z.row(row).to_vec();
let (nll, f_pi, f_pipi) = row_primary_closed_form_vector(
q0,
q1,
qd1,
&slopes,
&z,
&self.score_covariance,
self.weights[row],
self.event[row],
self.derivative_guard,
probit_scale,
)?;
acc.0 -= nll;
let mut j = Array2::<f64>::zeros((dim, total));
let entry = self.design_entry.try_row_chunk(row..row + 1).map_err(|e| {
format!("evaluate_exact_newton_joint_dense_per_z entry row: {e}")
})?;
let exit = self.design_exit.try_row_chunk(row..row + 1).map_err(|e| {
format!("evaluate_exact_newton_joint_dense_per_z exit row: {e}")
})?;
let deriv = self
.design_derivative_exit
.try_row_chunk(row..row + 1)
.map_err(|e| {
format!("evaluate_exact_newton_joint_dense_per_z derivative row: {e}")
})?;
let marginal =
self.marginal_design
.try_row_chunk(row..row + 1)
.map_err(|e| {
format!("evaluate_exact_newton_joint_dense_per_z marginal row: {e}")
})?;
j.slice_mut(s![0, slices.time.clone()])
.assign(&entry.row(0));
j.slice_mut(s![1, slices.time.clone()]).assign(&exit.row(0));
j.slice_mut(s![2, slices.time.clone()])
.assign(&deriv.row(0));
j.slice_mut(s![0, slices.marginal.clone()])
.assign(&marginal.row(0));
j.slice_mut(s![1, slices.marginal.clone()])
.assign(&marginal.row(0));
let g_row = self.logslope_surface_row(row)?;
for (coord, range) in self.logslope_surface_ranges.iter().enumerate() {
let global_range = (slices.logslope.start + range.start)
..(slices.logslope.start + range.end);
j.slice_mut(s![3 + coord, global_range])
.assign(&g_row.slice(s![range.clone()]));
}
for a in 0..dim {
for col in 0..total {
acc.1[col] -= f_pi[a] * j[[a, col]];
}
}
for a in 0..dim {
for b in 0..dim {
let alpha = f_pipi[[a, b]];
if alpha == 0.0 {
continue;
}
for ca in 0..total {
let va = j[[a, ca]] * alpha;
if va == 0.0 {
continue;
}
for cb in 0..total {
acc.2[[ca, cb]] += va * j[[b, cb]];
}
}
}
}
Ok(acc)
},
)
.try_reduce(
|| {
(
0.0,
Array1::<f64>::zeros(total),
Array2::<f64>::zeros((total, total)),
)
},
|mut a, b| -> Result<_, String> {
a.0 += b.0;
a.1 += &b.1;
a.2 += &b.2;
Ok(a)
},
)?;
Ok((ll, grad, hess))
}
/// Blockwise exact-Newton for the flexible (score-warp / link-deviation)
/// model.
///
/// Accumulates exact per-block coefficient gradients and Hessians directly
/// from the dynamic-q row jets. This preserves the exact block Newton
/// update while avoiding dense full-joint assembly when the caller only
/// needs block-local working sets.
pub(crate) fn evaluate_blockwise_exact_newton_flexible(
&self,
block_states: &[ParameterBlockState],
) -> Result<FamilyEvaluation, String> {
self.validate_exact_monotonicity(block_states)?;
let primary = flex_primary_slices(self);
self.evaluate_blockwise_exact_newton_dynamic_q(block_states, &primary, |row, q_geom| {
self.compute_row_flex_primary_gradient_hessian_exact(
row,
block_states,
q_geom,
&primary,
)
})
}
/// Blockwise exact-Newton for the time-wiggle model.
///
/// Accumulates exact block-local Hessians directly from the 4D primary
/// row calculus instead of materializing and slicing a dense joint Hessian.
pub(crate) fn evaluate_blockwise_exact_newton_timewiggle(
&self,
block_states: &[ParameterBlockState],
) -> Result<FamilyEvaluation, String> {
let primary = flex_primary_slices(self);
self.evaluate_blockwise_exact_newton_dynamic_q(block_states, &primary, |row, _| {
self.compute_row_primary_gradient_hessian_uncached(row, block_states)
})
}
pub(crate) fn evaluate_blockwise_exact_newton_mixed(
&self,
block_states: &[ParameterBlockState],
time_csrs: Option<&(
Arc<faer::sparse::SparseRowMat<usize, f64>>,
Arc<faer::sparse::SparseRowMat<usize, f64>>,
Arc<faer::sparse::SparseRowMat<usize, f64>>,
)>,
marginal_csr: Option<&Arc<faer::sparse::SparseRowMat<usize, f64>>>,
logslope_csr: Option<&Arc<faer::sparse::SparseRowMat<usize, f64>>>,
) -> Result<FamilyEvaluation, String> {
use gam_linalg::matrix::SparseHessianAccumulator;
enum BlockwiseHessianAccumulator {
Dense(Array2<f64>),
Sparse(SparseHessianAccumulator),
}
impl BlockwiseHessianAccumulator {
fn add_assign(&mut self, other: &Self) {
match (self, other) {
(Self::Dense(lhs), Self::Dense(rhs)) => *lhs += rhs,
(Self::Sparse(lhs), Self::Sparse(rhs)) => lhs.add_values(&rhs.values),
// Per-block accumulators all share one storage decision
// (marginal_csr / logslope_csr) made at the top of
// `family_evaluate_blockwise`.
// SAFETY: mismatch ⇒ a newly added partial picked the
// wrong storage variant — invariant violation. Zeroing the
// accumulator would silently corrupt the joint Hessian, so
// fail loudly instead of fabricating a result.
_ => panic!("blockwise Hessian accumulator kind mismatch"),
}
}
fn into_symmetric(self) -> SymmetricMatrix {
match self {
Self::Dense(mat) => SymmetricMatrix::Dense(mat),
Self::Sparse(acc) => SymmetricMatrix::Sparse(acc.into_sparse_col_mat()),
}
}
}
let slices = block_slices(self, block_states);
let p_t = slices.time.len();
let p_m = slices.marginal.len();
let p_g = slices.logslope.len();
let time_pattern = time_csrs.map(|(entry, exit, deriv)| {
SparseHessianAccumulator::from_multi_csr(
&[entry.as_ref(), exit.as_ref(), deriv.as_ref()],
p_t,
)
});
let marginal_pattern =
marginal_csr.map(|csr| SparseHessianAccumulator::from_single_csr(csr.as_ref(), p_m));
let logslope_pattern =
logslope_csr.map(|csr| SparseHessianAccumulator::from_single_csr(csr.as_ref(), p_g));
let e_sparse = time_csrs.map(|(entry, _, _)| {
let sym = entry.symbolic();
(sym.row_ptr(), sym.col_idx(), entry.val())
});
let x_sparse = time_csrs.map(|(_, exit, _)| {
let sym = exit.symbolic();
(sym.row_ptr(), sym.col_idx(), exit.val())
});
let d_sparse = time_csrs.map(|(_, _, deriv)| {
let sym = deriv.symbolic();
(sym.row_ptr(), sym.col_idx(), deriv.val())
});
let m_sparse = marginal_csr.map(|csr| {
let sym = csr.symbolic();
(sym.row_ptr(), sym.col_idx(), csr.val())
});
let g_sparse = logslope_csr.map(|csr| {
let sym = csr.symbolic();
(sym.row_ptr(), sym.col_idx(), csr.val())
});
type MixedAcc = (
f64,
Array1<f64>,
Array1<f64>,
Array1<f64>,
BlockwiseHessianAccumulator,
BlockwiseHessianAccumulator,
BlockwiseHessianAccumulator,
);
let make_acc = || -> MixedAcc {
(
0.0,
Array1::zeros(p_t),
Array1::zeros(p_m),
Array1::zeros(p_g),
time_pattern.as_ref().map_or_else(
|| BlockwiseHessianAccumulator::Dense(Array2::zeros((p_t, p_t))),
|pattern| BlockwiseHessianAccumulator::Sparse(pattern.empty_clone()),
),
marginal_pattern.as_ref().map_or_else(
|| BlockwiseHessianAccumulator::Dense(Array2::zeros((p_m, p_m))),
|pattern| BlockwiseHessianAccumulator::Sparse(pattern.empty_clone()),
),
logslope_pattern.as_ref().map_or_else(
|| BlockwiseHessianAccumulator::Dense(Array2::zeros((p_g, p_g))),
|pattern| BlockwiseHessianAccumulator::Sparse(pattern.empty_clone()),
),
)
};
let (
ll,
grad_time,
grad_marginal,
grad_logslope,
hess_time,
hess_marginal,
hess_logslope,
): MixedAcc = (0..self.n)
.into_par_iter()
.try_fold(make_acc, |mut acc, row| -> Result<_, String> {
let (row_nll, f_pi, f_pipi) =
self.compute_row_primary_gradient_hessian_uncached(row, block_states)?;
acc.0 -= row_nll;
match &e_sparse {
Some((e_rp, e_ci, e_v)) => {
let gt = &mut acc.1;
for p in e_rp[row]..e_rp[row + 1] {
gt[e_ci[p]] -= f_pi[0] * e_v[p];
}
let (x_rp, x_ci, x_v) = x_sparse
.as_ref()
.expect("time sparse metadata should be present for exit design");
for p in x_rp[row]..x_rp[row + 1] {
gt[x_ci[p]] -= f_pi[1] * x_v[p];
}
let (d_rp, d_ci, d_v) = d_sparse.as_ref().expect(
"time sparse metadata should be present for derivative design",
);
for p in d_rp[row]..d_rp[row + 1] {
gt[d_ci[p]] -= f_pi[2] * d_v[p];
}
}
None => {
let mut time = acc.1.view_mut();
self.design_entry
.axpy_row_into(row, -f_pi[0], &mut time)
.expect("time entry axpy dim mismatch");
self.design_exit
.axpy_row_into(row, -f_pi[1], &mut time)
.expect("time exit axpy dim mismatch");
self.design_derivative_exit
.axpy_row_into(row, -f_pi[2], &mut time)
.expect("time deriv axpy dim mismatch");
}
}
match &m_sparse {
Some((m_rp, m_ci, m_v)) => {
let gm = &mut acc.2;
let alpha_m = -(f_pi[0] + f_pi[1]);
for p in m_rp[row]..m_rp[row + 1] {
gm[m_ci[p]] += alpha_m * m_v[p];
}
}
None => {
self.marginal_design
.axpy_row_into(row, -(f_pi[0] + f_pi[1]), &mut acc.2.view_mut())
.expect(
"survival marginal block axpy should match block dimensions",
);
}
}
match &g_sparse {
Some((g_rp, g_ci, g_v)) => {
let gg = &mut acc.3;
for p in g_rp[row]..g_rp[row + 1] {
gg[g_ci[p]] -= f_pi[3] * g_v[p];
}
}
None => {
self.logslope_design
.axpy_row_into(row, -f_pi[3], &mut acc.3.view_mut())
.expect(
"survival logslope block axpy should match block dimensions",
);
}
}
match &mut acc.4 {
BlockwiseHessianAccumulator::Dense(hess_time) => {
let designs = [
&self.design_entry,
&self.design_exit,
&self.design_derivative_exit,
];
for a in 0..3 {
for b in 0..3 {
designs[a]
.row_outer_into(
row,
designs[b],
f_pipi[[a, b]],
&mut *hess_time,
)
.expect("time row_outer_into dim mismatch");
}
}
}
BlockwiseHessianAccumulator::Sparse(hess_time) => {
let (e_rp, e_ci, e_v) = e_sparse
.as_ref()
.expect("time sparse metadata should be present for entry design");
let (x_rp, x_ci, x_v) = x_sparse
.as_ref()
.expect("time sparse metadata should be present for exit design");
let (d_rp, d_ci, d_v) = d_sparse.as_ref().expect(
"time sparse metadata should be present for derivative design",
);
let row_slices: [(std::ops::Range<usize>, &[usize], &[f64]); 3] = [
(e_rp[row]..e_rp[row + 1], e_ci, e_v),
(x_rp[row]..x_rp[row + 1], x_ci, x_v),
(d_rp[row]..d_rp[row + 1], d_ci, d_v),
];
for a in 0..3 {
for b in 0..3 {
let alpha = f_pipi[[a, b]];
if alpha == 0.0 {
continue;
}
let (ref ra, cia, va) = row_slices[a];
let (ref rb, cib, vb) = row_slices[b];
for pi in ra.clone() {
let ca = cia[pi];
let xia = va[pi] * alpha;
for pj in rb.clone() {
let cb = cib[pj];
if ca <= cb {
hess_time.add_upper(ca, cb, xia * vb[pj]);
}
}
}
}
}
}
}
let alpha_m = f_pipi[[0, 0]] + f_pipi[[0, 1]] + f_pipi[[1, 0]] + f_pipi[[1, 1]];
match &mut acc.5 {
BlockwiseHessianAccumulator::Dense(hess_marginal) => {
self.marginal_design
.syr_row_into(row, alpha_m, &mut *hess_marginal)
.expect(
"survival marginal block syr should match block dimensions",
);
}
BlockwiseHessianAccumulator::Sparse(hess_marginal) => {
if alpha_m != 0.0 {
let (m_rp, m_ci, m_v) = m_sparse.as_ref().expect(
"marginal sparse metadata should be present for sparse block",
);
for pi in m_rp[row]..m_rp[row + 1] {
let ca = m_ci[pi];
let xia = m_v[pi] * alpha_m;
for pj in m_rp[row]..m_rp[row + 1] {
let cb = m_ci[pj];
if ca <= cb {
hess_marginal.add_upper(ca, cb, xia * m_v[pj]);
}
}
}
}
}
}
let alpha_g = f_pipi[[3, 3]];
match &mut acc.6 {
BlockwiseHessianAccumulator::Dense(hess_logslope) => {
self.logslope_design
.syr_row_into(row, alpha_g, &mut *hess_logslope)
.expect(
"survival logslope block syr should match block dimensions",
);
}
BlockwiseHessianAccumulator::Sparse(hess_logslope) => {
if alpha_g != 0.0 {
let (g_rp, g_ci, g_v) = g_sparse.as_ref().expect(
"logslope sparse metadata should be present for sparse block",
);
for pi in g_rp[row]..g_rp[row + 1] {
let ca = g_ci[pi];
let xia = g_v[pi] * alpha_g;
for pj in g_rp[row]..g_rp[row + 1] {
let cb = g_ci[pj];
if ca <= cb {
hess_logslope.add_upper(ca, cb, xia * g_v[pj]);
}
}
}
}
}
}
Ok(acc)
})
.try_reduce(make_acc, |mut a, b| -> Result<_, String> {
a.0 += b.0;
a.1 += &b.1;
a.2 += &b.2;
a.3 += &b.3;
a.4.add_assign(&b.4);
a.5.add_assign(&b.5);
a.6.add_assign(&b.6);
Ok(a)
})?;
Ok(FamilyEvaluation {
log_likelihood: ll,
blockworking_sets: {
let slices = block_slices(self, block_states);
let mut sets = vec![
BlockWorkingSet::ExactNewton {
gradient: grad_time,
hessian: hess_time.into_symmetric(),
},
BlockWorkingSet::ExactNewton {
gradient: grad_marginal,
hessian: hess_marginal.into_symmetric(),
},
BlockWorkingSet::ExactNewton {
gradient: grad_logslope,
hessian: hess_logslope.into_symmetric(),
},
];
if let Some(range) = slices.score_warp.as_ref() {
sets.push(BlockWorkingSet::ExactNewton {
gradient: Array1::zeros(range.len()),
hessian: SymmetricMatrix::Dense(Array2::zeros((range.len(), range.len()))),
});
}
if let Some(range) = slices.link_dev.as_ref() {
sets.push(BlockWorkingSet::ExactNewton {
gradient: Array1::zeros(range.len()),
hessian: SymmetricMatrix::Dense(Array2::zeros((range.len(), range.len()))),
});
}
sets
},
})
}
// ── Dense path (original) ────────────────────────────────────────
pub(crate) fn evaluate_blockwise_exact_newton_dense(
&self,
block_states: &[ParameterBlockState],
) -> Result<FamilyEvaluation, String> {
// Build RowKernel — the single source of truth for all exact-Newton
// quantities. The cache evaluates every row kernel once and stores
// (nll_i, g_i[4], H_i[4×4]).
let kern = SurvivalMarginalSlopeRowKernel::new(self.clone(), block_states.to_vec());
let rows = crate::row_kernel::RowSet::All;
let cache = build_row_kernel_cache(&kern, &rows)?;
let ll = row_kernel_log_likelihood(&cache, &rows);
// Joint gradient: g = -Σ_i Jᵢᵀ gᵢ (sign: gᵢ are NLL gradients,
// we negate to get log-likelihood gradient).
let nll_grad = row_kernel_gradient(&kern, &cache, &rows);
let joint_gradient = -nll_grad;
// Block-diagonal Hessians only — the inner solver consumes per-block
// working sets, so we accumulate the principal time-time, m-m, and
// g-g blocks directly instead of building the full joint Hessian and
// slicing. Cost falls from Θ(n·(p_t+p_m+p_g)²) to
// Θ(n·(p_t²+p_m²+p_g²)).
let slices = block_slices(self, block_states);
let p_t = slices.time.len();
let p_m = slices.marginal.len();
let p_g = slices.logslope.len();
let mut hess_time = Array2::<f64>::zeros((p_t, p_t));
let mut hess_marginal = Array2::<f64>::zeros((p_m, p_m));
let mut hess_logslope = Array2::<f64>::zeros((p_g, p_g));
for row in 0..cache.n {
let h = &cache.hessians[row];
let mut h_arr = Array2::<f64>::zeros((4, 4));
for a in 0..4 {
for b in 0..4 {
h_arr[[a, b]] = h[a][b];
}
}
self.add_pullback_block_diagonals(
row,
&h_arr,
&mut hess_time,
&mut hess_marginal,
&mut hess_logslope,
);
}
let mut blockworking_sets = vec![
BlockWorkingSet::ExactNewton {
gradient: joint_gradient.slice(s![slices.time.clone()]).to_owned(),
hessian: SymmetricMatrix::Dense(hess_time),
},
BlockWorkingSet::ExactNewton {
gradient: joint_gradient.slice(s![slices.marginal.clone()]).to_owned(),
hessian: SymmetricMatrix::Dense(hess_marginal),
},
BlockWorkingSet::ExactNewton {
gradient: joint_gradient.slice(s![slices.logslope.clone()]).to_owned(),
hessian: SymmetricMatrix::Dense(hess_logslope),
},
];
if let Some(range) = slices.score_warp.as_ref() {
// The 4-D row kernel does not span score_warp / link_dev primary
// dimensions, so these blocks contribute zero gradient/Hessian
// here — exactly what the joint-then-slice path produced.
blockworking_sets.push(BlockWorkingSet::ExactNewton {
gradient: joint_gradient.slice(s![range.clone()]).to_owned(),
hessian: SymmetricMatrix::Dense(Array2::zeros((range.len(), range.len()))),
});
}
if let Some(range) = slices.link_dev.as_ref() {
blockworking_sets.push(BlockWorkingSet::ExactNewton {
gradient: joint_gradient.slice(s![range.clone()]).to_owned(),
hessian: SymmetricMatrix::Dense(Array2::zeros((range.len(), range.len()))),
});
}
Ok(FamilyEvaluation {
log_likelihood: ll,
blockworking_sets,
})
}
// ── Sparse path ──────────────────────────────────────────────────
pub(crate) fn evaluate_blockwise_exact_newton_sparse(
&self,
block_states: &[ParameterBlockState],
time_csrs: &(
Arc<faer::sparse::SparseRowMat<usize, f64>>,
Arc<faer::sparse::SparseRowMat<usize, f64>>,
Arc<faer::sparse::SparseRowMat<usize, f64>>,
),
marginal_csr: &Arc<faer::sparse::SparseRowMat<usize, f64>>,
logslope_csr: &Arc<faer::sparse::SparseRowMat<usize, f64>>,
) -> Result<FamilyEvaluation, String> {
use gam_linalg::matrix::SparseHessianAccumulator;
let slices = block_slices(self, block_states);
let p_t = slices.time.len();
let p_m = slices.marginal.len();
let p_g = slices.logslope.len();
let (ref csr_entry, ref csr_exit, ref csr_deriv) = *time_csrs;
// Build symbolic sparsity patterns once.
let pattern_time = SparseHessianAccumulator::from_multi_csr(
&[csr_entry.as_ref(), csr_exit.as_ref(), csr_deriv.as_ref()],
p_t,
);
let pattern_marginal =
SparseHessianAccumulator::from_single_csr(marginal_csr.as_ref(), p_m);
let pattern_logslope =
SparseHessianAccumulator::from_single_csr(logslope_csr.as_ref(), p_g);
// Pre-extract CSR symbolic parts for zero-overhead inner loop access.
let e_sym = csr_entry.symbolic();
let e_rp = e_sym.row_ptr();
let e_ci = e_sym.col_idx();
let e_v = csr_entry.val();
let x_sym = csr_exit.symbolic();
let x_rp = x_sym.row_ptr();
let x_ci = x_sym.col_idx();
let x_v = csr_exit.val();
let d_sym = csr_deriv.symbolic();
let d_rp = d_sym.row_ptr();
let d_ci = d_sym.col_idx();
let d_v = csr_deriv.val();
let m_sym = marginal_csr.symbolic();
let m_rp = m_sym.row_ptr();
let m_ci = m_sym.col_idx();
let m_v = marginal_csr.val();
let g_sym = logslope_csr.symbolic();
let g_rp = g_sym.row_ptr();
let g_ci = g_sym.col_idx();
let g_v = logslope_csr.val();
// Accumulator type: gradients dense, Hessians sparse value buffers.
type SAcc = (
f64,
Array1<f64>,
Array1<f64>,
Array1<f64>,
SparseHessianAccumulator,
SparseHessianAccumulator,
SparseHessianAccumulator,
);
let make_acc = || -> SAcc {
(
0.0,
Array1::zeros(p_t),
Array1::zeros(p_m),
Array1::zeros(p_g),
pattern_time.empty_clone(),
pattern_marginal.empty_clone(),
pattern_logslope.empty_clone(),
)
};
let (
ll,
grad_time,
grad_marginal,
grad_logslope,
acc_time,
acc_marginal,
acc_logslope,
): SAcc = (0..self.n)
.into_par_iter()
.try_fold(make_acc, |mut acc, row| -> Result<_, String> {
let (row_nll, f_pi, f_pipi) =
self.compute_row_primary_gradient_hessian_uncached(row, block_states)?;
acc.0 -= row_nll;
// ── gradients (dense axpy via CSR scatter) ────────────
{
let gt = &mut acc.1;
for p in e_rp[row]..e_rp[row + 1] {
gt[e_ci[p]] -= f_pi[0] * e_v[p];
}
for p in x_rp[row]..x_rp[row + 1] {
gt[x_ci[p]] -= f_pi[1] * x_v[p];
}
for p in d_rp[row]..d_rp[row + 1] {
gt[d_ci[p]] -= f_pi[2] * d_v[p];
}
}
{
let gm = &mut acc.2;
let alpha_m = -(f_pi[0] + f_pi[1]);
for p in m_rp[row]..m_rp[row + 1] {
gm[m_ci[p]] += alpha_m * m_v[p];
}
}
{
let gg = &mut acc.3;
for p in g_rp[row]..g_rp[row + 1] {
gg[g_ci[p]] -= f_pi[3] * g_v[p];
}
}
// ── time Hessian: 3×3 cross-product scatter ──────────
// Only emit upper-triangle entries (ca <= cb) to avoid
// double-counting: SymmetricMatrix::Sparse mirrors the
// upper triangle into the lower.
let row_slices: [(std::ops::Range<usize>, &[usize], &[f64]); 3] = [
(e_rp[row]..e_rp[row + 1], e_ci, e_v),
(x_rp[row]..x_rp[row + 1], x_ci, x_v),
(d_rp[row]..d_rp[row + 1], d_ci, d_v),
];
let ht = &mut acc.4;
for a in 0..3 {
for b in 0..3 {
let alpha = f_pipi[[a, b]];
if alpha == 0.0 {
continue;
}
let (ref ra, cia, va) = row_slices[a];
let (ref rb, cib, vb) = row_slices[b];
for pi in ra.clone() {
let ca = cia[pi];
let xia = va[pi] * alpha;
for pj in rb.clone() {
let cb = cib[pj];
if ca <= cb {
ht.add_upper(ca, cb, xia * vb[pj]);
}
}
}
}
}
// ── marginal Hessian: symmetric rank-1 scatter ───────
let alpha_m = f_pipi[[0, 0]] + f_pipi[[0, 1]] + f_pipi[[1, 0]] + f_pipi[[1, 1]];
if alpha_m != 0.0 {
let hm = &mut acc.5;
let m_start = m_rp[row];
let m_end = m_rp[row + 1];
for pi in m_start..m_end {
let ca = m_ci[pi];
let xia = m_v[pi] * alpha_m;
for pj in m_start..m_end {
let cb = m_ci[pj];
if ca <= cb {
hm.add_upper(ca, cb, xia * m_v[pj]);
}
}
}
}
// ── logslope Hessian: symmetric rank-1 scatter ───────
let alpha_g = f_pipi[[3, 3]];
if alpha_g != 0.0 {
let hg = &mut acc.6;
let g_start = g_rp[row];
let g_end = g_rp[row + 1];
for pi in g_start..g_end {
let ca = g_ci[pi];
let xia = g_v[pi] * alpha_g;
for pj in g_start..g_end {
let cb = g_ci[pj];
if ca <= cb {
hg.add_upper(ca, cb, xia * g_v[pj]);
}
}
}
}
Ok(acc)
})
.try_reduce(make_acc, |mut a, b| -> Result<_, String> {
a.0 += b.0;
a.1 += &b.1;
a.2 += &b.2;
a.3 += &b.3;
a.4.add_values(&b.4.values);
a.5.add_values(&b.5.values);
a.6.add_values(&b.6.values);
Ok(a)
})?;
Ok(FamilyEvaluation {
log_likelihood: ll,
blockworking_sets: {
let slices = block_slices(self, block_states);
let mut sets = vec![
BlockWorkingSet::ExactNewton {
gradient: grad_time,
hessian: SymmetricMatrix::Sparse(acc_time.into_sparse_col_mat()),
},
BlockWorkingSet::ExactNewton {
gradient: grad_marginal,
hessian: SymmetricMatrix::Sparse(acc_marginal.into_sparse_col_mat()),
},
BlockWorkingSet::ExactNewton {
gradient: grad_logslope,
hessian: SymmetricMatrix::Sparse(acc_logslope.into_sparse_col_mat()),
},
];
if let Some(range) = slices.score_warp.as_ref() {
sets.push(BlockWorkingSet::ExactNewton {
gradient: Array1::zeros(range.len()),
hessian: SymmetricMatrix::Dense(Array2::zeros((range.len(), range.len()))),
});
}
if let Some(range) = slices.link_dev.as_ref() {
sets.push(BlockWorkingSet::ExactNewton {
gradient: Array1::zeros(range.len()),
hessian: SymmetricMatrix::Dense(Array2::zeros((range.len(), range.len()))),
});
}
sets
},
})
}
}
// ── CustomFamily impl ─────────────────────────────────────────────────
pub(crate) fn time_wiggle_basis_ncols(knots: &Array1<f64>, degree: usize) -> Result<usize, String> {
if knots.is_empty() {
return Err(SurvivalMarginalSlopeError::InvalidInput {
reason: "survival-marginal-slope timewiggle requires at least one knot".to_string(),
}
.into());
}
let probe = 0.5 * (knots[0] + knots[knots.len() - 1]);
let h0 = Array1::from_vec(vec![probe]);
Ok(monotone_wiggle_basis_with_derivative_order(h0.view(), knots, degree, 0)?.ncols())
}
pub(crate) fn smgs_deleted_required_channel_reason(
p_time: usize,
p_marginal: usize,
p_logslope: usize,
w_time: usize,
w_marginal: usize,
w_logslope: usize,
) -> Option<&'static str> {
if p_time > 0 && w_time == 0 {
Some("time")
} else if p_marginal > 0 && w_marginal == 0 {
Some("marginal")
} else if p_logslope > 0 && w_logslope == 0 {
Some("logslope")
} else {
None
}
}