File size: 87,836 Bytes
473c56f
1e96696
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
473c56f
 
 
 
1e96696
 
 
d819a00
473c56f
1e96696
 
473c56f
 
b427dc5
1e96696
473c56f
 
 
dfb4695
473c56f
 
 
d819a00
473c56f
 
d819a00
 
 
 
 
 
 
 
 
 
 
473c56f
 
 
 
1e96696
 
473c56f
 
 
1e96696
473c56f
 
1e96696
473c56f
1e96696
473c56f
1e96696
 
473c56f
 
 
b427dc5
473c56f
1e96696
 
473c56f
 
 
 
 
 
 
 
 
 
 
1e96696
473c56f
 
 
 
1e96696
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d819a00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b427dc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e96696
 
 
 
 
 
 
 
 
 
473c56f
 
 
 
 
 
1e96696
473c56f
 
 
 
 
 
 
 
0c0dba2
 
1e96696
 
 
0c0dba2
d819a00
0c0dba2
d819a00
1e96696
 
0c0dba2
 
 
 
1e96696
 
d819a00
1e96696
 
 
 
 
 
 
 
 
 
 
0c0dba2
 
 
 
 
 
 
 
 
 
 
1e96696
 
 
 
0c0dba2
 
 
 
 
 
 
 
 
 
 
 
 
 
1e96696
0c0dba2
1e96696
0c0dba2
 
 
 
1e96696
 
0c0dba2
1e96696
 
 
0c0dba2
 
 
 
d819a00
 
1e96696
 
 
 
d819a00
1e96696
 
 
 
 
 
 
d819a00
 
 
 
 
 
 
 
 
 
 
 
 
 
1e96696
 
 
 
 
 
 
 
 
 
 
d819a00
 
1e96696
 
d819a00
1e96696
d819a00
1e96696
 
d819a00
 
1e96696
 
 
d819a00
1e96696
d819a00
1e96696
 
b427dc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
473c56f
 
 
 
 
 
1e96696
 
 
 
 
 
 
 
 
 
473c56f
 
1e96696
 
 
 
 
 
 
 
d819a00
b427dc5
 
1e96696
 
 
 
 
 
d819a00
1e96696
 
d819a00
 
 
 
 
 
 
1e96696
 
 
d819a00
 
 
 
 
 
 
 
 
 
 
1e96696
 
 
 
 
 
 
 
 
 
 
 
 
 
473c56f
1e96696
473c56f
 
1e96696
 
 
 
473c56f
1e96696
473c56f
 
 
1e96696
 
 
 
 
 
473c56f
1e96696
473c56f
1e96696
473c56f
 
 
1e96696
 
 
 
 
 
 
 
 
 
 
 
473c56f
1e96696
 
 
 
473c56f
1e96696
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c0dba2
1e96696
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c0dba2
1e96696
0c0dba2
b427dc5
 
1e96696
 
0c0dba2
 
b427dc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e96696
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d819a00
 
b427dc5
 
d819a00
 
 
 
 
b427dc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d819a00
 
b427dc5
 
d819a00
 
 
b427dc5
 
 
 
 
d819a00
 
 
 
 
b427dc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d819a00
 
1e96696
 
 
 
 
 
 
 
d819a00
1e96696
 
 
 
 
 
 
 
 
 
 
 
 
 
b427dc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e96696
 
 
 
 
b427dc5
 
d819a00
b427dc5
 
1e96696
d819a00
1e96696
b427dc5
d819a00
 
 
 
 
b427dc5
 
1e96696
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d819a00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b427dc5
0c0dba2
1e96696
0c0dba2
 
 
1e96696
 
 
 
 
 
b427dc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e96696
0c0dba2
1e96696
0c0dba2
d819a00
 
 
 
1e96696
0c0dba2
 
1e96696
0c0dba2
1e96696
0c0dba2
1e96696
b427dc5
1e96696
 
d819a00
0c0dba2
d819a00
 
1e96696
d819a00
1e96696
 
 
 
b427dc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e96696
 
 
 
 
b427dc5
 
 
 
 
 
 
 
1e96696
 
 
 
 
 
0c0dba2
 
 
b427dc5
0c0dba2
 
 
1e96696
0c0dba2
 
1e96696
 
0c0dba2
1e96696
d819a00
1e96696
 
 
 
 
d819a00
1e96696
 
 
b427dc5
 
 
 
 
 
 
1e96696
 
 
d819a00
1e96696
 
 
b427dc5
1e96696
 
 
 
 
 
 
 
 
 
b427dc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e96696
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b427dc5
 
 
 
 
1e96696
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b427dc5
 
1e96696
 
 
 
b427dc5
 
1e96696
 
 
b427dc5
1e96696
 
 
 
 
 
b427dc5
 
 
 
1e96696
 
b427dc5
 
 
 
 
1e96696
 
 
 
 
 
 
b427dc5
 
 
 
1e96696
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b427dc5
 
1e96696
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b427dc5
 
1e96696
 
 
 
 
 
 
 
 
 
 
d819a00
 
b427dc5
 
1e96696
0c0dba2
473c56f
 
 
 
1e96696
 
 
473c56f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e96696
 
473c56f
 
 
 
1e96696
 
 
 
473c56f
 
 
 
 
 
 
1e96696
 
473c56f
 
 
1e96696
 
473c56f
 
 
 
1e96696
 
 
 
 
d819a00
 
1e96696
 
473c56f
1e96696
 
 
 
 
 
473c56f
 
 
 
1e96696
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b427dc5
1e96696
 
b427dc5
d819a00
 
1e96696
473c56f
d819a00
 
473c56f
 
 
 
 
 
 
 
dfb4695
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
473c56f
dfb4695
473c56f
0c0dba2
 
 
 
 
1e96696
0c0dba2
 
 
473c56f
 
1e96696
 
 
 
 
473c56f
1e96696
 
473c56f
 
d819a00
 
1e96696
 
 
 
 
 
473c56f
d819a00
 
473c56f
 
 
 
 
 
1e96696
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
473c56f
 
1e96696
473c56f
 
 
 
 
1e96696
 
 
 
473c56f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b427dc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
473c56f
 
1e96696
473c56f
 
 
 
b427dc5
 
 
1e96696
b427dc5
dfb4695
 
473c56f
b427dc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
473c56f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b427dc5
 
 
 
 
 
 
 
473c56f
 
 
1e96696
 
 
 
 
 
 
b427dc5
 
1e96696
473c56f
 
 
 
 
 
1e96696
 
 
 
473c56f
1e96696
 
 
 
473c56f
1e96696
 
473c56f
 
1e96696
 
473c56f
 
1e96696
 
473c56f
 
 
1e96696
 
473c56f
 
 
 
1e96696
473c56f
 
 
 
 
1e96696
473c56f
 
 
 
 
 
 
 
 
 
1e96696
 
 
473c56f
 
1e96696
b427dc5
473c56f
 
 
 
 
 
1e96696
 
473c56f
 
 
 
 
 
 
1e96696
 
 
 
 
 
 
 
473c56f
 
 
 
 
 
1e96696
473c56f
 
 
b427dc5
 
1e96696
 
b427dc5
 
473c56f
 
 
b427dc5
 
1e96696
 
b427dc5
 
473c56f
 
 
 
1e96696
 
473c56f
1e96696
 
 
473c56f
 
1e96696
473c56f
 
b427dc5
 
 
 
 
 
 
 
 
473c56f
 
 
 
 
 
dfb4695
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
473c56f
1e96696
473c56f
 
 
 
 
0c0dba2
1e96696
 
 
 
 
 
 
 
 
473c56f
1e96696
 
 
 
 
 
 
 
 
 
 
 
 
 
473c56f
 
 
 
 
 
 
 
 
dfb4695
473c56f
 
 
 
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
#!/usr/bin/env python
"""EAGLE runner for the packaged cascade (fastcascade v2, SHIP model U_PAIR_2c) — protocol v1.

Built on fastcascade_v2 (FastEngineV2) for lossless acceleration on both consumer GPUs (8-16 GB,
with --low_vram) and cluster GPUs:
  * fastcascade_v2 lossless levers: forked worker processes over a shared memory arena for
    per-candidate features and crops (threads fallback on Windows), off-critical-path parallel
    patient context (ctx_par), T1 base model overlapped under candidate extraction, overlapped
    nnU-Net exports, exact_fast (integer-exact centroids, argmax-free probability export,
    content-memoised binary_fill_holes), threaded + memoised resampling, single input decode,
    cached classifier heads, and GPU fp32 crop CNNs with load-time batch pre-warming.
  * consumer-GPU low-VRAM mode (--low_vram / $EAGLE_LOW_VRAM=1, tested under a 7 GB cap):
      - stage-wise GPU residency using read-only pinned CPU shadow weights (zero D2H offload,
        non-blocking DMA H2D: ~80 ms vs ~1.9 s per stage switch);
      - pinned CPU state-dict swaps for the 4 base seeds (~0.45 s vs ~1.18 s, zero extra VRAM);
      - D331 deep-feature accumulators on CPU with reusable pinned D2H staging buffers;
      - streams disabled below 32 GB effective VRAM so concurrent activation workspaces never OOM.
  * batch pipelining (enabled by default for --cases and queued --serve requests; --no_pipeline
    to disable): prefetches case n+1's CPU inputs + preprocessing while case n runs its final
    GPU drawers / compose / write (isolated per-case state, identical per-case outputs).
  * opt-in TF32 (--tf32 / $EAGLE_TF32=1): OFF by default (not bit-exact).
  * single case (--t1 --flair --out_dir), batch (--cases --out), or resident server (--serve
    SOCKET, JSON-lines protocol v1 unchanged).
"""
from __future__ import annotations

import argparse
import concurrent.futures as cf
import contextlib
import copy
import gc
import json
import mmap
import multiprocessing as mp
import os
import queue
import secrets
import shutil
import signal
import socket
import sys
import tempfile
import threading
import time
import traceback
import types
from pathlib import Path

# Frozen research modules (e.g. cascade2_common) import fcntl at module level; provide a
# harmless stub on Windows so runtime/code stays byte-identical to the frozen tree.
if os.name != "posix" and "fcntl" not in sys.modules:
    _fcntl_stub = types.ModuleType("fcntl")
    _fcntl_stub.LOCK_SH = 1
    _fcntl_stub.LOCK_EX = 2
    _fcntl_stub.LOCK_NB = 4
    _fcntl_stub.LOCK_UN = 8
    _fcntl_stub.flock = lambda _fd, _op: None
    sys.modules["fcntl"] = _fcntl_stub

HERE = Path(__file__).resolve().parent
BUNDLE = None
if (HERE / "bundle_boot.py").is_file() or "--bundle" in " ".join(sys.argv) or os.environ.get("EAGLE_UPAIR_BUNDLE"):
    sys.path.insert(0, str(HERE))
    _dwb, sys.dont_write_bytecode = sys.dont_write_bytecode, True
    import bundle_boot as _BB  # noqa: E402
    sys.dont_write_bytecode = _dwb
    _bd = _BB.bundle_dir_from(sys.argv)
    if _bd is None and (HERE / "bundle_boot.py").is_file() and (HERE.parent / "bundle.json").is_file():
        _bd = str(HERE.parent)
    if _bd is not None:
        BUNDLE = _BB.use_bundle(_bd)

FC = Path(os.environ.get("FASTCASCADE_DIR", HERE.parent / "packaging" / "fastcascade"))
FC2 = FC.parent / "fastcascade_v2"
sys.path.insert(0, str(FC))
if FC2.is_dir():
    sys.path.insert(0, str(FC2))
import run_fast as RF  # noqa: E402  (stdlib-only at import time)

PROTOCOL = 1
RUNNER_VERSION = "eagle_runner 2.3 (2026-11-28, fastcascade_v2, disk-backed low-RAM/low-VRAM, Windows TCP/WSL, sklearn compat)"
GATE_NAMES = {"s1": "seed-1", "s2": "seed-2", "m6": "mean-6", "all": "main"}
STAGE_FRAC = {"inputs": 0.0, "prep": 0.02, "heat": 0.06, "d331": 0.22, "c2t": 0.24, "cands": 0.26, "base": 0.68,
              "draw": 0.74, "compose": 0.96}
STAGE_MSG = {"inputs": "reading images", "prep": "preparing the T1", "heat": "FLAIR detector (6 networks)",
             "d331": "T1 feature network", "c2t": "evidence network", "cands": "candidate classifier",
             "base": "T1 base model (4 networks)", "draw": "outlining accepted candidates (4 drawer networks)",
             "compose": "combining base model and outlines"}


class Cancelled(Exception):
    pass


class _Ctx:
    progress = None
    cancel: threading.Event | None = None


CTX = _Ctx()
OPTS: dict[str, object] = {
    "model_version": "U_PAIR_2c",
    "idle_exit": 0.0,
    "low_vram": False,
    "tf32": False,
    "fast_v1": False,
    "pipeline": True,
    "no_cnn_gpu": False,
    "feat_procs": None,
    "verify_v2": False,
    "verify_every": 0,
    "no_cnn_prewarm": False,
}


def _env_flag(name: str) -> bool:
    return os.environ.get(name, "").strip().lower() in ("1", "true", "yes", "on")


def _env_opt_bool(name: str) -> bool | None:
    raw = os.environ.get(name, "").strip().lower()
    if raw in ("1", "true", "yes", "on"):
        return True
    if raw in ("0", "false", "no", "off"):
        return False
    return None


def _is_wsl() -> bool:
    if os.name != "posix":
        return False
    try:
        txt = Path("/proc/version").read_text(encoding="utf-8", errors="ignore").lower()
        return "microsoft" in txt or "wsl" in txt
    except OSError:
        return False


def _system_ram_gb() -> float | None:
    if os.name == "posix":
        try:
            for line in Path("/proc/meminfo").read_text(encoding="utf-8", errors="ignore").splitlines():
                if line.startswith("MemTotal:"):
                    return int(line.split()[1]) / (1024.0 * 1024.0)
        except (OSError, ValueError):
            return None
    elif os.name == "nt":
        try:
            import ctypes

            class _MEMSTAT(ctypes.Structure):
                _fields_ = [
                    ("dwLength", ctypes.c_ulong),
                    ("dwMemoryLoad", ctypes.c_ulong),
                    ("ullTotalPhys", ctypes.c_ulonglong),
                    ("ullAvailPhys", ctypes.c_ulonglong),
                    ("ullTotalPageFile", ctypes.c_ulonglong),
                    ("ullAvailPageFile", ctypes.c_ulonglong),
                    ("ullTotalVirtual", ctypes.c_ulonglong),
                    ("ullAvailVirtual", ctypes.c_ulonglong),
                    ("ullAvailExtendedVirtual", ctypes.c_ulonglong),
                ]

            st = _MEMSTAT()
            st.dwLength = ctypes.sizeof(st)
            if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(st)):
                return st.ullTotalPhys / float(2**30)
        except Exception:  # noqa: BLE001
            return None
    return None


def _is_low_ram() -> bool:
    """True on WSL2 or hosts with tight RAM where forked workers + huge shared arenas risk OOM."""
    ov = _env_opt_bool("EAGLE_LOW_RAM")
    if ov is not None:
        return ov
    ram = _system_ram_gb()
    if _is_wsl() and (ram is None or ram < 24.0):
        return True
    return ram is not None and ram < 16.0


def _should_pin_weights() -> bool:
    """Only lock pinned CPU RAM for weights on big-RAM (>= 64 GB) non-WSL hosts.
    PyTorch's caching host allocator inflates ~6 GB of pinned weights to ~24 GB RSS of
    non-swappable physical memory, which crashes WSL2 VMs and thrashes 16-32 GB desktops."""
    ov = _env_opt_bool("EAGLE_PIN_WEIGHTS")
    if ov is not None:
        return ov
    if _is_low_ram() or _is_wsl():
        return False
    ram = _system_ram_gb()
    return ram is not None and ram >= 64.0


def _should_use_disk_weights() -> bool:
    """In --low_vram mode on WSL2 (< 32 GB VM RAM) or < 24 GB desktops/laptops, stream each
    nnU-Net checkpoint from disk one network at a time instead of holding all ~6 GB of weights
    in anonymous CPU heap RAM. Keeps peak RSS around ~3-4 GB and peak VRAM around ~2.5-3 GB."""
    ov = _env_opt_bool("EAGLE_DISK_WEIGHTS")
    if ov is not None:
        return ov
    if not OPTS["low_vram"]:
        return False
    ram = _system_ram_gb()
    if _is_wsl():
        return ram is None or ram < 32.0
    return ram is not None and ram < 24.0


def _ncpu() -> int:
    return len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else (os.cpu_count() or 4)


def _can_fork_arena() -> bool:
    return (
        os.name == "posix"
        and hasattr(mmap, "MAP_SHARED")
        and "fork" in mp.get_all_start_methods()
    )


def _say(frac, msg):
    if CTX.progress is not None:
        try:
            CTX.progress(round(float(frac), 3), msg)
        except Exception:  # noqa: BLE001
            pass


def _check_cancel():
    if CTX.cancel is not None and CTX.cancel.is_set():
        raise Cancelled("cancelled by the client")


# ------------------------------------------------------------------------------------------------------- low-VRAM D331 features
class _CpuAccDF:
    """Lossless low-VRAM replacement for cls2_d331feat: keeps the 32-/64-ch full-volume accumulators on CPU
    while all network forwards and Gaussian products run on GPU. Uses reusable pinned CPU staging buffers
    for fast DMA D2H when running on CUDA -> IEEE float32 bit-identical."""

    def __init__(self, df, place, pin_ok: bool = True):
        self._df, self._place = df, place
        self._pin_ok = pin_ok
        self._pin1 = None
        self._pin2 = None

    def __getattr__(self, k):
        return getattr(self._df, k)

    def _copy_d2h(self, gpu_t, buf_attr):
        import torch
        if not self._pin_ok or gpu_t.device.type != "cuda":
            return gpu_t.cpu()
        buf = getattr(self, buf_attr)
        if buf is None or buf.shape != gpu_t.shape or buf.dtype != gpu_t.dtype:
            try:
                buf = torch.empty(gpu_t.shape, dtype=gpu_t.dtype, pin_memory=True)
                setattr(self, buf_attr, buf)
            except RuntimeError:
                return gpu_t.cpu()
        buf.copy_(gpu_t, non_blocking=False)
        return buf

    def features(self, net, t1, device, gw):
        import numpy as np
        import torch
        self._place()
        PATCH, steps = self._df.PATCH, self._df.steps
        cpu = torch.device("cpu")
        shp0 = t1.shape
        pad = [max(0, p - s) for p, s in zip(PATCH, shp0)]
        x = np.pad(t1, [(0, q) for q in pad])
        shp = x.shape
        xt = torch.from_numpy(x).to(device)[None, None]
        acc1 = torch.zeros((32,) + shp, device=cpu)
        acc2 = torch.zeros((64,) + tuple((s + 1) // 2 for s in shp), device=cpu)
        accl = torch.zeros((2,) + shp, device=device)
        wsum = torch.zeros(shp, device=device)
        g2 = torch.nn.functional.avg_pool3d(gw[None, None], 2)[0, 0]
        cap = {}
        dec = net.decoder
        h1 = dec.stages[-1].register_forward_hook(lambda m, i, o: cap.__setitem__("d1", o))
        h2 = dec.stages[-2].register_forward_hook(lambda m, i, o: cap.__setitem__("d2", o))
        try:
            with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16, enabled=device.type == "cuda"):
                for a in steps(shp[0], PATCH[0]):
                    for b in steps(shp[1], PATCH[1]):
                        for c in steps(shp[2], PATCH[2]):
                            sl = (slice(a, a + PATCH[0]), slice(b, b + PATCH[1]), slice(c, c + PATCH[2]))
                            lo = net(xt[(slice(None), slice(None)) + sl])
                            lo = lo[0] if isinstance(lo, (list, tuple)) else lo
                            accl[(slice(None),) + sl] += lo[0].float() * gw
                            acc1[(slice(None),) + sl] += self._copy_d2h(cap["d1"][0].float() * gw, "_pin1")
                            sl2 = tuple(slice(s.start // 2, s.start // 2 + p // 2) for s, p in zip(sl, PATCH))
                            acc2[(slice(None),) + sl2] += self._copy_d2h(cap["d2"][0].float() * g2, "_pin2")
                            wsum[sl] += gw
                            del lo
                            cap.clear()
        finally:
            h1.remove()
            h2.remove()
        w2 = torch.nn.functional.avg_pool3d(wsum[None, None], 2, ceil_mode=True)[0, 0]
        acc1 /= wsum.to(cpu)
        accl /= wsum
        acc2 /= w2[: acc2.shape[1], : acc2.shape[2], : acc2.shape[3]].clamp(min=1e-6).to(cpu)
        d = tuple(slice(0, s) for s in shp0)
        return acc1[(slice(None),) + d], acc2, (accl[1] - accl[0])[d]


# ------------------------------------------------------------------------------------------------------- CPU-shadow weight helpers
def _cpu_tensor(t, pin: bool = True):
    import torch
    if not isinstance(t, torch.Tensor):
        return t
    c = t.detach().cpu().contiguous()
    if pin and torch.cuda.is_available() and not c.is_pinned():
        try:
            return c.pin_memory()
        except RuntimeError:
            return c
    return c


def _snapshot_net_cpu(net, pin: bool = True):
    """Read-only CPU shadow copy of every parameter and buffer in ``net``, rebinding in place
    so unpinned/GPU storage is released immediately instead of doubling peak RAM."""
    sp = {}
    for k, p in net.named_parameters():
        c = _cpu_tensor(p, pin=pin)
        p.data = c
        sp[k] = c
    sb = {}
    for k, b in net.named_buffers():
        c = _cpu_tensor(b, pin=pin)
        b.data = c
        sb[k] = c
    return sp, sb


def _bind_net_cpu(net, shadow):
    """Drop GPU weight storage immediately (zero D2H copy: inference weights are read-only)."""
    sp, sb = shadow
    for k, p in net.named_parameters():
        p.data = sp[k]
    for k, b in net.named_buffers():
        b.data = sb[k]


def _bind_net_gpu(net, shadow, dev, non_blocking: bool = True):
    """Load CPU shadow weights to ``dev`` (non-blocking DMA when pinned)."""
    sp, sb = shadow
    for k, p in net.named_parameters():
        p.data = sp[k].to(dev, non_blocking=non_blocking)
    for k, b in net.named_buffers():
        b.data = sb[k].to(dev, non_blocking=non_blocking)


def _copy_state_dict_cpu(net, cpu_sd, non_blocking: bool = True):
    """Copy a CPU state dict into an already-on-GPU network (non-blocking DMA when pinned)."""
    import torch
    with torch.no_grad():
        for k, p in net.state_dict().items():
            src = cpu_sd[k]
            if isinstance(src, torch.Tensor):
                p.copy_(src, non_blocking=non_blocking)


def _trim_heap() -> None:
    """Return freed glibc heap arenas to the OS on Linux/WSL2 so VM memory stays low."""
    if os.name != "posix" or sys.platform != "linux":
        return
    try:
        import ctypes
        ctypes.CDLL("libc.so.6").malloc_trim(0)
    except Exception:  # noqa: BLE001
        pass


def _strip_net(net):
    """Release every parameter and buffer tensor storage to 0 bytes (keeps module skeleton)."""
    import torch
    empties = {}

    def _empty(dt):
        t = empties.get(dt)
        if t is None:
            t = torch.empty(0, dtype=dt, device="cpu")
            empties[dt] = t
        return t

    for _k, p in net.named_parameters():
        p.data = _empty(p.dtype)
    for _k, b in net.named_buffers():
        b.data = _empty(b.dtype)


def _load_net_ckpt(net, ckpt_path: str, dev):
    """Load nnU-Net ``network_weights`` from ``ckpt_path`` directly onto ``dev``."""
    import torch
    ck = torch.load(str(ckpt_path), map_location=dev, weights_only=False)
    sd = ck["network_weights"]
    del ck
    for k, p in net.named_parameters():
        p.data = sd[k]
    for k, b in net.named_buffers():
        b.data = sd[k]
    del sd
    net.eval()


# ------------------------------------------------------------------------------------------------------- engine subclass
def _install_engine():
    import engine as E
    if getattr(E, "_EAGLE_INSTALLED", False):
        return
    import numpy as np

    use_v2 = (not OPTS["fast_v1"]) and FC2.is_dir()
    if use_v2:
        import engine2 as E2
        Base = E2.FastEngineV2
        ENGINE_TAG = f"{E2.ENGINE_VERSION}+eagle2.0"
    else:
        E2 = None
        Base = E.FastEngine
        ENGINE_TAG = f"{E.ENGINE_VERSION}+eagle2.0-v1"

    class EagleEngine(Base):
        """FastEngineV2 (or v1 fallback) + progress/cancel + pinned low-VRAM + batch prefetch pipeline."""

        def __init__(self, a, rec, gates, opts):
            opts = dict(opts)
            self._use_v2 = use_v2
            self._memo_lock = threading.Lock()
            self._pinned_base_sds = None
            self._lv = None
            self._low_ram = _is_low_ram()
            self._disk_weights = _should_use_disk_weights()
            self._pin_weights = False if self._disk_weights else _should_pin_weights()
            self._pf_exec = cf.ThreadPoolExecutor(max_workers=1) if OPTS["pipeline"] else None
            self._pf_future = None
            self._pf_cid = None

            if use_v2:
                ncpu = _ncpu()
                ram_gb = _system_ram_gb()
                if OPTS["feat_procs"] is not None:
                    fp = int(OPTS["feat_procs"])
                elif self._low_ram or not _can_fork_arena():
                    fp = 0
                elif ncpu >= 4:
                    if ram_gb is not None and ram_gb < 32.0:
                        fp = min(4, max(2, ncpu - 2))
                    else:
                        fp = min(8, max(2, ncpu - 2))
                else:
                    fp = 0
                opts.setdefault("feat_procs", fp)
                arena_mb = 512 if (ram_gb is not None and ram_gb < 32.0) else 768
                opts.setdefault("arena_mb", arena_mb)
                if self._low_ram:
                    opts.setdefault("feat_threads", min(4, ncpu))
                    opts.setdefault("export_threads", min(3, ncpu))
                    opts.setdefault("resample_threads", min(4, ncpu))
                    opts["ctx_process"] = False
                else:
                    opts.setdefault("feat_threads", min(8, ncpu))
                    opts.setdefault("export_threads", min(6, ncpu))
                    opts.setdefault("resample_threads", min(12, max(4, ncpu)))
                if not _can_fork_arena():
                    opts["ctx_process"] = False
                if a.device != "cpu" and not OPTS["no_cnn_gpu"]:
                    opts["cnn_gpu"] = True
                if OPTS["low_vram"]:
                    opts["no_resident_seeds"] = True
                    opts["streams"] = False
                if OPTS["tf32"]:
                    opts["prec32"] = "tf32"
                if OPTS["verify_v2"]:
                    opts["verify_v2"] = True
                    opts["verify_every"] = int(OPTS["verify_every"] or 1)
                if OPTS["no_cnn_prewarm"]:
                    opts["no_cnn_prewarm"] = True

            super().__init__(a, rec, gates, opts)
            self._gate_i = 0

            # Replace v2 memos with thread-safe bounded memos so batch prefetch can overlap safely.
            if use_v2:
                self._harden_memos()

            def hook(st, fn):
                def w(*args, **kwargs):
                    _check_cancel()
                    if st == "cands":
                        self._gate_i = 0
                    if st == "base" and getattr(self, "_base_done", False):
                        return fn(*args, **kwargs)
                    if st == "d331" and getattr(self, "_d331_done", False):
                        return fn(*args, **kwargs)
                    if self._lv is not None:
                        __import__("torch").cuda.empty_cache()
                    _say(STAGE_FRAC[st], STAGE_MSG.get(st, st))
                    return fn(*args, **kwargs)
                return w

            for st in STAGE_FRAC:
                if hasattr(self, st):
                    setattr(self, st, hook(st, getattr(self, st)))
            if not use_v2 and hasattr(self, "cands_gate"):
                gfn = self.cands_gate

                def cands_gate(c, info, heat_sel, spec):
                    _check_cancel()
                    n = max(len(self.gates), 1)
                    i = min(self._gate_i, n - 1)
                    self._gate_i += 1
                    _say(STAGE_FRAC["cands"] + (STAGE_FRAC["base"] - STAGE_FRAC["cands"]) * i / n,
                         f"candidate classifier, gate {GATE_NAMES.get(heat_sel, heat_sel)}")
                    return gfn(c, info, heat_sel, spec)
                self.cands_gate = cands_gate

        def _harden_memos(self):
            """Make _img_memo and _rs_memo thread-safe and bounded for overlapped batch prefetch."""
            import SimpleITK as sitk
            import nnunetv2.preprocessing.resampling.default_resampling as RS

            if not self.o.get("no_read_memo"):
                # Unwrap back to real ReadImage if we wrapped it in super()._install_v2_patches
                orig_read = sitk.ReadImage
                lock = self._memo_lock
                memo = self._img_memo

                def read_safe(path, *a, **k):
                    if a or k or not isinstance(path, (str, os.PathLike)):
                        return orig_read(path, *a, **k)
                    key = os.path.abspath(str(path))
                    with lock:
                        hit = memo.get(key)
                    if hit is not None:
                        return sitk.Image(hit)
                    img = orig_read(str(path))
                    with lock:
                        if len(memo) >= 16:
                            memo.pop(next(iter(memo)))
                        memo[key] = img
                    return sitk.Image(img)
                # Note: orig_read already checks self._img_memo without a lock; avoid double-caching by
                # replacing directly with SimpleITK's underlying function if accessible, else lock around it.
                if getattr(orig_read, "__name__", "") == "read_memo" and orig_read.__closure__:
                    for cell in orig_read.__closure__:
                        val = cell.cell_contents
                        if callable(val) and getattr(val, "__name__", "") == "ReadImage":
                            orig_read = val
                            break
                sitk.ReadImage = read_safe

            if not self.o.get("no_par_resample") and not self.o.get("no_resample_memo"):
                rs_fn = RS.resample_data_or_seg
                lock = self._memo_lock
                memo_rs = self._rs_memo

                def rs_locked(*a, **k):
                    with lock:
                        if len(memo_rs) > 48:
                            for old_k in list(memo_rs)[:24]:
                                memo_rs.pop(old_k, None)
                    return rs_fn(*a, **k)
                RS.resample_data_or_seg = rs_locked

        # ---- VRAM-aware stream control
        def _effective_vram_gb(self):
            import torch
            if not torch.cuda.is_available() or self.models().dev.type != "cuda":
                return 0.0
            tot = torch.cuda.get_device_properties(torch.cuda.current_device()).total_memory / 2**30
            cap = os.environ.get("EAGLE_GPU_MEM_CAP_GB")
            return min(tot, float(cap)) if cap else tot

        def _streams_on(self):
            if not self._use_v2:
                return False
            if OPTS["low_vram"] or not self.o.get("streams", True):
                return False
            if self.models().dev.type != "cuda":
                return False
            # Multi-stream nnU-Net forwards reserve ~46 GB across concurrent activation workspaces;
            # on < 60 GB GPUs (all consumer & workstation cards up to 48 GB) sequential stage passes
            # keep peak VRAM at ~10.8 GB (or 6.6 GB in --low_vram) with < 0.5 s difference per case.
            return self._effective_vram_gb() >= 60.0

        # ---- warmup (cross-platform fcntl guard + low-VRAM setup before warmup)
        def warmup(self):
            if OPTS["low_vram"] and self.models().dev.type == "cuda":
                self._lv_setup()
            if self._lv is not None and self._lv.get("mode") == "disk":
                return self._warmup_disk()
            if os.name != "posix":
                return self._warmup_windows()
            return super().warmup()

        def _warmup_disk(self):
            """Warm cuDNN benchmark cache using one representative network per stage (1-net RAM/VRAM)."""
            import torch
            t0 = time.time()
            DF = self._DF
            dev = self.models().dev

            def run_one_net(pr, ckpt, cin, fp32):
                self._lv_load_one(pr, ckpt)
                x = torch.zeros((cin, *pr.configuration_manager.patch_size), dtype=torch.float32)
                with (E.RC.fp32_gpu() if fp32 else contextlib.nullcontext()), torch.no_grad():
                    pr.predict_logits_from_preprocessed_data(x)

            # One detector per preprocessing/architecture group (all 6 share ResEncUNetL)
            for keys in self.det_groups.values():
                pr = self.det_preds[keys[0]]
                run_one_net(pr, pr._eagle_ckpt, 2, False)
            d331 = self.models().d331()
            run_one_net(d331, d331._eagle_ckpt, 1, True)
            with E.RC.fp32_gpu(), torch.no_grad():
                DF.features(self.models().d331_net(), np.zeros(tuple(d331.configuration_manager.patch_size), np.float32),
                            dev, DF.gaussian(dev))
            base_ckpts = getattr(self.base_pred, "_eagle_base_ckpts", [])
            if base_ckpts:
                run_one_net(self.base_pred, base_ckpts[0], 2, False)
            if self.drawer_preds:
                pr = self.drawer_preds[0]
                run_one_net(pr, pr._eagle_ckpt, 2, True)
            self._lv_offload_all()
            torch.cuda.synchronize()
            return round(time.time() - t0, 1)

        def _warmup_windows(self):
            import torch
            t0 = time.time()
            DF = self._DF
            dev = self.models().dev

            def run(pr, cin, fp32):
                x = torch.zeros((cin, *pr.configuration_manager.patch_size), dtype=torch.float32)
                with (E.RC.fp32_gpu() if fp32 else contextlib.nullcontext()), torch.no_grad():
                    pr.predict_logits_from_preprocessed_data(x)
            for _k, pr in self.det_preds.items():
                run(pr, 2, False)
            d331 = self.models().d331()
            run(d331, 1, True)
            with E.RC.fp32_gpu(), torch.no_grad():
                DF.features(self.models().d331_net(), np.zeros(tuple(d331.configuration_manager.patch_size), np.float32),
                            dev, DF.gaussian(dev))
            pr = self.base_pred
            allp = pr.list_of_parameters
            try:
                for prm in allp:
                    pr.list_of_parameters = [prm]
                    run(pr, 2, False)
            finally:
                pr.list_of_parameters = allp
            for pr in self.drawer_preds:
                run(pr, 2, True)
            torch.cuda.synchronize()
            return round(time.time() - t0, 1)

        def _wrap_low_vram_loaders(self):
            """In --low_vram mode, free each single-fold predictor's duplicate CPU state dict
            immediately after it loads into ``pr.network``; in disk-backed low-RAM mode, also
            record checkpoint paths and strip weights right away so peak load RAM stays ~1.5 GB."""
            if self.o.get("no_keep_weights"):
                return
            M = self.models()
            if getattr(M, "_lv_loaders_wrapped", False):
                return
            disk = bool(self._disk_weights)

            def _ckpt_for(name, args, kwargs):
                import cascade2_common as C
                import cascade2_infer as I
                if name == "heat_det":
                    src = args[0] if len(args) > 0 else kwargs["src"]
                    fold_name = args[1] if len(args) > 1 else kwargs["fold_name"]
                    h = E.RP.PCFG["heats"][src]
                    tr = h["trainers"][fold_name] if "trainers" in h else h["trainer"]
                    idx = h["folds"][fold_name]
                    return str(I.model_dir(C.DET, tr) / f"fold_{idx}" / "checkpoint_final.pth")
                if name == "d331":
                    import devset_common as D
                    return str(D.model_dir("d331") / "fold_0" / "checkpoint_final.pth")
                if name == "drawer_member":
                    trainer = args[0] if len(args) > 0 else kwargs["trainer"]
                    d = E.RC.CFG["drawer"]
                    return str(I.model_dir(C.DEL, trainer) / f"fold_{d['fold']}" / "checkpoint_final.pth")
                return None

            def wrap_single(name, fn):
                def w(*args, **kwargs):
                    pr = fn(*args, **kwargs)
                    if not hasattr(pr, "_eagle_ckpt"):
                        pr._eagle_ckpt = _ckpt_for(name, args, kwargs)
                    if len(pr.list_of_parameters) == 1 and pr.list_of_parameters[0]:
                        E.FastEngine._keep_weights(pr)
                        pr.list_of_parameters[0].clear()
                    if disk and not getattr(pr, "_eagle_stripped_init", False):
                        _strip_net(pr.network)
                        pr._eagle_stripped_init = True
                        gc.collect()
                        _trim_heap()
                    return pr
                return w

            for name in ("heat_det", "d331", "drawer_member"):
                if hasattr(M, name):
                    setattr(M, name, wrap_single(name, getattr(M, name)))

            if disk and hasattr(M, "base_ens"):
                def base_ens_disk(name, ckpt):
                    key = f"base_{name}_{ckpt}"
                    if key not in M._m:
                        import cascade2_common as C
                        import cascade2_infer as I
                        import torch
                        b = E.RP.PCFG["bases"][name]
                        assert C.fold_index(C.DEL, b["fold_name"]) == b["fold"], b
                        dirs = [I.model_dir(C.DEL, t) for t in b["trainers"]]
                        pr = I.predictor(dirs[0], [b["fold"]], M.device, False, ckpt)
                        ref_shapes = {k: tuple(v.shape) for k, v in pr.list_of_parameters[0].items()}
                        p0 = (dirs[0] / "plans.json").read_bytes()
                        d0 = (dirs[0] / "dataset.json").read_bytes()
                        ck0 = torch.load(str(dirs[0] / f"fold_{b['fold']}" / ckpt), map_location=torch.device("cpu"), weights_only=False)
                        conf0 = ck0["init_args"]["configuration"]
                        del ck0
                        E.FastEngine._keep_weights(pr)
                        pr.list_of_parameters[0].clear()
                        _strip_net(pr.network)
                        gc.collect()
                        for d in dirs[1:]:
                            assert (d / "plans.json").read_bytes() == p0, f"plans.json differs: {d}"
                            assert (d / "dataset.json").read_bytes() == d0, f"dataset.json differs: {d}"
                            ck = torch.load(str(d / f"fold_{b['fold']}" / ckpt), map_location=torch.device("cpu"), weights_only=False)
                            w = ck["network_weights"]
                            assert set(w) == set(ref_shapes) and all(tuple(w[k].shape) == ref_shapes[k] for k in ref_shapes), f"architecture differs: {d}"
                            assert ck["init_args"]["configuration"] == conf0, f"configuration differs: {d}"
                            del w, ck
                            gc.collect()
                        pr._eagle_base_ckpts = [str(d / f"fold_{b['fold']}" / ckpt) for d in dirs]
                        pr._eagle_stripped_init = True
                        M._m[key] = pr
                    return M._m[key]

                M.base_ens = base_ens_disk
            M._lv_loaders_wrapped = True

        def load_all(self):
            # Avoid FastEngineV2's 87-second 1..64 CNN prewarm loop at startup; prewarm only the full
            # chunk size (64, ~1.5 s) unless explicitly requested via --cnn_prewarm_all.
            orig_prewarm = self.o.get("no_cnn_prewarm", False)
            if self._use_v2 and not OPTS.get("cnn_prewarm_all"):
                self.o["no_cnn_prewarm"] = True

            if OPTS["low_vram"] and self._use_v2:
                self._wrap_low_vram_loaders()
                self.o["no_resident_seeds"] = True
                self.o["streams"] = False
                orig_prec32 = self.o.get("prec32", "fp32")
                self.o["prec32"] = "fp32"
                ck = super().load_all()
                self.o["prec32"] = orig_prec32
                self.o["no_cnn_prewarm"] = orig_prewarm
                if self.models().dev.type == "cuda":
                    self._lv_setup()
                    if orig_prec32 != "fp32":
                        import gpu_multi as GM
                        import torch
                        P = tuple(self.models().d331().configuration_manager.patch_size)
                        with self._fp32ctx():
                            if self._lv.get("mode") == "disk":
                                d331_pr = self.models().d331()
                                self._lv_load_one(d331_pr, d331_pr._eagle_ckpt)
                                GM.sw_logits(d331_pr, torch.zeros((1, *P)))
                                with torch.no_grad():
                                    self._DF.features(self.models().d331_net(), np.zeros(P, np.float32),
                                                      self.models().dev, self._DF.gaussian(self.models().dev))
                                if self.drawer_preds:
                                    dr0 = self.drawer_preds[0]
                                    self._lv_load_one(dr0, dr0._eagle_ckpt)
                                    GM.sw_logits(dr0, torch.zeros((2, *P)))
                            else:
                                self._lv_place("d331")
                                GM.sw_logits(self.models().d331(), torch.zeros((1, *P)))
                                with torch.no_grad():
                                    self._DF.features(self.models().d331_net(), np.zeros(P, np.float32),
                                                      self.models().dev, self._DF.gaussian(self.models().dev))
                                self._lv_place("drawer")
                                for pr in self.drawer_preds:
                                    GM.sw_logits(pr, torch.zeros((2, *P)))
                        torch.cuda.synchronize()
                        ck["LOSSY_prec32"] = orig_prec32
                    self._lv_offload_all()
                    if self.o.get("cnn_gpu") and not orig_prewarm:
                        self._cnn_prewarm_lv(ck, sizes=(64,) if not OPTS.get("cnn_prewarm_all") else tuple(range(1, 65)))
                    if not self._disk_weights:
                        self._pin_base_seeds()
                    gc.collect()
                    if self._low_ram or self._disk_weights:
                        _trim_heap()
                    import torch
                    ram = _system_ram_gb()
                    ck["low_vram"] = True
                    ck["disk_weights"] = bool(self._disk_weights)
                    ck["pin_weights"] = self._pin_weights
                    ck["low_ram"] = self._low_ram
                    ck["wsl"] = _is_wsl()
                    if ram is not None:
                        ck["host_ram_GB"] = round(ram, 1)
                    if self._disk_weights:
                        ck["n_param_sets"] = {"base_seeds": len(getattr(self.base_pred, "_eagle_base_ckpts", []))}
                    ck["streams_active"] = False
                    ck["feat_procs"] = self.pp.nproc if self.pp is not None else 0
                    ck["tf32"] = bool(OPTS["tf32"])
                    ck["gpu_peak_alloc_load_GB"] = round(torch.cuda.max_memory_allocated() / 2**30, 2)
                    ck["gpu_peak_reserved_load_GB"] = round(torch.cuda.max_memory_reserved() / 2**30, 2)
                return ck

            # Normal mode: if effective VRAM < 15 GB (e.g. cap without --low_vram), avoid resident base copies
            if self._use_v2 and self.models().dev.type == "cuda" and self._effective_vram_gb() < 15.0:
                self.o["no_resident_seeds"] = True
            ck = super().load_all()
            self.o["no_cnn_prewarm"] = orig_prewarm
            if self._use_v2 and self.models().dev.type == "cuda" and self.o.get("cnn_gpu") and not orig_prewarm and not OPTS.get("cnn_prewarm_all"):
                self._cnn_prewarm_lv(ck, sizes=(64,))
            if self.models().dev.type == "cuda" and not getattr(self, "base_copies", None):
                self._pin_base_seeds()
            if self._use_v2:
                ck["streams_active"] = self._streams_on()
                ck["feat_procs"] = self.pp.nproc if self.pp is not None else 0
                ck["tf32"] = bool(OPTS["tf32"])
            return ck

        def _cnn_prewarm_lv(self, ck, sizes=(64,)):
            """Prewarm crop-CNN cuDNN kernels (chunk size 64 by default; ~1.5 s vs 87 s for 1..64)."""
            import cls3_cand as CC
            import dethead_cnn as N
            import dethead_crops as R
            import torch
            t0 = time.time()
            gdev = self.models().dev
            nets_ = CC.nets(torch.device("cpu"))
            FS, FIT = R.FS, R.FIT
            for nb in sizes:
                z = {
                    "t1f": torch.zeros((nb, FS, FS, FS), dtype=torch.int8),
                    "hmf": torch.zeros((nb, FS, FS, FS), dtype=torch.uint8),
                    "t1c": torch.zeros((nb, FS, FS, FS), dtype=torch.int8),
                    "hmc": torch.zeros((nb, FS, FS, FS), dtype=torch.uint8),
                    "t1s": torch.zeros((nb, FIT, FIT, FIT), dtype=torch.int8),
                    "hms": torch.zeros((nb, FIT, FIT, FIT), dtype=torch.uint8),
                }
                z["flf"] = z["t1f"][:1] * 0
                z["flc"] = z["flf"]
                with torch.no_grad(), E.RC.fp32_gpu():
                    for tag in ("v2a", "v2a_s1"):
                        N.predict(nets_[tag], {k: v.to(gdev) for k, v in z.items()}, np.ones(nb), 0, gdev, bs=64, tta=True)
            torch.cuda.synchronize()
            if self._lv is not None:
                torch.cuda.empty_cache()
            ck["t_cnn_prewarm_s"] = round(time.time() - t0, 1)

        def _pin_base_seeds(self):
            if self._pinned_base_sds is not None or len(self.base_pred.list_of_parameters) <= 1:
                return
            if self._pin_weights:
                # Pin in place inside list_of_parameters so we never hold both unpinned and pinned copies.
                for sd in self.base_pred.list_of_parameters:
                    for k in list(sd.keys()):
                        sd[k] = _cpu_tensor(sd[k], pin=True)
            self._pinned_base_sds = self.base_pred.list_of_parameters
            if self._lv is not None and self._pinned_base_sds:
                # Share seed 0's tensors with base_pred's CPU shadow (frees ~408 MB duplicate).
                sd0 = self._pinned_base_sds[0]
                pr = self.base_pred
                sp, sb = self._lv["shadows"]["base"][0]
                for k, p in pr.network.named_parameters():
                    src = sd0.get(k)
                    if src is not None and src.shape == p.shape and src.dtype == p.dtype:
                        sp[k] = src
                for k, b in pr.network.named_buffers():
                    src = sd0.get(k)
                    if src is not None and src.shape == b.shape and src.dtype == b.dtype:
                        sb[k] = src
                if self._lv["cur"] != "base":
                    _bind_net_cpu(pr.network, (sp, sb))

        # ---- low-VRAM read-only residency (disk-backed 1-net on WSL/<24 GB, pinned DMA >=64 GB, pageable CPU otherwise)
        def _lv_setup(self):
            if self._lv is not None:
                return
            import torch
            M = self.models()
            groups = {
                "det": list(self.det_preds.values()),
                "d331": [M.d331()],
                "base": [self.base_pred],
                "drawer": list(self.drawer_preds),
            }
            if self._disk_weights:
                for g in ("det", "d331", "drawer"):
                    for pr in groups[g]:
                        if not self.o.get("no_keep_weights") and len(pr.list_of_parameters) == 1 and pr.list_of_parameters[0]:
                            E.FastEngine._keep_weights(pr)
                            pr.list_of_parameters[0].clear()
                        _strip_net(pr.network)
                        orig = pr.predict_logits_from_preprocessed_data

                        def plog_disk(*args, _pr=pr, _o=orig, **kwargs):
                            self._lv_load_one(_pr, _pr._eagle_ckpt)
                            return _o(*args, **kwargs)
                        pr.predict_logits_from_preprocessed_data = plog_disk
                _strip_net(self.base_pred.network)
                self._lv = {
                    "mode": "disk", "groups": groups, "active_pr": None, "active_ckpt": None,
                    "cur": None, "dev": M.dev, "switches": 0, "t_switch": 0.0,
                }
                gc.collect()
                torch.cuda.empty_cache()
                d331_pr = M.d331()
                self._DF = _CpuAccDF(self._DF, lambda: self._lv_load_one(d331_pr, d331_pr._eagle_ckpt), pin_ok=False)
                print(
                    f"low-VRAM mode (disk-backed low-RAM): 1-network GPU/RAM residency across "
                    f"{sum(len(v) for v in groups.values())} networks, CPU D331 accumulators (lossless)",
                    file=sys.stderr, flush=True,
                )
                return

            shadows = {}
            for g, prs in groups.items():
                shadows[g] = []
                for pr in prs:
                    if not self.o.get("no_keep_weights") and len(pr.list_of_parameters) == 1 and pr.list_of_parameters[0]:
                        E.FastEngine._keep_weights(pr)
                        pr.list_of_parameters[0].clear()
                    sh = _snapshot_net_cpu(pr.network, pin=self._pin_weights)
                    shadows[g].append(sh)
                    orig = pr.predict_logits_from_preprocessed_data

                    def plog(*args, _g=g, _o=orig, **kwargs):
                        self._lv_place(_g)
                        return _o(*args, **kwargs)
                    pr.predict_logits_from_preprocessed_data = plog
            self._lv = {
                "mode": "ram", "groups": groups, "shadows": shadows, "cur": None, "dev": M.dev,
                "switches": 0, "t_switch": 0.0,
            }
            gc.collect()
            torch.cuda.empty_cache()
            self._DF = _CpuAccDF(self._DF, lambda: self._lv_place("d331"), pin_ok=self._pin_weights)
            mode_label = "pinned DMA" if self._pin_weights else "pageable CPU"
            print(
                f"low-VRAM mode ({mode_label}): stage-wise GPU residency of "
                f"{sum(len(v) for v in groups.values())} networks, CPU D331 accumulators (lossless)",
                file=sys.stderr, flush=True,
            )

        def _lv_load_one(self, pr, ckpt_path: str):
            lv = self._lv
            if lv is None or lv.get("mode") != "disk":
                return
            if lv["active_pr"] is pr and lv["active_ckpt"] == ckpt_path:
                return
            import torch
            t0 = time.time()
            if lv["active_pr"] is not None:
                torch.cuda.synchronize()
                _strip_net(lv["active_pr"].network)
                lv["active_pr"] = None
                lv["active_ckpt"] = None
                torch.cuda.empty_cache()
            _load_net_ckpt(pr.network, ckpt_path, lv["dev"])
            lv["active_pr"] = pr
            lv["active_ckpt"] = ckpt_path
            lv["switches"] += 1
            lv["t_switch"] += time.time() - t0

        def _lv_offload_all(self):
            lv = self._lv
            if lv is None:
                return
            import torch
            if lv.get("mode") == "disk":
                if lv["active_pr"] is not None:
                    torch.cuda.synchronize()
                    _strip_net(lv["active_pr"].network)
                    lv["active_pr"] = None
                    lv["active_ckpt"] = None
                    torch.cuda.empty_cache()
                return
            torch.cuda.synchronize()
            for gg, prs in lv["groups"].items():
                for pr, sh in zip(prs, lv["shadows"][gg]):
                    _bind_net_cpu(pr.network, sh)
            lv["cur"] = None
            torch.cuda.empty_cache()

        def _lv_place(self, g):
            lv = self._lv
            if lv is None or lv.get("mode") == "disk" or lv["cur"] == g:
                return
            import torch
            t0 = time.time()
            torch.cuda.synchronize()
            for gg, prs in lv["groups"].items():
                if gg != g:
                    for pr, sh in zip(prs, lv["shadows"][gg]):
                        _bind_net_cpu(pr.network, sh)
            torch.cuda.empty_cache()
            for pr, sh in zip(lv["groups"][g], lv["shadows"][g]):
                _bind_net_gpu(pr.network, sh, lv["dev"], non_blocking=self._pin_weights)
            torch.cuda.synchronize()
            lv["cur"] = g
            lv["switches"] += 1
            lv["t_switch"] += time.time() - t0

        # ---- stage overrides for fast base swaps, low-VRAM placement, and batch prefetch
        def base(self, c, info):
            if getattr(self, "_base_done", False):
                return
            disk_base = (
                self._lv is not None
                and self._lv.get("mode") == "disk"
                and hasattr(self.base_pred, "_eagle_base_ckpts")
                and self.models().dev.type == "cuda"
            )
            if not disk_base and (not self._use_v2 or self.base_copies or self._pinned_base_sds is None or self.models().dev.type != "cuda"):
                if self._lv is not None:
                    self._lv_place("base")
                return super().base(c, info)
            # Fast state-dict swaps through 1 GPU base network + sw_logits (bit-identical, 0 extra VRAM)
            import torch
            import gpu_multi as GM
            from nnunetv2.inference.data_iterators import PreprocessAdapterFromNpy
            if self._lv is not None and not disk_base:
                self._lv_place("base")
            pr = self.base_pred
            img1, props = self._t1()
            img = np.vstack([img1, self.S["heats"][self.a.base_heat][None]], dtype=np.float32, casting="unsafe")
            ppa = PreprocessAdapterFromNpy(
                [img], [None], [props], [None], pr.plans_manager, pr.dataset_json, pr.configuration_manager,
                num_threads_in_multithreaded=1, verbose=False,
            )
            dct = next(ppa)
            lgs = []
            if disk_base:
                for ckpt_path in pr._eagle_base_ckpts:
                    self._lv_load_one(pr, ckpt_path)
                    lg = GM.sw_logits(pr, dct["data"]).cpu()
                    if torch.any(torch.isinf(lg)):
                        raise RuntimeError("Encountered inf in predicted array (nnU-Net check)")
                    lgs.append(lg)
                self._lv_offload_all()
            else:
                for sd in self._pinned_base_sds:
                    _copy_state_dict_cpu(pr.network, sd, non_blocking=self._pin_weights)
                    lg = GM.sw_logits(pr, dct["data"]).cpu()
                    if torch.any(torch.isinf(lg)):
                        raise RuntimeError("Encountered inf in predicted array (nnU-Net check)")
                    lgs.append(lg)
                # Reset _keep_weights tracker so any subsequent predict_logits_from_preprocessed_data reloads cleanly
                if hasattr(pr.network, "load_state_dict"):
                    pr.network._fc_dirty = True

            def prob1(t):
                pb = self._export(t.clone(), pr, dct["data_properties"])
                return np.asarray(pb, np.float32)[1]

            avg = self.a.base_avg
            seeds = list(self.xp.map(prob1, lgs))
            if avg == "logit":
                lg = lgs[0].clone()
                for x in lgs[1:]:
                    lg += x
                if len(lgs) > 1:
                    lg /= len(lgs)
                out = prob1(lg) if len(lgs) > 1 else seeds[0]
            else:
                out = np.mean(seeds, 0) if len(lgs) > 1 else seeds[0]
            self.S["base_u8"] = E._u8(out)
            self.S["base_seeds_u8"] = [E._u8(s) for s in seeds]
            info.update(
                base=self.a.base, base_trainers=E.RP.PCFG["bases"][self.a.base]["trainers"],
                base_heat=self.a.base_heat, base_n_seeds=len(lgs),
            )

        def d331(self, c, info):
            if getattr(self, "_d331_done", False):
                return
            if self._lv is not None:
                if self._lv.get("mode") == "disk":
                    d331_pr = self.models().d331()
                    self._lv_load_one(d331_pr, d331_pr._eagle_ckpt)
                else:
                    self._lv_place("d331")
            if self._use_v2 and not self._streams_on() and self.d331_shared_pp:
                # Avoid redundant export conv + run D331 deep features right away while d331 is resident on GPU
                import torch
                import gpu_multi as GM
                pr = self.models().d331()
                x1 = torch.from_numpy(self.S["pp_t1_unmasked"][None].astype(np.float32))
                with self._fp32ctx():
                    if self.models().dev.type == "cuda":
                        lg = GM.sw_logits(pr, x1).cpu()
                    else:
                        lg = pr.predict_logits_from_preprocessed_data(x1).cpu()
                props = copy.deepcopy(self.S["pp_props"])
                fut = self.xp.submit(lambda: E._u8(np.asarray(self._export(lg, pr, props))[1]))
                if not self.o.get("no_early_d331feat"):
                    t1, brain, _ = self.load_prep(c)
                    mem = self._case_mem(c.cid)
                    t0 = time.time()
                    dev = self.models().dev
                    DF = self._DF
                    with self._fp32ctx(), torch.no_grad():
                        d1, d2, mg = DF.features(
                            self.models().d331_net(), np.where(brain, t1, 0).astype(np.float32), dev, DF.gaussian(dev)
                        )
                    mem["d331"] = (d1.cpu(), d2.cpu(), mg.cpu())
                    del d1, d2, mg
                    mem["t_d331feat"] = time.time() - t0
                if self._lv is not None and self._lv.get("mode") == "disk":
                    self._lv_offload_all()
                self.S["d331_u8"] = fut.result()
                self._d331_done = True
                return
            super().d331(c, info)
            if self._lv is not None and self._lv.get("mode") == "disk":
                self._lv_offload_all()

        def _gate_phase2(self, c, st, spec):
            # In low-VRAM mode, offload base network before crop CNNs run so VRAM stays well under 7 GB
            if self._lv is not None and (self._lv.get("cur") is not None or self._lv.get("active_pr") is not None):
                self._lv_offload_all()
            return super()._gate_phase2(c, st, spec)

        def heat(self, c, info):
            if self._lv is not None:
                self._lv_place("det")
            r = super().heat(c, info)
            if self._lv is not None and self._lv.get("mode") == "disk":
                self._lv_offload_all()
            return r

        def draw(self, c, info):
            # Release ~1.3 GB D331 deep features + patient context once cands has finished (low-RAM)
            if self._low_ram or self._disk_weights:
                self.mem.clear()
                gc.collect()
                _trim_heap()
            # Trigger case n+1 CPU prefetch right before GPU drawer passes + compose + write
            next_c = self.S.pop("_next_case", None)
            if next_c is not None and self._pf_exec is not None:
                self._pf_cid = next_c.cid
                self._pf_future = self._pf_exec.submit(self._prefetch_prep, next_c)
            if self._lv is not None:
                self._lv_place("drawer")
            r = super().draw(c, info)
            if self._lv is not None and self._lv.get("mode") == "disk":
                self._lv_offload_all()
            return r

        # ---- batch prefetch (case n+1 pure-CPU inputs + prep + det preprocessing)
        def _prefetch_prep(self, c):
            """Pure CPU preparation for case n+1; touches no CUDA state and mutates no self.S."""
            import pickle
            import dethead_apply as A
            from nnunetv2.imageio.simpleitk_reader_writer import SimpleITKIO

            pf_info = {}
            t0 = time.time()
            self.inputs(c, pf_info)
            t_in = round(time.time() - t0, 2)
            t0 = time.time()
            t1img = SimpleITKIO().read_images([c.t1_in])
            t1b = t1img[0][0] > 0
            ref = E.RC.read_img(c.t1_in)
            t1, seg, props = A.preprocess_t1(c.t1_in)
            pp_props = copy.deepcopy(props)
            brain = seg != -1
            t1m = np.where(brain, t1, 0).astype(np.float32)
            det_groups = self._det_preprocess(c) if self._use_v2 else None
            t_pr = round(time.time() - t0, 2)
            return {
                "cid": c.cid,
                "t1_in": c.t1_in,
                "fl_in": c.fl_in,
                "t1img": t1img,
                "t1b": t1b,
                "ref": ref,
                "pp_t1_unmasked": t1,
                "pp_props": pp_props,
                "t1_16": t1m.astype(np.float16),
                "brain": brain,
                "props_pkl": pickle.dumps(props),
                "pp_shape": list(t1m.shape),
                "brain_ml": float(brain.sum()) / 1000.0,
                "det_groups": det_groups,
                "pf_info": pf_info,
                "t_inputs": t_in,
                "t_prep": t_pr,
            }

        def _apply_prefetched(self, c, pf, info):
            import pickle
            c.t1_in = pf["t1_in"]
            c.fl_in = pf["fl_in"]
            info.update(pf["pf_info"])
            self.S["t1img"] = pf["t1img"]
            self.S["t1b"] = pf["t1b"]
            self.S["ref"] = pf["ref"]
            self.S["pp_t1_unmasked"] = pf["pp_t1_unmasked"]
            self.S["pp_props"] = pf["pp_props"]
            self.S["t1_16"] = pf["t1_16"]
            self.S["brain"] = pf["brain"]
            self.S["props_pkl"] = pf["props_pkl"]
            info["pp_shape"] = pf["pp_shape"]
            info["brain_ml"] = pf["brain_ml"]
            if pf["det_groups"] is not None:
                done_f: cf.Future = cf.Future()
                done_f.set_result(pf["det_groups"])
                self.S["det_pp_future"] = done_f
            # Submit patient_ctx to procpool immediately (same as FastEngineV2.prep)
            if self._use_v2:
                if self.pp is not None:
                    self.pp.arena.reset()
                if self.pp is not None and self.o.get("ctx_process", True):
                    import procpool as PP
                    S = self.S
                    A = self.pp.arena
                    t1d, _ = A.put(S["t1_16"].astype(np.float32))
                    bd, _ = A.put(S["brain"].astype(bool))
                    shp = S["t1_16"].shape
                    descs = {
                        k: A.alloc(shp, dt)[0]
                        for k, dt in (
                            ("t1z", np.float32), ("cls", np.int8), ("dv", np.float32), ("dedge", np.float32),
                            ("douter", np.float32), ("brain", np.bool_), ("nawm", np.bool_),
                        )
                    }
                    S["ctx_descs"] = descs
                    S["ctx_future"] = self.pp.submit(
                        PP.t_ctx, t1d, bd, pickle.loads(S["props_pkl"]), c.cid, descs, not self.o.get("no_ctx_par")
                    )
                elif self.ctx_proc is not None:
                    from engine2 import _ctx_worker
                    S = self.S
                    S["ctx_future"] = self.ctx_proc.submit(
                        _ctx_worker, S["t1_16"], S["brain"], S["props_pkl"], c.cid, not self.o.get("no_ctx_par")
                    )

        def run_one(self, c, out_frozen=None, out_eagle=None, next_case=None):
            import faulthandler
            import torch

            # Consume any matching prefetch future from the previous case
            pf = None
            if self._pf_future is not None:
                fut, pf_cid = self._pf_future, self._pf_cid
                self._pf_future, self._pf_cid = None, None
                try:
                    res = fut.result()
                    if pf_cid == c.cid:
                        pf = res
                except Exception:  # noqa: BLE001  (fallback to normal synchronous prep)
                    pf = None

            self._ncase = getattr(self, "_ncase", -1) + 1
            ve = int(self.o.get("verify_every") or 0)
            self._vfy = bool(self.o.get("verify_v2")) and (ve <= 1 or self._ncase % ve == 0)
            self.S = {}
            self.mem = {}
            self._base_done = False
            self._d331_done = False
            if next_case is not None:
                self.S["_next_case"] = next_case
            if self._use_v2 and self._pf_future is None and next_case is None:
                with self._memo_lock:
                    self._img_memo.clear()
                    self._rs_memo.clear()
                if self._fh is not None:
                    self._fh.clear()

            info = {"case_id": c.cid, "engine": ENGINE_TAG, "timing_s": {}, "prefetched": pf is not None}
            dev_cuda = self.models().dev.type == "cuda"
            if dev_cuda:
                torch.cuda.reset_peak_memory_stats()
            t_case = time.time()
            if hasattr(faulthandler, "dump_traceback_later"):
                faulthandler.dump_traceback_later(int(self.o.get("case_watchdog_s", 900)), exit=False)
            gt = int(self.o.get("gpu_threads") or torch.get_num_threads())

            if pf is not None:
                t0 = time.time()
                self._apply_prefetched(c, pf, info)
                info["timing_s"]["inputs"] = 0.0
                info["timing_s"]["prep"] = round(time.time() - t0, 2)
                info["prefetched_cpu_s"] = {"inputs": pf["t_inputs"], "prep": pf["t_prep"]}
                stages = ["heat", "d331", "cands", "base", "draw", "compose"]
            else:
                t0 = time.time()
                self.inputs(c, info)
                info["timing_s"]["inputs"] = round(time.time() - t0, 2)
                stages = ["prep", "heat", "d331"] + (["c2t"] if self.o.get("c2t_score") else []) + [
                    "cands", "base", "draw", "compose"
                ]

            for st in stages:
                t0 = time.time()
                if st != "cands":
                    torch.set_num_threads(gt)
                getattr(self, st)(c, info)
                if not (st == "base" and "base" in info["timing_s"]):
                    info["timing_s"][st] = round(time.time() - t0, 2)

            t0 = time.time()
            if out_frozen is not None:
                self.write_frozen_layout(c, Path(out_frozen) / "cases" / c.cid)
                if self.o.get("emit_member_variants") and hasattr(self, "write_member_variants"):
                    self.write_member_variants(c, Path(out_frozen))
            if out_eagle is not None:
                self.write_eagle(c, out_eagle, info)
            info["timing_s"]["write"] = round(time.time() - t0, 2)
            if dev_cuda:
                info["gpu_peak_alloc_GB"] = round(torch.cuda.max_memory_allocated() / 2**30, 2)
                info["gpu_peak_reserved_GB"] = round(torch.cuda.max_memory_reserved() / 2**30, 2)
            if hasattr(faulthandler, "cancel_dump_traceback_later"):
                faulthandler.cancel_dump_traceback_later()
            info["wall_s"] = round(time.time() - t_case, 2)
            info["status"] = "ok"
            info["verified_v2"] = self._vfy
            if self._vfy:
                info["verify_checks"] = {
                    k: v[-1] for k, v in self.checks.items()
                    if k.startswith("verify") and v and v[-1].get("case") == c.cid
                }
            shutil.rmtree(self.W(c), ignore_errors=True)
            self.S = {}
            self.mem = {}
            if self._low_ram or self._lv is not None:
                gc.collect()
                if self._low_ram or self._disk_weights:
                    _trim_heap()
            return info

        def write_eagle(self, c, out_dir, info):
            import cc3d
            import pandas as pd
            import scipy.ndimage as ndi

            out = Path(out_dir)
            out.mkdir(parents=True, exist_ok=True)
            S = self.S
            self.write(S["final"].astype(np.uint8), out / "lesion_mask.nii.gz", np.uint8)
            self.write(S["heats"][E.AR.MSRC], out / "prob.nii.gz", np.float32)
            self.write(S["source"], out / "source_map.nii.gz", np.uint8)
            self.write(S["acc"], out / "accepted.nii.gz", np.uint16)
            G = S["gates"]
            gname = {g: GATE_NAMES.get(h, h) for g, h, _s in self.gates}
            anyc = None
            for g in G.values():
                m = g["Lraw"].astype(np.int32) > 0
                anyc = m if anyc is None else (anyc | m)
            if anyc is not None and anyc.any():
                U = cc3d.connected_components(anyc.astype(np.uint8), connectivity=26).astype(np.uint16)
            else:
                U = np.zeros(S["final"].shape, np.uint16)
            self.write(U, out / "candidates.nii.gz", np.uint16)
            fin = S["final"].astype(bool)
            nU = int(U.max())
            items = []
            sl = ndi.find_objects(U.astype(np.int32)) if nU else []
            score_of = {}
            for g, d in G.items():
                df = d["df"]
                score_of[g] = (
                    {int(r["cid"]): (float(r["score"]), bool(r["accepted"])) for _, r in df.iterrows()}
                    if len(df) else {}
                )
            for u in range(1, nU + 1):
                s = sl[u - 1]
                if s is None:
                    continue
                reg = U[s] == u
                gs, acc_g, thr = {}, [], {}
                for g, d in G.items():
                    ids = np.unique(d["Lraw"][s][reg])
                    ids = [int(i) for i in ids if i > 0 and int(i) in score_of[g]]
                    if not ids:
                        continue
                    sc = [score_of[g][i][0] for i in ids]
                    gs[gname[g]] = round(max(sc), 6)
                    thr[gname[g]] = float(d["threshold"])
                    if any(score_of[g][i][1] for i in ids):
                        acc_g.append(gname[g])
                acc_scores = [gs[n] for n in acc_g]
                score = max(acc_scores) if acc_scores else (max(gs.values()) if gs else None)
                items.append({
                    "label": u, "score": score, "flag": "accept" if acc_g else "reject",
                    "source": "drawer" if acc_g else None, "gates": acc_g, "gate_scores": gs,
                    "gate_thresholds": thr, "in_final_mask": bool(fin[s][reg].any()), "voxels": int(reg.sum()),
                })
            with open(out / "candidates.json", "w", encoding="utf-8") as fh:
                json.dump(items, fh, indent=1)
            keep = ["cid", "vox", "ml_pp", "centroid_zyx_raw", "score", "score_ss", "score_c2t", "accepted",
                    "h_peak", "h_mean", "p_d331_max", "p_d331_mean"]
            for g, d in G.items():
                df = d["df"]
                o = (df[[k for k in keep if k in df.columns]].copy()
                     if len(df) else pd.DataFrame(columns=["cid", "vox", "score", "score_ss", "accepted"]))
                o.insert(1, "case_id", c.cid)
                o["classifier"] = "s_sepd"
                o["threshold"] = d["threshold"]
                o.to_csv(out / f"candidates_{g}.csv", index=False, float_format="%.6g")
            self._runner_json(c, out, info)

        def _runner_json(self, c, out, info, extra=None):
            gates = [
                {
                    "name": GATE_NAMES.get(h, h), "id": g, "heat": h, "threshold": float(s["threshold"]),
                    "classifier": Path(s.get("dir") or s["dh"]).name,
                    "n_candidates": (info.get("gates") or {}).get(g, {}).get("n_candidates"),
                    "n_accepted": (info.get("gates") or {}).get(g, {}).get("n_accepted"),
                }
                for g, h, s in self.gates
            ]
            doc = {
                "model_version": OPTS["model_version"], "runner": RUNNER_VERSION,
                "bundle": ({"path": BUNDLE["bundle"], "version": BUNDLE["meta"]["version"]} if BUNDLE else None),
                "engine": ENGINE_TAG, "protocol": PROTOCOL, "profile": self.a.resolved.get("profile"),
                "device": str(self.models().dev), "case_id": c.cid, "gates": gates,
                "accept_rule": "accepted if ANY gate accepts (union)",
                "stage_versions": {
                    "detector": list(self.rec["members"]["det"]),
                    "base": self.a.resolved["base_trainers"],
                    "drawer": self.a.drawer_trainers,
                },
                "threads": {k: os.environ.get(k) for k in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS")},
                "timing_s": info.get("timing_s"), "checks": self.checks, "tf32": bool(OPTS["tf32"]),
            }
            if self._lv is not None:
                doc["low_vram"] = {
                    "mode": self._lv.get("mode", "ram"),
                    "switches_total": self._lv["switches"],
                    "t_switch_total_s": round(self._lv["t_switch"], 2),
                    "disk_weights": bool(self._disk_weights),
                    "pinned_dma": bool(self._pin_weights),
                    "low_ram": bool(self._low_ram),
                }
            doc.update(extra or {})
            with open(out / "runner.json", "w", encoding="utf-8") as fh:
                json.dump(doc, fh, indent=1, default=str)

    E.FastEngine = EagleEngine
    E._EAGLE_INSTALLED = True


_orig_build = RF.build


def _install_sklearn_compat():
    """Allow scikit-learn 1.7.x HistGradientBoosting pickles to load bit-identically on 1.8+.

    In scikit-learn 1.7.x, Cython loss objects (e.g. ``CyHalfBinomialLoss``) pickled with
    top-level module name ``_loss``. Newer scikit-learn releases drop the top-level alias while
    keeping ``sklearn._loss._loss`` binary-compatible for inference.
    """
    if "_loss" in sys.modules:
        return
    try:
        import sklearn._loss._loss as _skl_loss
        sys.modules["_loss"] = _skl_loss
    except Exception:  # noqa: BLE001
        pass


def _build(a):
    _install_sklearn_compat()
    _install_engine()
    r = _orig_build(a)
    cap = os.environ.get("EAGLE_GPU_MEM_CAP_GB")
    if cap:
        import torch
        if torch.cuda.is_available():
            tot = torch.cuda.get_device_properties(torch.cuda.current_device()).total_memory / 2**30
            torch.cuda.set_per_process_memory_fraction(min(1.0, float(cap) / tot))
            print(f"GPU memory cap {float(cap):.2f} GB of {tot:.1f} GB", file=sys.stderr, flush=True)
    return r


def _eagle_case(eng, req, next_case=None):
    import engine as E
    RC = E.RC
    cid = req.get("case_id") or "case"
    c = RC.Case(RC.safe_id(cid), req["t1"], req["flair"], None, req.get("brain_mask") or None)
    t0 = time.time()
    info = eng.run_one(c, out_eagle=req["out_dir"], next_case=next_case)
    info["wall_s_incl_write"] = round(time.time() - t0, 2)
    out = Path(req["out_dir"])
    try:
        with open(out / "runner.json", encoding="utf-8") as fh:
            rj = json.load(fh)
        rj.update({
            k: info.get(k) for k in (
                "wall_s", "wall_s_incl_write", "gpu_peak_alloc_GB", "gpu_peak_reserved_GB",
                "n_candidates", "n_accepted", "final_ml", "final_components", "prefetched",
            )
        })
        rj["wall_s_request"] = round(time.time() - t0, 2)
        with open(out / "runner.json", "w", encoding="utf-8") as fh:
            json.dump(rj, fh, indent=1, default=str)
    except FileNotFoundError:
        pass
    _say(1.0, "done")
    return info


def _run_batch(a):
    """run_fast.run_batch with case n+1 CPU prefetch overlapped behind case n's GPU draw/compose/write."""
    import engine as E
    RC = E.RC
    t0 = time.time()
    eng, rec = RF.build(a)
    t_build = time.time() - t0
    ck = eng.load_all()
    if a.chunk == 0 and not a.no_manifest:
        tm = time.time()
        man = E.AR.manifest(eng.a, rec, RC.read_cases(a.cases))
        ck["t_manifest_s"] = round(time.time() - tm, 1)
        ck["pinned_checked"] = len(man["pinned_checked"])
        ck["pinned_mismatch"] = man["pinned_mismatch"]
    cases = RC.read_cases(a.cases)
    mine = cases[a.chunk::a.nchunk][: a.limit or None]
    out = Path(a.out)
    (out / "logs").mkdir(parents=True, exist_ok=True)
    tag = f"{os.environ.get('SLURM_JOB_ID', 'local')}_{a.chunk}of{a.nchunk}"
    RC.log(
        f"eagle_runner2 | profile {a.profile} | gates {[g for g, _, _ in eng.gates]} | device {eng.a.device} | "
        f"low_vram {OPTS['low_vram']} | pipeline {OPTS['pipeline']} | {len(mine)}/{len(cases)} cases | "
        f"build {t_build:.1f}s load {ck['t_load_s']}s | checks {ck}"
    )
    todo = [c for c in mine if not (a.resume and (out / "cases" / c.cid / f"{c.cid}_fast_log.json").exists())]
    recs = []
    for i, c in enumerate(todo):
        nxt = todo[i + 1] if (OPTS["pipeline"] and i + 1 < len(todo)) else None
        try:
            info = eng.run_one(c, out_frozen=out, next_case=nxt)
            RC.dump_json(info, out / "cases" / c.cid / f"{c.cid}_fast_log.json")
            recs.append(info)
            RC.log(
                "CASE_DONE", c.cid,
                json.dumps({
                    k: info.get(k) for k in (
                        "n_candidates", "n_accepted", "final_ml", "wall_s", "timing_s",
                        "gpu_peak_alloc_GB", "gpu_peak_reserved_GB", "prefetched",
                    )
                }),
            )
        except Exception as e:  # noqa: BLE001
            traceback.print_exc()
            RC.log("CASE_FAILED", c.cid, repr(e)[:300])
    RC.dump_json(
        {"t_build_s": t_build, "checks": ck, "t_total_s": time.time() - t0, "n": len(recs),
         "cases": [r["case_id"] for r in recs]},
        out / "logs" / f"run_{tag}.json",
    )
    RC.log("RUN_DONE", len(recs), "ok of", len(todo))


RF.build = _build
RF.eagle_case = _eagle_case
RF.run_batch = _run_batch


# ------------------------------------------------------------------------------------------------------- server (protocol v1)
class Job:
    def __init__(self, req):
        self.req = req
        self.events: queue.Queue = queue.Queue()
        self.cancel = threading.Event()
        self.done = False


def _send(conn, obj):
    conn.sendall((json.dumps(obj, default=str) + "\n").encode())


def _recv_line(conn):
    buf = b""
    while not buf.endswith(b"\n"):
        d = conn.recv(65536)
        if not d:
            break
        buf += d
    return json.loads(buf.decode()) if buf.strip() else None


def _probe_existing_server(sp: str) -> bool:
    """True if another resident server is already listening on ``sp`` (AF_UNIX or TCP descriptor)."""
    if not os.path.exists(sp):
        return False
    # Check TCP descriptor file first (Windows or EAGLE_SERVER_TCP=1)
    try:
        if os.path.isfile(sp) and os.path.getsize(sp) <= 4096:
            ep = json.loads(Path(sp).read_text(encoding="utf-8"))
            if isinstance(ep, dict) and ep.get("transport") == "tcp":
                host = str(ep.get("host") or "")
                port = int(ep.get("port") or 0)
                token = str(ep.get("token") or "")
                if host in ("127.0.0.1", "::1") and 1 <= port <= 65535 and token:
                    with socket.create_connection((host, port), timeout=2.0) as t:
                        t.settimeout(2.0)
                        _send(t, {"cmd": "ping", "token": token})
                        resp = _recv_line(t)
                        return bool(resp and resp.get("ok"))
    except (OSError, ValueError, TypeError):
        pass
    if hasattr(socket, "AF_UNIX"):
        try:
            with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as t:
                t.settimeout(2)
                t.connect(sp)
            return True
        except OSError:
            pass
    return False


def serve(a):
    import faulthandler
    import engine as E
    eng, _ = RF.build(a)
    eng.load_all()
    sp = a.serve
    if os.path.exists(sp):
        if _probe_existing_server(sp):
            print(f"ERROR another server is listening on {sp}", flush=True)
            sys.exit(3)
        try:
            os.unlink(sp)
        except OSError:
            pass
    Path(sp).parent.mkdir(parents=True, exist_ok=True)
    use_tcp = (not hasattr(socket, "AF_UNIX")) or _env_flag("EAGLE_SERVER_TCP")
    expected_token = None
    transport_info = {"transport": "unix"}
    if use_tcp:
        srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        srv.bind(("127.0.0.1", 0))
        port = srv.getsockname()[1]
        srv.listen(16)
        expected_token = secrets.token_hex(32)
        ep = {"transport": "tcp", "host": "127.0.0.1", "port": port, "token": expected_token, "pid": os.getpid()}
        tmp = f"{sp}.tmp{os.getpid()}"
        with open(tmp, "w", encoding="utf-8") as fh:
            json.dump(ep, fh)
        if os.name == "posix":
            os.chmod(tmp, 0o600)
        os.replace(tmp, sp)
        transport_info = {"transport": "tcp", "host": "127.0.0.1", "port": port}
    else:
        srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        srv.bind(sp)
        if os.name == "posix":
            os.chmod(sp, 0o600)
        srv.listen(16)
    jobs: queue.Queue = queue.Queue()
    state = {"current": None, "queued": [], "stop": False, "last": time.time(), "served": 0}
    lock = threading.Lock()
    dev = str(eng.models().dev)

    def handle(conn):
        with conn:
            try:
                req = _recv_line(conn)
            except Exception as e:  # noqa: BLE001
                try:
                    _send(conn, {"ok": False, "error": f"bad request: {e!r}"})
                except OSError:
                    pass
                return
            if expected_token is not None:
                got_tok = str((req or {}).get("token") or "")
                if not secrets.compare_digest(got_tok, expected_token):
                    try:
                        _send(conn, {"ok": False, "error": "unauthorized"})
                    except OSError:
                        pass
                    return
            cmd = (req or {}).get("cmd", "segment")
            if cmd == "ping":
                with lock:
                    _send(conn, {
                        "ok": True, "protocol": PROTOCOL, "ready": True, "busy": state["current"] is not None,
                        "queued": len(state["queued"]), "device": dev, "pid": os.getpid(),
                        "model_version": OPTS["model_version"], "runner": RUNNER_VERSION, "served": state["served"],
                        "bundle": BUNDLE["meta"]["version"] if BUNDLE else None, "low_vram": OPTS["low_vram"],
                        "tf32": OPTS["tf32"],
                        "checks": {k: eng.checks.get(k) for k in ("t_load_s", "t_warmup_s", "t_cnn_prewarm_s",
                                                                   "pinned_checked", "streams_active", "feat_procs",
                                                                   "disk_weights")},
                    })
                return
            if cmd == "cancel":
                n = 0
                with lock:
                    for j in [state["current"], *state["queued"]]:
                        if j is not None and (not req.get("out_dir") or j.req.get("out_dir") == req.get("out_dir")):
                            j.cancel.set()
                            n += 1
                _send(conn, {"ok": True, "cancelled": n})
                return
            if cmd == "shutdown":
                state["stop"] = True
                jobs.put(None)
                _send(conn, {"ok": True})
                return
            if cmd != "segment":
                _send(conn, {"ok": False, "error": f"unknown cmd {cmd!r}"})
                return
            miss = [k for k in ("t1", "flair", "out_dir") if not req.get(k)]
            if miss:
                _send(conn, {"event": "error", "ok": False, "error": f"missing field(s) {miss}", "cancelled": False})
                return
            job = Job(req)
            with lock:
                state["queued"].append(job)
                ahead = len(state["queued"]) - 1 + (state["current"] is not None)
            jobs.put(job)
            try:
                if ahead:
                    _send(conn, {"event": "progress", "fraction": 0.0,
                                 "message": f"waiting for the model ({ahead} case(s) ahead)"})
                while True:
                    try:
                        ev = job.events.get(timeout=5.0)
                    except queue.Empty:
                        _send(conn, {"event": "heartbeat"})
                        continue
                    _send(conn, ev)
                    if ev.get("event") in ("done", "error"):
                        break
            except OSError:
                job.cancel.set()

    def accept_loop():
        while not state["stop"]:
            try:
                conn, _ = srv.accept()
            except OSError:
                break
            threading.Thread(target=handle, args=(conn,), daemon=True).start()

    def _term(signum, frame):
        state["stop"] = True
        jobs.put(None)

    signal.signal(signal.SIGTERM, _term)
    threading.Thread(target=accept_loop, daemon=True).start()
    print("SERVING", sp, json.dumps({"device": dev, "protocol": PROTOCOL, "pid": os.getpid(),
                                     "low_vram": OPTS["low_vram"], **transport_info}), flush=True)
    try:
        while not state["stop"]:
            try:
                job = jobs.get(timeout=1.0)
            except queue.Empty:
                if OPTS["idle_exit"] and time.time() - state["last"] > OPTS["idle_exit"] and state["current"] is None:
                    print(f"IDLE_EXIT after {OPTS['idle_exit']:.0f} s", flush=True)
                    break
                continue
            if job is None:
                continue
            with lock:
                if job in state["queued"]:
                    state["queued"].remove(job)
                state["current"] = job
                # Peek next queued job for batch prefetch overlap
                nxt_c = None
                if OPTS["pipeline"] and state["queued"]:
                    nr = state["queued"][0].req
                    nxt_c = E.RC.Case(
                        E.RC.safe_id(nr.get("case_id") or "case"), nr["t1"], nr["flair"], None,
                        nr.get("brain_mask") or None,
                    )
            t0 = time.time()
            try:
                if job.cancel.is_set():
                    raise Cancelled("cancelled before start")
                CTX.cancel = job.cancel
                CTX.progress = lambda f, m, _j=job: _j.events.put({"event": "progress", "fraction": f, "message": m})
                info = _eagle_case(eng, job.req, next_case=nxt_c)
                job.events.put({"event": "done", "ok": True, "info": info})
                print("CASE_DONE", job.req.get("case_id"), f"{time.time() - t0:.1f}s", flush=True)
            except Cancelled as e:
                if hasattr(faulthandler, "cancel_dump_traceback_later"):
                    faulthandler.cancel_dump_traceback_later()
                eng.S = {}
                eng.mem = {}
                if getattr(eng, "_lv", None) is not None and eng._lv.get("mode") == "disk":
                    eng._lv_offload_all()
                job.events.put({"event": "error", "ok": False, "cancelled": True, "error": str(e)})
                print("CASE_CANCELLED", job.req.get("case_id"), f"{time.time() - t0:.1f}s", flush=True)
            except Exception as e:  # noqa: BLE001
                if hasattr(faulthandler, "cancel_dump_traceback_later"):
                    faulthandler.cancel_dump_traceback_later()
                eng.S = {}
                eng.mem = {}
                if getattr(eng, "_lv", None) is not None and eng._lv.get("mode") == "disk":
                    eng._lv_offload_all()
                job.events.put({"event": "error", "ok": False, "cancelled": False, "error": repr(e),
                                "trace": traceback.format_exc()[-4000:]})
                print("CASE_FAILED", job.req.get("case_id"), repr(e)[:300], flush=True)
            finally:
                CTX.cancel = None
                CTX.progress = None
                with lock:
                    state["current"] = None
                    state["served"] += 1
                    state["last"] = time.time()
    finally:
        try:
            srv.close()
        except OSError:
            pass
        try:
            if not use_tcp:
                os.unlink(sp)
            elif os.path.isfile(sp):
                cur = json.loads(Path(sp).read_text(encoding="utf-8"))
                if cur.get("token") == expected_token:
                    os.unlink(sp)
        except (OSError, ValueError):
            pass
        print("SERVER_EXIT", flush=True)


RF.serve = serve


def _rf_main():
    """Cross-platform entrypoint equivalent to ``run_fast.main()`` (safe on Windows)."""
    import faulthandler
    if hasattr(faulthandler, "register") and hasattr(signal, "SIGUSR1"):
        faulthandler.register(signal.SIGUSR1, all_threads=True)
    ap = argparse.ArgumentParser(description=RF.__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--cases")
    ap.add_argument("--out")
    ap.add_argument("--profile", default="parity")
    ap.add_argument("--clf_dir")
    ap.add_argument("--union_gates")
    ap.add_argument("--clf", action="append")
    ap.add_argument("--workers", type=int, default=1)
    ap.add_argument("--threads", type=int, default=2)
    ap.add_argument("--gpu_threads", type=int, default=-1)
    ap.add_argument("--cands_threads", type=int, default=2)
    ap.add_argument("--no_shared_d331_pp", action="store_true")
    ap.add_argument("--no_warmup", action="store_true")
    ap.add_argument("--cands_pool", type=int, default=-1)
    ap.add_argument("--cudnn_deterministic", action="store_true")
    ap.add_argument("--cnn_gpu", action="store_true")
    ap.add_argument("--c2t_score", action="store_true")
    ap.add_argument("--overlap", action="store_true")
    ap.add_argument("--chunk", type=int, default=0)
    ap.add_argument("--nchunk", type=int, default=1)
    ap.add_argument("--limit", type=int, default=0)
    ap.add_argument("--resume", action="store_true")
    ap.add_argument("--no_manifest", action="store_true")
    ap.add_argument("--device", default=None)
    ap.add_argument("--t1")
    ap.add_argument("--flair")
    ap.add_argument("--out_dir")
    ap.add_argument("--brain_mask")
    ap.add_argument("--work_dir")
    ap.add_argument("--model_dir")
    ap.add_argument("--case_id")
    ap.add_argument("--serve")
    ap.add_argument("--server")
    a = ap.parse_args()
    if a.clf_dir:
        a.clf_dir = os.path.abspath(a.clf_dir)
    ncpu = len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else (os.cpu_count() or 2)
    per = max(2, ncpu // max(a.workers, 1))
    if a.gpu_threads < 0:
        a.gpu_threads = per
    if a.cands_pool < 0:
        a.cands_pool = min(8, per)
    if a.workers > 1:
        return RF.run_workers(a)
    RF.set_threads(a.threads, a.gpu_threads)
    if a.server and a.t1:
        return RF.client(a)
    if a.serve:
        a.out = a.out or os.path.join(a.work_dir or tempfile.gettempdir(), "fastcascade_server")
        return RF.serve(a)
    if a.t1:
        a.out = a.work_dir or os.path.join(a.out_dir, ".fastcascade")
        eng, _ = RF.build(a)
        eng.load_all()
        info = RF.eagle_case(
            eng, {"t1": a.t1, "flair": a.flair, "out_dir": a.out_dir, "brain_mask": a.brain_mask, "case_id": a.case_id}
        )
        print(json.dumps(info.get("timing_s")), flush=True)
        return None
    assert a.cases and a.out, "--cases and --out (batch) or --t1/--flair/--out_dir (single case)"
    return RF.run_batch(a)


def main():
    if "--bundle_verify" in sys.argv:
        sys.exit(1 if _BB.verify(BUNDLE["bundle"] if BUNDLE else str(HERE.parent)) else 0)
    ap = argparse.ArgumentParser(add_help=False)
    ap.add_argument("--idle_exit", type=float, default=0.0)
    ap.add_argument("--model_version", default=OPTS["model_version"])
    ap.add_argument("--no_progress", action="store_true")
    ap.add_argument("--low_vram", action="store_true")
    ap.add_argument("--tf32", action="store_true")
    ap.add_argument("--fast_v1", action="store_true")
    ap.add_argument("--no_pipeline", action="store_true")
    ap.add_argument("--no_cnn_gpu", action="store_true")
    ap.add_argument("--no_cnn_prewarm", action="store_true")
    ap.add_argument("--cnn_prewarm_all", action="store_true")
    ap.add_argument("--feat_procs", type=int, default=None)
    ap.add_argument("--verify_v2", action="store_true")
    ap.add_argument("--verify_every", type=int, default=0)
    own, rest = ap.parse_known_args()
    OPTS.update(
        idle_exit=own.idle_exit,
        model_version=own.model_version,
        low_vram=own.low_vram or _env_flag("EAGLE_LOW_VRAM"),
        tf32=own.tf32 or _env_flag("EAGLE_TF32"),
        fast_v1=own.fast_v1 or _env_flag("EAGLE_RUNNER_V1"),
        pipeline=not own.no_pipeline,
        no_cnn_gpu=own.no_cnn_gpu,
        no_cnn_prewarm=own.no_cnn_prewarm,
        cnn_prewarm_all=own.cnn_prewarm_all,
        feat_procs=own.feat_procs,
        verify_v2=own.verify_v2,
        verify_every=own.verify_every,
    )
    if BUNDLE is not None:
        rest = _BB.runner_args(BUNDLE, rest)
        if own.model_version == "U_PAIR_2c":
            OPTS["model_version"] = BUNDLE["meta"].get("model_version", "U_PAIR_2c")
    sys.argv = [str(FC / "run_fast.py"), *rest]
    if "--serve" not in rest and "--t1" in rest and not own.no_progress:
        def pr(f, m):
            print("PROGRESS " + json.dumps({"fraction": f, "message": m}), flush=True)
        CTX.progress = pr
    _rf_main()


if __name__ == "__main__":
    main()