File size: 95,598 Bytes
85f2567
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
"""Training loop. A smoke fit only shows that the software runs.

Hyperparameters come from the YAML config. ``pretrained: true`` downloads
ImageNet weights and is refused unless ``CLOUDIE_ALLOW_PRETRAINED=1``.
The wind loss is weighted Smooth L1. The class loss is auxiliary. A size
term is added only when ``r34_nmi`` and ``rmw_nmi`` exist as labels, and
those columns are targets, not inputs. ``model.name: convlstm`` uses four
frames from the same storm and the same split.

``python -m src.train`` picks xpu, then cuda, then cpu. XPU and CUDA both
need ``CLOUDIE_ALLOW_GPU=1``. Normalization is fit per dataset on train
storms only. ``--init-from`` loads weights for a later dataset and refits
those stats. ``--resume`` continues the last finished epoch.
"""

from __future__ import annotations

import argparse
import copy
import hashlib
import json
import logging
import os
import random
import subprocess
import time
from pathlib import Path

import numpy as np
import pandas as pd

from src.config import checkpoint_path, load_config, parse_image_size
from src.data_loader import apply_frame_cache, load_image, load_manifest, resolve_image
from src.device import (
    amp_policy_for,
    autocast_context,
    compare_model_parity,
    make_grad_scaler,
    peak_memory_bytes,
    reset_peak_memory,
    resolve_device,
    seeded_parity_batch,
    xpu_device_properties,
)
from src.labels import apply_wind_standard, back_converted_prediction, run_conversion_note
from src.preprocessing import (
    NormStats,
    fit_norm_stats,
    norm_by_dataset,
    prepare_image,
    prepare_training_chip,
    stack_prepared,
)
from src.schema import (
    SchemaError,
    parse_is_synthetic,
    recorded_wind_averaging,
    split_wind_averaging,
    wind_averaging_seconds,
    wind_to_imd5,
)
from src.sequences import N_FRAMES, _row, frame_windows, size_targets_present, stack_windows
from src.splits import (
    LeakageError,
    add_previous_frame_id,
    assert_no_forbidden_inputs,
    assign_storms,
    null_cross_split_links,
    storm_ids_by_split,
)

SMOKE_BANNER = (
    "Checkpoint was fit on synthetic smoke data. "
    "Metrics from it are a software check. Do not report them as skill."
)
NOT_A_FORECAST = (
    "This checkpoint is not a forecast or a warning. "
    "Agreement with a best track is not ground truth."
)
class EarlyStopping:
    """Stop after ``patience`` validation checks without an improvement."""

    def __init__(self, patience: int) -> None:
        if patience < 1:
            raise ValueError("patience must be at least 1")
        self.patience = patience
        self.best = float("inf")
        self.waits = 0
        self.best_state: dict | None = None

    def update(self, metric: float, state: dict) -> bool:
        """Return True when training should stop. Lower metric is better."""
        if metric < self.best:
            self.best = float(metric)
            self.waits = 0
            self.best_state = copy.deepcopy(state)
            return False
        self.waits += 1
        return self.waits >= self.patience


def assert_model_inputs(names: list[str] | tuple[str, ...]) -> None:
    """Images are the model input. Wind, size, and class labels are not."""
    assert_no_forbidden_inputs(names, "forbidden model inputs")


def class_sample_weights(
    class_names: list[str | None], known: list[str]
) -> tuple[np.ndarray, np.ndarray]:
    """Inverse-frequency weights fit on this list only.

    ``class_weight`` lines up with ``known``. A class that does not appear
    gets weight 0. A row with no project class gets sample weight 1.
    """
    counts = np.array(
        [sum(name == item for item in class_names) for name in known], dtype=np.float64
    )
    present = counts > 0
    class_weight = np.zeros(len(known), dtype=np.float64)
    if present.any():
        class_weight[present] = counts[present].sum() / (present.sum() * counts[present])
    index = {name: position for position, name in enumerate(known)}
    sample = np.ones(len(class_names), dtype=np.float64)
    for row, name in enumerate(class_names):
        if name in index and class_weight[index[name]] > 0:
            sample[row] = class_weight[index[name]]
    return sample, class_weight


LOSS_WEIGHTINGS = ("none", "inverse_freq", "sqrt_inverse_freq")


def loss_weighting_mode(value: object) -> str:
    """``train.loss_weighting``. The default ``none`` leaves the wind loss unweighted."""
    if value is None or (isinstance(value, str) and value.strip().lower() in {"", "null", "none"}):
        return "none"
    text = str(value).strip().lower()
    if text not in LOSS_WEIGHTINGS:
        raise ValueError("train.loss_weighting must be none, inverse_freq, or sqrt_inverse_freq")
    return text


def config_flag(value: object, name: str) -> bool:
    """YAML bool. Strings ``true`` and ``false`` are accepted. Anything else raises."""
    if isinstance(value, (bool, np.bool_)):
        return bool(value)
    if value is None or (isinstance(value, str) and not value.strip()):
        return False
    text = str(value).strip().lower()
    if text in {"1", "true", "yes", "y", "t"}:
        return True
    if text in {"0", "false", "no", "n", "f"}:
        return False
    raise ValueError(f"{name} must be true or false")


def frequency_rows(frame: pd.DataFrame) -> tuple[pd.DataFrame, str]:
    """Rows that define intensity-bin frequencies.

    Only the assigned train split is used. Synthetic copies are excluded
    when that split also has original frames, so a ``rot_180`` duplicate
    cannot change the weight. Val and test never contribute, including
    under ``storm_cv`` (the val fold is already ``split == val``). A train
    split whose every row is synthetic, which is the smoke manifest, uses
    those rows because there is no original frame to count.
    """
    if "split" not in frame.columns:
        raise LeakageError("intensity weights need an assigned split")
    train = frame.loc[frame["split"].astype(str) == "train"].copy()
    if train.empty:
        raise LeakageError("intensity weights need train rows")
    note = "train originals; synthetic copies, val, and test are excluded"
    if "is_synthetic" not in train.columns:
        return train.reset_index(drop=True), note
    flags = [parse_is_synthetic(value) for value in train["is_synthetic"].tolist()]
    originals = train.loc[[not flag for flag in flags]]
    if originals.empty:
        return (
            train.reset_index(drop=True),
            "train rows; every train row is synthetic, so no original frame was excluded",
        )
    return originals.reset_index(drop=True), note


def _bin_weight_table(counts: dict[str, int], mode: str) -> dict[str, float | None]:
    """Per-bin weight. A bin with no train originals stays null.

    ``inverse_freq`` is ``n / (k * count)`` over bins that occur, the same
    shape as the class weights above, so the count-weighted mean is 1.
    ``sqrt_inverse_freq`` is the square root of that weight. ``none`` is 1
    on bins that occur and is not applied to the loss.
    """
    choice = loss_weighting_mode(mode)
    present = {name: int(count) for name, count in counts.items() if int(count) > 0}
    total = float(sum(present.values()))
    n_present = len(present)
    weights: dict[str, float | None] = {}
    for name, count in counts.items():
        count = int(count)
        if count <= 0:
            weights[name] = None
            continue
        if choice == "none":
            weights[name] = 1.0
            continue
        base = total / (n_present * float(count))
        if choice == "inverse_freq":
            weights[name] = float(base)
        else:
            weights[name] = float(np.sqrt(base))
    return weights


def intensity_balance(frame: pd.DataFrame, config: dict, wind_column: str) -> dict:
    """Train-only bin counts and the weights the run will record.

    Sampling, when enabled, draws with the inverse-frequency weights so
    each occurring bin has the same expected count. That table is separate
    from ``sqrt_inverse_freq`` loss weights.
    """
    train_cfg = config.get("train") if isinstance(config.get("train"), dict) else {}
    mode = loss_weighting_mode(train_cfg.get("loss_weighting", "none"))
    balanced = config_flag(train_cfg.get("balanced_sampling", False), "train.balanced_sampling")
    rows, note = frequency_rows(frame)
    names = [str(name) for name in config["data"]["imd5_names"]]
    labels = project_labels(rows, config, wind_column)
    counts = {name: 0 for name in names}
    for label in labels:
        if label in counts:
            counts[label] += 1
    return {
        "loss_weighting": mode,
        "balanced_sampling": balanced,
        "source": note,
        "split_strategy": str((config.get("split") or {}).get("strategy", "")),
        "wind_column": str(wind_column),
        "n_frequency_rows": int(len(rows)),
        "n_below_lowest_edge": int(sum(label not in counts for label in labels)),
        "counts": counts,
        "weights": _bin_weight_table(counts, mode),
        "sampling_weights": _bin_weight_table(counts, "inverse_freq") if balanced else None,
    }


def align_bin_weights(
    labels: list, table: dict[str, float | None] | None, *, neutral: float = 1.0
) -> np.ndarray:
    """One weight per row. A missing bin, or a row below 17 kt, stays neutral."""
    if table is None:
        return np.ones(len(labels), dtype=np.float64)
    out = np.empty(len(labels), dtype=np.float64)
    for index, label in enumerate(labels):
        weight = None if label is None else table.get(str(label))
        out[index] = float(neutral if weight is None else weight)
    return out


def annotate_balance(frame: pd.DataFrame, balance: dict, config: dict) -> pd.DataFrame:
    """Record the project bin and the loss weight on every row.

    Val and test stay at weight 1. They are not in the frequency table.
    ``none`` writes 1 on every row and the training loop does not weight
    the loss.
    """
    out = frame.copy()
    labels = project_labels(out, config, str(balance["wind_column"]))
    out["intensity_bin"] = ["" if label is None else str(label) for label in labels]
    if balance["loss_weighting"] == "none":
        out["loss_weight"] = np.ones(len(out), dtype=np.float64)
        return out
    weights = align_bin_weights(labels, balance["weights"])
    train = out["split"].astype(str).eq("train").to_numpy()
    applied = np.ones(len(out), dtype=np.float64)
    applied[train] = weights[train]
    out["loss_weight"] = applied
    return out


def balance_record(balance: dict) -> dict:
    """JSON-safe copy of the weight table for the run manifest."""

    def _weights(table: dict | None) -> dict | None:
        if table is None:
            return None
        return {str(name): None if value is None else float(value) for name, value in table.items()}

    return {
        "loss_weighting": balance["loss_weighting"],
        "balanced_sampling": bool(balance["balanced_sampling"]),
        "source": balance["source"],
        "split_strategy": balance["split_strategy"],
        "wind_column": balance["wind_column"],
        "n_frequency_rows": int(balance["n_frequency_rows"]),
        "n_below_lowest_edge": int(balance["n_below_lowest_edge"]),
        "counts": {str(name): int(count) for name, count in balance["counts"].items()},
        "weights": _weights(balance["weights"]),
        "sampling_weights": _weights(balance["sampling_weights"]),
    }


def is_on_fix(value: object) -> bool:
    """True only when the flag is explicitly true. Unknown is not on-fix."""
    if isinstance(value, (bool, np.bool_)):
        return bool(value)
    if value is None or value is pd.NA:
        return False
    try:
        missing = pd.isna(value)
    except (TypeError, ValueError):
        missing = False
    if isinstance(missing, (bool, np.bool_)) and bool(missing):
        return False
    return str(value).strip().lower() in {"1", "true", "yes", "y", "t"}


def on_fix_metrics(
    truth: np.ndarray, pred: np.ndarray, flags, config: dict
) -> dict:
    """Validation metrics on explicit on-fix rows. Unknown rows stay out."""
    mask = np.asarray([is_on_fix(value) for value in list(flags)], dtype=bool)
    truth_arr = np.asarray(truth, dtype=np.float64).reshape(-1)
    pred_arr = np.asarray(pred, dtype=np.float64).reshape(-1)
    if mask.shape[0] != truth_arr.shape[0] or pred_arr.shape[0] != truth_arr.shape[0]:
        raise ValueError("on_fix flags must align with the validation rows")
    return _score_split(truth_arr[mask], pred_arr[mask], config)


def project_labels(
    frame: pd.DataFrame, config: dict, wind_column: str = "wind_speed_kt"
) -> list[str | None]:
    """Project class names, only when one wind-averaging period is recorded.

    These names are the project's grouping, not official IMD classes.
    A missing or mixed period raises instead of leaving the names blank.
    ``wind_column`` is the training target. INCYDE's own IMD class is the
    ``imd_class`` column, computed on the 3-minute label.
    """
    recorded_wind_averaging(frame)
    edges = tuple(float(edge) for edge in config["data"]["imd5_edges_kt"])
    names = tuple(str(name) for name in config["data"]["imd5_names"])
    return [
        wind_to_imd5(float(wind), edges, names) for wind in frame[wind_column]
    ]


def manifest_is_synthetic(frame: pd.DataFrame) -> bool:
    """True when any row is explicitly synthetic.

    A missing column or a null flag raises. Null is not treated as real,
    and one synthetic row keeps the whole manifest marked synthetic.
    """
    if "is_synthetic" not in frame.columns:
        raise SchemaError(
            "is_synthetic is required so a synthetic row cannot be read as real"
        )
    flags = [parse_is_synthetic(value) for value in frame["is_synthetic"].tolist()]
    return any(flags)


_TRAIN_KEYS = (
    "batch_size",
    "epochs",
    "lr",
    "weight_decay",
    "patience",
    "class_loss_weight",
    "size_loss_weight",
    "grad_accum_steps",
    "num_workers",
    "device_parity_tol",
)

LAST_CHECKPOINT = "last.pt"


def _require_train_block(config: dict) -> dict:
    train_cfg = config.get("train")
    if not isinstance(train_cfg, dict):
        raise ValueError("config train is required")
    missing = [key for key in _TRAIN_KEYS if key not in train_cfg]
    if missing:
        raise ValueError(f"config train missing {missing}")
    return train_cfg


def assert_normalize(config: dict) -> None:
    """The deep path standardizes with train-split mean and std."""
    mode = config["data"]["normalize"]
    if str(mode) != "zscore":
        raise ValueError("data.normalize must be zscore")


def recorded_wind_period(frame: pd.DataFrame) -> str | None:
    """The single ``wind_averaging`` value on a manifest, if the column exists."""
    if "wind_averaging" not in frame.columns:
        return None
    periods = sorted({str(value) for value in frame["wind_averaging"].dropna().unique()})
    if len(periods) != 1:
        return None
    return periods[0]


def assert_wind_averaging(config: dict, frame: pd.DataFrame) -> str | None:
    """Require ``data.wind_averaging`` and refuse a manifest that disagrees.

    A manifest with no period column does not inherit the config value.
    Project class names stay off until the column records one period.
    """
    declared = config["data"]["wind_averaging"]
    if declared is None or str(declared).strip() == "":
        raise ValueError("config data.wind_averaging is required")
    declared_text = str(declared)
    observed = recorded_wind_period(frame)
    if observed is not None and observed != declared_text:
        raise ValueError(
            f"manifest wind_averaging is {observed} but config data.wind_averaging "
            f"is {declared_text}. Do not mix averaging periods."
        )
    return observed


def split_frame(frame: pd.DataFrame, config: dict) -> pd.DataFrame:
    split_cfg = config["split"]
    holdout_years = split_cfg["holdout_years"] or []
    holdout_basin = split_cfg["holdout_basin"] or None
    assigned = assign_storms(
        frame,
        str(split_cfg["strategy"]),
        test_fraction=float(split_cfg["test_fraction"]),
        val_fraction=float(split_cfg["val_fraction"]),
        seed=int(split_cfg["seed"]),
        holdout_years=[int(year) for year in holdout_years],
        holdout_basin=None if holdout_basin in (None, "null", "") else str(holdout_basin),
    )
    if "prev_sample_id" not in assigned.columns:
        assigned = add_previous_frame_id(assigned)
    assigned, _dropped = null_cross_split_links(assigned)
    return assigned


def stack_split(
    frame: pd.DataFrame,
    manifest_path: Path,
    split_name: str,
    image_size: int | str | None,
    stats: NormStats | None,
    max_missing_fraction: float,
) -> tuple[np.ndarray, np.ndarray, list[str | None]]:
    rows = frame[frame["split"] == split_name].reset_index(drop=True)
    if rows.empty:
        raise ValueError(f"split {split_name} has no rows")
    labels = [None if pd.isna(value) else str(value) for value in rows["_class"]]
    images = []
    winds = []
    for row in rows.itertuples(index=False):
        path = resolve_image(manifest_path, row.image_path)
        images.append(
            prepare_image(load_image(path), image_size, stats, max_missing_fraction)
        )
        winds.append(float(row.wind_speed_kt))
    return stack_prepared(images), np.asarray(winds, dtype=np.float32), labels


def _set_seed(seed: int) -> None:
    random.seed(seed)
    np.random.seed(seed)
    torch = _torch()
    torch.manual_seed(seed)


def _torch():
    import torch

    return torch


def build_loader(
    dataset, *, batch_size: int, shuffle: bool, num_workers: int, generator=None, sampler=None
):
    """DataLoader with ``persistent_workers`` whenever workers are used.

    ``num_workers`` comes from ``train.num_workers``. Zero workers load in
    the parent process and do not set ``persistent_workers``. A balanced
    sampler replaces shuffle. The sampler carries its own generator.
    """
    from torch.utils.data import DataLoader

    workers = int(num_workers)
    if workers < 0:
        raise ValueError("train.num_workers must be >= 0")
    if sampler is not None and shuffle:
        raise ValueError("balanced sampling does not also shuffle the loader")
    kwargs = {
        "batch_size": int(batch_size),
        "shuffle": bool(shuffle) if sampler is None else False,
        "num_workers": workers,
    }
    if sampler is not None:
        kwargs["sampler"] = sampler
    elif generator is not None:
        kwargs["generator"] = generator
    if workers > 0:
        kwargs["persistent_workers"] = True
    return DataLoader(dataset, **kwargs)


def make_balanced_sampler(weights: np.ndarray, num_samples: int, seed: int):
    """Draw with replacement so every positive-weight bin can appear.

    ``num_samples`` is one epoch. Weights are the inverse-frequency table
    from the train originals. A zero-sum table is refused.
    """
    torch = _torch()
    from torch.utils.data import WeightedRandomSampler

    values = np.asarray(weights, dtype=np.float64).reshape(-1)
    if values.size == 0 or not np.isfinite(values).all() or np.any(values < 0):
        raise ValueError("balanced sampling weights must be finite and non-negative")
    if float(values.sum()) <= 0:
        raise ValueError("balanced sampling weights must have a positive sum")
    generator = torch.Generator()
    generator.manual_seed(int(seed))
    return WeightedRandomSampler(
        weights=torch.as_tensor(values, dtype=torch.double),
        num_samples=int(num_samples),
        replacement=True,
        generator=generator,
    )


class ArrayFrames:
    """In-memory frames. Module-level so Windows workers can unpickle it."""

    def __init__(self, images, winds, labels, known: list[str], sample_weight, size=None) -> None:
        torch = _torch()
        index = {name: position for position, name in enumerate(known)}
        class_index = [index.get(label, -1) if label is not None else -1 for label in labels]
        self.images = torch.from_numpy(np.ascontiguousarray(images))
        self.winds = torch.from_numpy(np.asarray(winds, dtype=np.float32)).view(-1, 1)
        self.class_index = torch.tensor(class_index, dtype=torch.long)
        self.sample_weight = torch.tensor(np.asarray(sample_weight), dtype=torch.float32)
        self.size = None if size is None else torch.tensor(np.asarray(size), dtype=torch.float32)

    def __len__(self) -> int:
        return int(self.images.shape[0])

    def __getitem__(self, item: int):
        row = (
            self.images[item],
            self.winds[item],
            self.class_index[item],
            self.sample_weight[item],
        )
        if self.size is None:
            return row
        return row + (self.size[item],)


class PathFrames:
    """Load one frame per item so DataLoader workers stay on small files.

    A cache path is an fp16 ``.npy``. A source path is whatever the
    manifest already pointed at. Normalization uses the train-split stats
    for this dataset only.
    """

    def __init__(
        self,
        records: list[dict],
        image_size: int | None,
        mean: float | None,
        std: float | None,
        max_missing: float,
        known: list[str],
    ) -> None:
        self.records = list(records)
        self.image_size = image_size
        self.mean = None if mean is None else float(mean)
        self.std = None if std is None else float(std)
        self.max_missing = float(max_missing)
        self.known = list(known)
        self._index = {name: position for position, name in enumerate(known)}

    def __len__(self) -> int:
        return len(self.records)

    def __getitem__(self, item: int):
        torch = _torch()
        row = self.records[item]
        stats = None
        if self.mean is not None and self.std is not None:
            stats = NormStats(mean=self.mean, std=self.std, source_split="train")
        image = load_image(row["path"])
        angle = row.get("angle")
        if angle is not None and pd.isna(angle):
            angle = None
        image = prepare_training_chip(image, self.image_size, angle, stats, self.max_missing)
        label = row["label"]
        class_index = self._index.get(label, -1) if label is not None else -1
        return (
            torch.from_numpy(np.ascontiguousarray(image)),
            torch.tensor([float(row["wind"])], dtype=torch.float32),
            torch.tensor(class_index, dtype=torch.long),
            torch.tensor(float(row["weight"]), dtype=torch.float32),
        )


def uses_sequences(config: dict) -> bool:
    return str(config["model"]["name"]) == "convlstm"


def train_size_head(frame: pd.DataFrame) -> bool:
    """Turn the size head on only when the train split has size labels."""
    rows = frame[frame["split"] == "train"] if "split" in frame.columns else frame
    return size_targets_present(rows)


def model_n_frames(config: dict) -> int:
    if not uses_sequences(config):
        return 1
    requested = int(config["model"]["n_frames"])
    if requested != N_FRAMES:
        raise ValueError(f"ConvLSTM uses {N_FRAMES} frames")
    return requested


def build_backbone(config: dict):
    """Build the image backbone. Refuses an ImageNet download by default."""
    from src.model import ConvLSTMRegressor, ResNetRegressor, SimpleCNN

    model_cfg = config["model"]
    pretrained = bool(model_cfg["pretrained"])
    if pretrained and os.environ.get("CLOUDIE_ALLOW_PRETRAINED") != "1":
        raise RuntimeError(
            "pretrained: true downloads ImageNet weights and must not run in CI. "
            "Set CLOUDIE_ALLOW_PRETRAINED=1 only for a local run that intends the download."
        )
    name = str(model_cfg["name"])
    dropout = float(model_cfg["dropout"])
    channels = int(config["data"]["channels"])
    if name == "simple_cnn":
        return SimpleCNN(in_channels=channels, dropout=dropout)
    if name == "resnet18":
        return ResNetRegressor(in_channels=channels, pretrained=pretrained, dropout=dropout)
    if name == "convlstm":
        return ConvLSTMRegressor(
            in_channels=channels,
            hidden=int(model_cfg["hidden"]),
            n_frames=model_n_frames(config),
            dropout=dropout,
        )
    raise ValueError(f"unknown model {name}")


def build_net(config: dict, size_head: bool = False):
    """Wind and class heads. The size head exists only when labels do.

    The size head reads image features. It does not take wind speed.
    """
    torch = _torch()
    from torch import nn

    backbone = build_backbone(config)
    n_classes = len(config["data"]["imd5_names"])

    class _Net(nn.Module):
        def __init__(self) -> None:
            super().__init__()
            self.backbone = backbone
            self.class_head = nn.Linear(int(backbone.feature_dim), n_classes)
            self.size_head = (
                nn.Linear(int(backbone.feature_dim), 2) if size_head else None
            )

        def forward(self, inputs: torch.Tensor):
            features = self.backbone.encode(inputs)
            wind = self.backbone.head(features)
            logits = self.class_head(features)
            if self.size_head is None:
                return wind, logits
            return wind, logits, self.size_head(features)

    return _Net()


def _wind_loss(prediction, target, sample_weight):
    import torch.nn.functional as F

    per_row = F.smooth_l1_loss(prediction.view(-1), target.view(-1), reduction="none")
    if sample_weight is None:
        return per_row.mean()
    weight = sample_weight.view(-1)
    return (per_row * weight).sum() / weight.sum().clamp_min(1e-8)


def batch_wind_loss(prediction, target, sample_weight, loss_weighting: str):
    """Smooth L1 for one batch.

    ``none`` is the unweighted mean, including when the rows carry a
    weight column. Other modes use that column. The mean of the weighted
    terms is divided by the weight sum, not by the row count.
    """
    import torch.nn.functional as F

    per_row = F.smooth_l1_loss(prediction.reshape(-1), target.reshape(-1), reduction="none")
    if loss_weighting_mode(loss_weighting) == "none" or sample_weight is None:
        return per_row.mean()
    weight = sample_weight.reshape(-1)
    return (per_row * weight).sum() / weight.sum().clamp_min(1e-8)


def _class_loss(logits, class_index, class_weight):
    import torch.nn.functional as F

    mask = class_index >= 0
    if int(mask.sum()) == 0:
        return logits.sum() * 0.0
    return F.cross_entropy(logits[mask], class_index[mask], weight=class_weight)


def _size_loss(prediction, target):
    """Smooth L1 on finite R34 and RMW pairs. No term when none are finite."""
    import torch
    import torch.nn.functional as F

    finite = torch.isfinite(target).all(dim=1)
    if int(finite.sum()) == 0:
        return prediction.sum() * 0.0
    return F.smooth_l1_loss(prediction[finite], target[finite])


def _split_output(output):
    if isinstance(output, tuple) and len(output) == 3:
        return output[0], output[1], output[2]
    wind, logits = output
    return wind, logits, None


def _run_epoch(
    model,
    loader,
    optimizer,
    class_weight,
    class_loss_weight: float,
    train: bool,
    size_loss_weight: float = 0.0,
    grad_accum_steps: int = 1,
):
    torch = _torch()
    accum = int(grad_accum_steps)
    if accum < 1:
        raise ValueError("train.grad_accum_steps must be at least 1")
    model.train(train)
    total = 0.0
    count = 0
    pending = 0
    if train:
        optimizer.zero_grad(set_to_none=True)
    for batch in loader:
        images, winds, class_index, sample_weight = batch[0], batch[1], batch[2], batch[3]
        size_target = batch[4] if len(batch) > 4 else None
        with torch.set_grad_enabled(train):
            wind_hat, logits, size_hat = _split_output(model(images))
            monitor = _wind_loss(wind_hat, winds, None)
            loss = _wind_loss(wind_hat, winds, sample_weight) if train else monitor
            if train and class_loss_weight > 0:
                loss = loss + class_loss_weight * _class_loss(logits, class_index, class_weight)
            if (
                train
                and size_hat is not None
                and size_target is not None
                and size_loss_weight > 0
            ):
                loss = loss + size_loss_weight * _size_loss(size_hat, size_target)
            if train:
                (loss / accum).backward()
                pending += 1
                if pending == accum:
                    optimizer.step()
                    optimizer.zero_grad(set_to_none=True)
                    pending = 0
        batch_rows = int(images.shape[0])
        total += float(monitor.detach()) * batch_rows
        count += batch_rows
    if train and pending:
        optimizer.step()
        optimizer.zero_grad(set_to_none=True)
    if count == 0:
        raise ValueError("loader produced no rows")
    return total / count


def _dataset(
    images,
    winds,
    labels,
    known: list[str],
    sample_weight: np.ndarray,
    size: np.ndarray | None = None,
):
    return ArrayFrames(images, winds, labels, known, sample_weight, size)


def _aligned_size(frame: pd.DataFrame, split_name: str) -> np.ndarray:
    rows = frame[frame["split"] == split_name].reset_index(drop=True)
    values = rows[["r34_nmi", "rmw_nmi"]].apply(pd.to_numeric, errors="coerce")
    return values.to_numpy(dtype=np.float32)


def _load_examples(
    config: dict,
    frame: pd.DataFrame,
    manifest: Path,
    split_name: str,
    stats: NormStats | None,
    size_head: bool,
):
    image_size = parse_image_size(config["data"]["image_size"])
    max_missing = float(config["data"]["max_missing_fraction"])
    wind_column = config.get("labels", {}).get("label_column", "wind_speed_kt")
    if wind_column not in frame.columns:
        wind_column = "wind_speed_kt"
    if uses_sequences(config):
        images, winds, labels, size = stack_windows(
            frame,
            manifest,
            split_name,
            image_size,
            stats,
            max_missing,
            model_n_frames(config),
            wind_column=wind_column,
        )
        return images, winds, labels, size if size_head else None
    images, winds, labels = stack_split(
        frame, manifest, split_name, image_size, stats, max_missing
    )
    size = _aligned_size(frame, split_name) if size_head else None
    return images, winds, labels, size


def fit_split_normalization(
    frame: pd.DataFrame, manifest: str | Path, config: dict
) -> NormStats:
    """Fit pixel mean and std on the train split only.

    The images are the train split. ``data.image_size`` comes from config.
    ``native`` keeps each chip's height and width.
    A later held-out coverage check reuses ``storm_ids_by_split`` and these
    stored stats.
    """
    groups = storm_ids_by_split(frame)
    if not groups["train"]:
        raise LeakageError("normalization stats may be fit on the train split only")
    if uses_sequences(config):
        raw_images, _winds, _labels, _size = _load_examples(
            config, frame, Path(manifest), "train", None, False
        )
        norm_frames = [
            raw_images[index, step]
            for index in range(raw_images.shape[0])
            for step in range(raw_images.shape[1])
        ]
        return fit_norm_stats(norm_frames, "train")

    image_size = parse_image_size(config["data"]["image_size"])
    max_missing = float(config["data"]["max_missing_fraction"])
    rows = frame[frame["split"] == "train"]
    if rows.empty:
        raise LeakageError("normalization stats may be fit on the train split only")
    manifest_path = Path(manifest)
    count = 0
    total = 0.0
    total_sq = 0.0
    for row in rows.itertuples(index=False):
        path = resolve_image(manifest_path, row.image_path)
        img = prepare_image(load_image(path), image_size, None, max_missing)
        finite = img[np.isfinite(img)]
        if finite.size > 0:
            finite64 = finite.astype(np.float64, copy=False)
            count += int(finite64.size)
            total += float(finite64.sum())
            total_sq += float((finite64 * finite64).sum())
    if count == 0:
        raise ValueError("train images have no finite pixels")
    mean = float(total / count)
    var = max(0.0, float((total_sq / count) - (mean ** 2)))
    std = float(np.sqrt(var))
    if std < 1e-6:
        std = 1.0
    return NormStats(mean=mean, std=std, source_split="train")


def train(config: dict, manifest_path: str | Path | None = None) -> Path:
    """Fit on the train split and write the checkpoint named in ``paths``."""
    assert_model_inputs(("image",))
    train_cfg = _require_train_block(config)
    assert_normalize(config)
    manifest = Path(manifest_path or config["paths"]["manifest"])
    frame = load_manifest(manifest)
    wind_period = assert_wind_averaging(config, frame)
    torch = _torch()

    seed = int(config["project"]["seed"])
    _set_seed(seed)
    synthetic = manifest_is_synthetic(frame)
    assigned = split_frame(frame, config)
    assigned["_class"] = project_labels(assigned, config)
    image_size = parse_image_size(config["data"]["image_size"])
    max_missing = float(config["data"]["max_missing_fraction"])
    # Size labels are a training-fold decision, same as class weights.
    size_head = train_size_head(assigned)
    n_frames = model_n_frames(config)
    stats = fit_split_normalization(assigned, manifest, config)
    train_images, train_winds, train_labels, train_size = _load_examples(
        config, assigned, manifest, "train", stats, size_head
    )
    val_images, val_winds, val_labels, val_size = _load_examples(
        config, assigned, manifest, "val", stats, size_head
    )
    known = [str(name) for name in config["data"]["imd5_names"]]
    sample_weight, class_weight_np = class_sample_weights(train_labels, known)
    # Validation uses weight 1. The class weights stay the train fold's.
    val_weight = np.ones(len(val_labels), dtype=np.float64)
    batch_size = int(train_cfg["batch_size"])
    workers = int(train_cfg["num_workers"])
    grad_accum_steps = int(train_cfg["grad_accum_steps"])
    generator = torch.Generator()
    generator.manual_seed(seed)
    train_loader = build_loader(
        _dataset(train_images, train_winds, train_labels, known, sample_weight, train_size),
        batch_size=batch_size,
        shuffle=True,
        num_workers=workers,
        generator=generator,
    )
    val_loader = build_loader(
        _dataset(val_images, val_winds, val_labels, known, val_weight, val_size),
        batch_size=batch_size,
        shuffle=False,
        num_workers=workers,
    )
    model = build_net(config, size_head=size_head)
    optimizer = torch.optim.AdamW(
        model.parameters(),
        lr=float(train_cfg["lr"]),
        weight_decay=float(train_cfg["weight_decay"]),
    )
    class_weight = torch.tensor(class_weight_np, dtype=torch.float32)
    class_loss_weight = float(train_cfg["class_loss_weight"])
    size_loss_weight = float(train_cfg["size_loss_weight"]) if size_head else 0.0
    stopper = EarlyStopping(int(train_cfg["patience"]))
    epochs = int(train_cfg["epochs"])
    last_epoch = 0
    for epoch in range(epochs):
        last_epoch = epoch
        _run_epoch(
            model,
            train_loader,
            optimizer,
            class_weight,
            class_loss_weight,
            True,
            size_loss_weight,
            grad_accum_steps,
        )
        val_loss = _run_epoch(
            model,
            val_loader,
            optimizer,
            class_weight,
            class_loss_weight,
            False,
            size_loss_weight,
        )
        if not np.isfinite(val_loss):
            raise RuntimeError("validation loss is not finite")
        if stopper.update(val_loss, model.state_dict()):
            break
    if stopper.best_state is None:
        raise RuntimeError("training produced no validation score")
    model.load_state_dict(stopper.best_state)
    checkpoint = checkpoint_path(config)
    checkpoint.parent.mkdir(parents=True, exist_ok=True)
    dataset_name = str(config["data"]["dataset"])
    payload = {
        "state_dict": {key: value.detach().cpu() for key, value in model.state_dict().items()},
        "model_name": str(config["model"]["name"]),
        "dropout": float(config["model"]["dropout"]),
        "pretrained": False,
        "in_channels": int(config["data"]["channels"]),
        "n_classes": len(known),
        "class_names": known,
        "edges_kt": [float(edge) for edge in config["data"]["imd5_edges_kt"]],
        "norm_mean": stats.mean,
        "norm_std": stats.std,
        "norm_source_split": stats.source_split,
        "norm_by_dataset": norm_by_dataset(dataset_name, stats),
        "dataset": dataset_name,
        "image_size": image_size,
        "max_missing_fraction": max_missing,
        "mean_baseline_kt": float(
            np.mean(
                assigned.loc[assigned["split"] == "train", "wind_speed_kt"].to_numpy(
                    dtype=np.float64
                )
            )
        ),
        "is_synthetic": synthetic,
        "wind_averaging": wind_period,
        "wind_averaging_s": wind_averaging_seconds(wind_period),
        "wind_averaging_by_split": split_wind_averaging(assigned),
        "split": {
            "strategy": str(config["split"]["strategy"]),
            "seed": int(config["split"]["seed"]),
            "test_fraction": float(config["split"]["test_fraction"]),
            "val_fraction": float(config["split"]["val_fraction"]),
        },
        "best_val_loss": stopper.best,
        "epoch": last_epoch,
        "present_as_forecast": False,
        "honesty": SMOKE_BANNER if synthetic else NOT_A_FORECAST,
        "n_frames": n_frames,
        "size_head": size_head,
        "hidden": int(config["model"]["hidden"]) if uses_sequences(config) else None,
    }
    torch.save(payload, checkpoint)
    if synthetic:
        print(SMOKE_BANNER)
    else:
        print(NOT_A_FORECAST)
    print(f"Wrote {checkpoint}")
    return checkpoint


LOGGER = logging.getLogger("src.train")

# CLI names. simplecnn is the YAML name simple_cnn.
_CLI_MODELS = {
    "simplecnn": "simple_cnn",
    "simple_cnn": "simple_cnn",
    "resnet18": "resnet18",
    "convlstm": "convlstm",
}
_DATASETS = ("nasa", "tcir", "incyde", "smoke")
RUN_FILES = (
    "checkpoint",
    "resolved_config.yaml",
    "split_manifest.csv",
    "loss_curve.csv",
    "loss_curve.png",
    "metrics.json",
)


def canonical_model_name(name: str) -> str:
    """Map the CLI model name onto ``model.name`` in the YAML."""
    key = str(name).strip().lower()
    if key not in _CLI_MODELS:
        raise ValueError("model must be simplecnn, resnet18, or convlstm")
    return _CLI_MODELS[key]


def refuse_mixed_resolution(
    frame: pd.DataFrame, dataset: str, image_size: int | None = None
) -> None:
    """One dataset, one source resolution. NASA and TCIR stay in separate runs.

    INCYDE crops are not one native size. A configured square resize is the
    training grid. ``native`` still refuses a mix.
    """
    if frame.empty:
        raise ValueError(f"{dataset} frame has no rows")
    sizes: set[int] = set()
    if "orig_size" in frame.columns:
        sizes = {int(value) for value in frame["orig_size"].tolist()}
    elif {"native_height", "native_width"} <= set(frame.columns):
        sizes = {
            int(height) if int(height) == int(width) else -1
            for height, width in zip(frame["native_height"], frame["native_width"], strict=True)
        }
    if dataset == "incyde":
        if {"native_height", "native_width"} <= set(frame.columns):
            shapes = {
                (int(height), int(width))
                for height, width in zip(
                    frame["native_height"], frame["native_width"], strict=True
                )
            }
        else:
            shapes = {(int(value), int(value)) for value in sizes}
        if len(shapes) > 1 and image_size is None:
            raise ValueError(
                "INCYDE frames mix native sizes "
                f"{sorted(shapes)} and data.image_size is native. "
                "Set a square image_size so corner bars are not a second grid."
            )
        return
    if len(sizes) > 1:
        raise ValueError(
            f"refusing a {dataset} batch that mixes resolutions {sorted(sizes)}. "
            "NASA and TCIR runs stay separate."
        )
    if dataset == "nasa" and sizes:
        from src.nasa_tc import WORKING_SIZE

        if sizes != {int(WORKING_SIZE)}:
            raise ValueError(
                f"NASA phase 1 keeps only {int(WORKING_SIZE)}x{int(WORKING_SIZE)} frames, got {sorted(sizes)}"
            )
    if dataset == "tcir" and sizes:
        from src.tcir import IMAGE_SIZE

        if sizes != {int(IMAGE_SIZE)}:
            raise ValueError(f"TCIR frames must stay {int(IMAGE_SIZE)}x{int(IMAGE_SIZE)}, got {sorted(sizes)}")


def _log_excluded(dataset: str, count: int, detail: str) -> None:
    message = f"{dataset} excluded {int(count)} frames ({detail})"
    LOGGER.info(message)
    print(message)


def _absolute_image_paths(frame: pd.DataFrame, base: Path) -> pd.DataFrame:
    out = frame.copy()
    paths: list[str] = []
    for image_path in out["image_path"].tolist():
        path = Path(str(image_path))
        if not path.is_absolute():
            path = base / path
        paths.append(path.resolve().as_posix())
    out["image_path"] = paths
    return out


def load_nasa_frame(config: dict) -> tuple[pd.DataFrame, int]:
    """NASA manifest for both official sides. ``source_split`` is not the split.

    Phase 1 keeps ``orig_size`` 366 only. Colour frames and any other size
    are excluded, and the excluded count is logged. Nothing is downloaded.
    NASA has no IBTrACS join key, so ``near_land`` stays unknown. See
    ``nasa_tc/audit/README.md``.
    """
    from src.nasa_tc import WORKING_SIZE, build_manifest, csv_tables, exclusions_for, split_exclusions
    from src.schema import require_valid

    root = Path(config["paths"]["nasa_root"])
    if not root.is_dir():
        raise FileNotFoundError(
            f"NASA root {root} is missing. Set paths.nasa_root in the YAML. "
            "This entrypoint does not download imagery."
        )
    raw = build_manifest(root, root, tables=csv_tables, keep_excluded=True)
    colour = exclusions_for(raw)
    kept, _dropped = split_exclusions(raw)
    if "orig_size" not in kept.columns:
        raise ValueError("NASA manifest is missing orig_size")
    if "split" in kept.columns:
        raise LeakageError("NASA manifest must not carry split; source_split holds the official side")
    size_ok = kept["orig_size"].astype(int) == int(WORKING_SIZE)
    size_excluded = int((~size_ok).sum())
    frame = require_valid(kept.loc[size_ok].reset_index(drop=True))
    excluded = int(len(colour)) + size_excluded
    _log_excluded(
        "nasa",
        excluded,
        f"{int(len(colour))} colour, {size_excluded} not {int(WORKING_SIZE)}x{int(WORKING_SIZE)}",
    )
    if "source_split" not in frame.columns:
        raise LeakageError("NASA manifest must keep the official side in source_split")
    refuse_mixed_resolution(frame, "nasa")
    return _absolute_image_paths(frame, root), excluded


def load_tcir_frame(config: dict) -> tuple[pd.DataFrame, int]:
    """TCIR IR1 manifest. There is no official split inside the HDF5 files.

    ``assign_storms`` writes ``split``. Excluded IR1 frames are logged.
    This entrypoint does not download TCIR.
    """
    from src.tcir import IMAGE_SIZE, build_manifest

    files = config["paths"]["tcir_files"]
    if not isinstance(files, list) or not files:
        raise ValueError(
            "paths.tcir_files must list TCIR HDF5 paths. This entrypoint does not download TCIR."
        )
    manifest_dir = Path(config["paths"]["tcir_manifest_dir"])
    frame, excluded, _pixel = build_manifest(
        list(files), manifest_dir, export=True, flip_southern=False
    )
    if "split" in frame.columns or "source_split" in frame.columns:
        raise LeakageError(
            "TCIR has no official split. Keep any official label in source_split only, "
            "and let assign_storms write split."
        )
    refuse_mixed_resolution(frame, "tcir")
    sizes = {int(value) for value in frame["orig_size"].tolist()}
    if sizes != {int(IMAGE_SIZE)}:
        raise ValueError(f"TCIR frames must stay {int(IMAGE_SIZE)}x{int(IMAGE_SIZE)}, got {sorted(sizes)}")
    _log_excluded("tcir", int(len(excluded)), "IR1 gate")
    return _absolute_image_paths(frame, manifest_dir), int(len(excluded))


def load_incyde_frame(config: dict) -> tuple[pd.DataFrame, int]:
    """INCYDE manifest from a local extract. The audit CSVs name the split.

    ``rot_180`` copies stay on the source storm and in train only. Nothing
    is downloaded. ``on_fix``, ``distance_to_land_km``, and ``near_land``
    come from ``incyde/audit/frame_flags.csv``. Unknown audit cells stay
    unknown. The 3-minute label is not rescaled.
    """
    from src.incyde import load_frame

    frame, excluded = load_frame(config)
    if "source_split" in frame.columns:
        raise LeakageError("INCYDE must not carry an official source_split")
    refuse_mixed_resolution(frame, "incyde", parse_image_size(config["data"]["image_size"]))
    _log_excluded("incyde", int(excluded), "default_exclude, dropped augs, eval synthetics")
    return frame, int(excluded)


def load_smoke_frame(config: dict) -> tuple[pd.DataFrame, int]:
    """Synthetic manifest named by ``paths.manifest``. Not a result."""
    path = Path(config["paths"]["manifest"])
    if not path.is_file():
        raise FileNotFoundError(
            f"smoke manifest {path} is missing. Run python -m src.make_smoke_data. "
            "This entrypoint does not download imagery."
        )
    frame = load_manifest(path)
    if "split" in frame.columns:
        frame = frame.drop(columns=["split"])
    if "orig_size" in frame.columns or "native_height" in frame.columns:
        refuse_mixed_resolution(frame, "smoke")
    _log_excluded("smoke", 0, "synthetic manifest is already one size")
    return _absolute_image_paths(frame, path.parent), 0


def training_wind_column(config: dict) -> str:
    """Column the loss reads. The default in the YAML is ``wind_kt_3min``."""
    column = str(config["labels"]["label_column"]).strip()
    if column not in {"wind_kt_3min", "wind_speed_kt", "wind_kt"}:
        raise ValueError("labels.label_column must be wind_kt_3min, wind_speed_kt, or wind_kt")
    return column


def apply_label_standard(frame: pd.DataFrame, config: dict) -> pd.DataFrame:
    """Attach ``wind_kt_3min`` using the YAML factor. Raw knots stay put."""
    block = config["labels"]
    return apply_wind_standard(
        frame,
        factor=float(block["wind_1min_to_3min"]),
        policy=str(block["near_land_policy"]),
        open_water_km=float(block["open_water_km"]),
    )


def load_training_frame(dataset: str, config: dict) -> tuple[pd.DataFrame, int]:
    """Load one dataset. NASA and TCIR are never concatenated.

    Every dataset then gets ``wind_kt_3min``. INCYDE passes through.
    NASA and TCIR 1-minute labels are multiplied by the configured factor.
    """
    name = str(dataset).strip().lower()
    if name not in _DATASETS:
        raise ValueError(f"dataset must be one of {', '.join(_DATASETS)}")
    if name == "nasa":
        frame, excluded = load_nasa_frame(config)
    elif name == "tcir":
        frame, excluded = load_tcir_frame(config)
    elif name == "incyde":
        frame, excluded = load_incyde_frame(config)
    else:
        frame, excluded = load_smoke_frame(config)
    return apply_label_standard(frame, config), excluded


def assign_project_split(frame: pd.DataFrame, config: dict) -> pd.DataFrame:
    """Storm-wise split over the whole frame. ``source_split`` is not used.

    A pre-existing ``split`` column is dropped. Official NASA sides stay in
    ``source_split``. A storm that sits on both official sides gets one
    project split.
    """
    work = frame.copy()
    if "split" in work.columns:
        work = work.drop(columns=["split"])
    assigned = split_frame(work, config)
    if "source_split" in assigned.columns:
        per_storm = assigned.groupby(assigned["storm_id"].astype(str))["split"].nunique()
        if bool((per_storm > 1).any()):
            raise LeakageError("source_split leaked into the project split and cut a storm")
        both = assigned.groupby(assigned["storm_id"].astype(str))["source_split"].nunique()
        shared = both[both > 1]
        for storm_id in shared.index:
            rows = assigned.loc[assigned["storm_id"].astype(str) == str(storm_id), "split"]
            if int(rows.nunique()) != 1:
                raise LeakageError(f"source_split leaked into the project split for {storm_id}")
    groups = storm_ids_by_split(assigned)
    if groups["train"] & groups["val"] or groups["train"] & groups["test"] or groups["val"] & groups["test"]:
        raise LeakageError("storm overlap across splits")
    return assigned


def _move_batch(batch, device):
    images = batch[0].to(device)
    winds = batch[1].to(device)
    class_index = batch[2].to(device)
    sample_weight = batch[3].to(device)
    size_target = batch[4].to(device) if len(batch) > 4 else None
    return images, winds, class_index, sample_weight, size_target


def _split_mae(model, loader, device, policy) -> float:
    """Validation MAE in knots. Dropout is off. This is the early-stopping score."""
    torch = _torch()
    was_training = model.training
    model.eval()
    total = 0.0
    count = 0
    with torch.no_grad():
        for batch in loader:
            images, winds, _class_index, _sample_weight, _size = _move_batch(batch, device)
            with autocast_context(policy):
                wind_hat, _logits, _size_hat = _split_output(model(images))
                error = torch.abs(wind_hat.float().view(-1) - winds.float().view(-1))
            total += float(error.sum())
            count += int(images.shape[0])
    if was_training:
        model.train()
    if count == 0:
        raise ValueError("validation loader produced no rows")
    return total / count


def _collect_predictions(model, loader, device, policy) -> tuple[np.ndarray, np.ndarray]:
    """Point predictions with dropout off, aligned with the loader order."""
    torch = _torch()
    was_training = model.training
    model.eval()
    truths: list[np.ndarray] = []
    preds: list[np.ndarray] = []
    with torch.no_grad():
        for batch in loader:
            images, winds, _class_index, _sample_weight, _size = _move_batch(batch, device)
            with autocast_context(policy):
                wind_hat, _logits, _size_hat = _split_output(model(images))
            truths.append(winds.detach().float().cpu().numpy().reshape(-1))
            preds.append(wind_hat.detach().float().cpu().numpy().reshape(-1))
    if was_training:
        model.train()
    if not truths:
        raise ValueError("loader produced no rows")
    return np.concatenate(truths), np.concatenate(preds)


def _apply_step(optimizer, scaler) -> None:
    if scaler is None:
        optimizer.step()
    else:
        scaler.step(optimizer)
        scaler.update()
    optimizer.zero_grad(set_to_none=True)


def _optimizer_cpu_state(optimizer) -> dict:
    torch = _torch()
    blob = optimizer.state_dict()
    cpu_state: dict = {}
    for param_id, state in blob.get("state", {}).items():
        cpu_state[param_id] = {
            key: (value.detach().cpu() if torch.is_tensor(value) else value)
            for key, value in state.items()
        }
    blob["state"] = cpu_state
    return blob


def _move_optimizer_to(optimizer, device) -> None:
    torch = _torch()
    for state in optimizer.state.values():
        for key, value in list(state.items()):
            if torch.is_tensor(value):
                state[key] = value.to(device)


def _fit_run(
    model,
    train_loader,
    val_loader,
    train_cfg: dict,
    device,
    max_steps: int | None,
    *,
    start_epoch: int = 0,
    history: list | None = None,
    stopper: EarlyStopping | None = None,
    steps_done: int = 0,
    optimizer_state: dict | None = None,
    on_epoch_end=None,
    already_stopped: bool = False,
    loss_weighting: str = "none",
):
    """Smooth L1 on wind, AdamW, early stopping on validation MAE.

    Gradient accumulation steps come from ``train.grad_accum_steps``.
    CUDA fp16 uses GradScaler. XPU bf16 and CPU fp32 do not. A checkpoint
    callback runs after every finished epoch so a sleep can resume there.
    ``loss_weighting`` ``none`` keeps the unweighted mean.
    """
    torch = _torch()

    weighting = loss_weighting_mode(loss_weighting)
    policy = amp_policy_for(device)
    accum = int(train_cfg["grad_accum_steps"])
    if accum < 1:
        raise ValueError("train.grad_accum_steps must be at least 1")
    if max_steps is not None and int(max_steps) < 1:
        raise ValueError("max_steps must be at least 1")
    model.to(device)
    optimizer = torch.optim.AdamW(
        model.parameters(),
        lr=float(train_cfg["lr"]),
        weight_decay=float(train_cfg["weight_decay"]),
    )
    if optimizer_state is not None:
        optimizer.load_state_dict(optimizer_state)
        _move_optimizer_to(optimizer, device)
    scaler = make_grad_scaler(policy)
    epochs = int(train_cfg["epochs"])
    if stopper is None:
        stopper = EarlyStopping(int(train_cfg["patience"]))
    history = list(history or [])
    steps = int(steps_done)
    stopped_early = bool(already_stopped)
    reset_peak_memory(device)
    end_epoch = start_epoch if already_stopped else epochs
    for epoch in range(int(start_epoch), int(end_epoch)):
        epoch_start = time.time()
        model.train()
        _move_optimizer_to(optimizer, device)
        optimizer.zero_grad(set_to_none=True)
        total = 0.0
        count = 0
        pending = 0
        for batch in train_loader:
            if max_steps is not None and steps >= int(max_steps):
                break
            images, winds, _class_index, sample_weight, _size = _move_batch(batch, device)
            with autocast_context(policy):
                wind_hat, _logits, _size_hat = _split_output(model(images))
                loss = batch_wind_loss(wind_hat.float(), winds.float(), sample_weight, weighting)
            if scaler is None:
                (loss / accum).backward()
            else:
                scaler.scale(loss / accum).backward()
            pending += 1
            rows = int(images.shape[0])
            total += float(loss.detach()) * rows
            count += rows
            steps += 1
            if pending == accum:
                _apply_step(optimizer, scaler)
                pending = 0
        if pending:
            _apply_step(optimizer, scaler)
        if count == 0:
            break
        val_mae = _split_mae(model, val_loader, device, policy)
        if not np.isfinite(val_mae):
            raise RuntimeError("validation MAE is not finite")
        train_loss = total / count
        elapsed = time.time() - epoch_start
        print(
            f"epoch {epoch + 1}/{epochs} | train_loss={train_loss:.4f} | val_mae={float(val_mae):.2f} kt | elapsed={elapsed:.1f}s",
            flush=True,
        )
        history.append(
            {
                "epoch": epoch,
                "step": steps,
                "train_loss": train_loss,
                "val_mae": float(val_mae),
            }
        )
        state = {key: value.detach().cpu() for key, value in model.state_dict().items()}
        if stopper.update(float(val_mae), state):
            stopped_early = True
        if on_epoch_end is not None:
            on_epoch_end(
                epoch=epoch,
                model=model,
                optimizer=optimizer,
                history=history,
                stopper=stopper,
                steps=steps,
                stopped_early=stopped_early,
            )
        if stopped_early:
            break
        if max_steps is not None and steps >= int(max_steps):
            break
    if stopper.best_state is None:
        raise RuntimeError("training produced no validation score")
    model.load_state_dict(stopper.best_state)
    return model, history, stopped_early, float(stopper.best), peak_memory_bytes(device)


def _config_hash(config: dict) -> str:
    payload = json.dumps(config, sort_keys=True, default=str)
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()


def _write_loss_curve(history: list[dict], csv_path: Path, png_path: Path) -> None:
    import matplotlib

    matplotlib.use("Agg", force=True)
    import matplotlib.pyplot as plt

    table = pd.DataFrame(history)
    csv_path.parent.mkdir(parents=True, exist_ok=True)
    table.to_csv(csv_path, index=False)
    figure, axis = plt.subplots(figsize=(6.4, 4.0))
    axis.plot(table["epoch"], table["train_loss"], marker="o", label="train SmoothL1")
    axis.plot(table["epoch"], table["val_mae"], marker="o", label="val MAE (kt)")
    axis.set_xlabel("epoch")
    axis.set_ylabel("loss / MAE")
    axis.set_title("Training curve. Not a forecast.")
    axis.legend(frameon=False)
    figure.tight_layout()
    figure.savefig(png_path, dpi=100)
    plt.close(figure)


def _score_split(truth: np.ndarray, pred: np.ndarray, config: dict) -> dict:
    """MAE, RMSE, and bias from ``src.evaluate`` on one held-out split."""
    from src.evaluate import score_winds

    edges = tuple(float(edge) for edge in config["data"]["imd5_edges_kt"])
    names = tuple(str(name) for name in config["data"]["imd5_names"])
    overall = score_winds(truth, pred, edges, names)["overall"]
    return {
        "n": overall["n"],
        "mae_kt": overall["mae_kt"],
        "rmse_kt": overall["rmse_kt"],
        "bias_kt": overall["bias_kt"],
    }


def _run_id(dataset: str, model_name: str, config_digest: str) -> str:
    stamp = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime())
    return f"{dataset}-{model_name}-{stamp}-{time.time_ns()}-{config_digest[:8]}"


def git_commit() -> str | None:
    """HEAD of this checkout, or null when git is not available."""
    try:
        text = subprocess.check_output(
            ["git", "rev-parse", "HEAD"],
            cwd=Path(__file__).resolve().parents[1],
            text=True,
            stderr=subprocess.DEVNULL,
        ).strip()
    except (OSError, subprocess.CalledProcessError):
        return None
    return text or None


def _file_sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with Path(path).open("rb") as handle:
        for chunk in iter(lambda: handle.read(1 << 20), b""):
            digest.update(chunk)
    return digest.hexdigest()


def _load_torch_payload(path: Path) -> dict:
    torch = _torch()
    if not path.is_file():
        raise FileNotFoundError(path)
    try:
        payload = torch.load(path, map_location="cpu", weights_only=False)
    except TypeError:
        payload = torch.load(path, map_location="cpu")
    if not isinstance(payload, dict):
        raise RuntimeError(f"{path} is not a checkpoint dict")
    return payload


def _parent_periods(payload: dict) -> set[str]:
    periods: set[str] = set()
    grouped = payload.get("wind_averaging_by_split")
    if isinstance(grouped, dict):
        for entry in grouped.values():
            if isinstance(entry, dict):
                periods.update(str(value) for value in entry.get("wind_averaging", []))
    single = payload.get("wind_averaging")
    if single not in (None, ""):
        periods.add(str(single))
    return {value for value in periods if value and value.lower() != "none"}


def load_init_weights(model, path: str | Path, config: dict) -> tuple[object, str, set[str], object]:
    """Load weights only. Optimizer state is left untouched.

    A different ``model_name`` or a state dict whose keys or shapes differ
    is refused. The returned hash is the file bytes, and the period set is
    whatever the parent run recorded.
    """
    checkpoint = Path(path)
    payload = _load_torch_payload(checkpoint)
    if "state_dict" not in payload:
        raise RuntimeError(f"Refusing init-from: {checkpoint} has no state_dict")
    expected = str(config["model"]["name"])
    loaded_name = payload.get("model_name")
    if loaded_name is not None and str(loaded_name) != expected:
        raise RuntimeError(
            "Refusing init-from: architecture does not match "
            f"(checkpoint model {loaded_name}, training model {expected})"
        )
    incoming = payload["state_dict"]
    current = model.state_dict()
    if set(incoming) != set(current):
        missing = sorted(set(current) - set(incoming))[:8]
        extra = sorted(set(incoming) - set(current))[:8]
        raise RuntimeError(
            "Refusing init-from: architecture does not match "
            f"(missing {missing}, extra {extra})"
        )
    for key, tensor in current.items():
        if tuple(tensor.shape) != tuple(incoming[key].shape):
            raise RuntimeError(
                "Refusing init-from: architecture does not match at "
                f"{key}: {tuple(tensor.shape)} vs {tuple(incoming[key].shape)}"
            )
    model.load_state_dict({key: value.detach().cpu() for key, value in incoming.items()})
    run_id = payload.get("run_id")
    return run_id, _file_sha256(checkpoint), _parent_periods(payload), payload.get("label_column")


def averaging_mismatch(
    parent_periods: set[str],
    current_periods: set[str],
    parent_label: object,
    current_label: object,
) -> bool:
    """True when raw averaging periods differ and the 3-minute target is not both sides.

    A parent and a child that both train on ``wind_kt_3min`` already share
    the converted target, so a 1-minute pretrain and a 3-minute fine-tune
    do not set the mismatch flag. Forcing raw labels (``wind_speed_kt`` or
    ``wind_kt``) on either side keeps the flag.
    """
    if str(parent_label) == "wind_kt_3min" and str(current_label) == "wind_kt_3min":
        return False
    parent = {str(value) for value in parent_periods if str(value).strip()}
    current = {str(value) for value in current_periods if str(value).strip()}
    if not parent or not current or parent == current:
        return False
    return True


def _warn_wind_mismatch(
    parent: set[str],
    current: set[str],
    parent_label: object,
    current_label: object,
) -> bool:
    """Loud warning when raw labels cross averaging periods."""
    if not averaging_mismatch(parent, current, parent_label, current_label):
        return False
    message = (
        "WARNING: wind_averaging mismatch. "
        f"Parent checkpoint records {sorted(parent)} and this dataset records {sorted(current)}. "
        "No conversion factor is applied."
    )
    LOGGER.warning(message)
    print(message)
    return True


def assert_test_score_allowed(dataset: str, allow_final_test: bool) -> None:
    """INCYDE test storms are not scored unless ``--allow-final-test`` is set.

    That covers Bean's default split and ``year_holdout_2019``.
    """
    if str(dataset).strip().lower() == "incyde" and not allow_final_test:
        raise RuntimeError(
            "refusing to score INCYDE test storms without --allow-final-test. "
            "This applies to the default storm split and to split year_holdout_2019."
        )


def _path_records(
    frame: pd.DataFrame,
    manifest: Path,
    split_name: str,
    wind_column: str,
    angles: np.ndarray | None = None,
    weights: np.ndarray | None = None,
) -> list[dict]:
    rows = frame[frame["split"] == split_name].reset_index(drop=True)
    if rows.empty:
        raise ValueError(f"split {split_name} has no rows")
    labels = [None if pd.isna(value) else str(value) for value in rows["_class"]]
    paths = [str(resolve_image(manifest, path)) for path in rows["image_path"].tolist()]
    winds = rows[wind_column].to_numpy(dtype=np.float64)
    raw = rows["wind_speed_kt"].to_numpy(dtype=np.float64)
    # wind_kt_scale maps a 3-minute prediction back to the raw label.
    # A run forced onto the raw column already predicts in raw knots.
    if wind_column == "wind_kt_3min" and "wind_kt_scale" in rows.columns:
        scale = rows["wind_kt_scale"].to_numpy(dtype=np.float64)
    else:
        scale = np.ones(len(rows), dtype=np.float64)
    if weights is None:
        row_weights = np.ones(len(rows), dtype=np.float64)
    else:
        row_weights = np.asarray(weights, dtype=np.float64).reshape(-1)
        if row_weights.shape[0] != len(rows):
            raise ValueError("loss weights must align with the split")
    if "on_fix" in rows.columns:
        on_fix_values = rows["on_fix"].tolist()
    else:
        on_fix_values = [None] * len(rows)
    records = []
    for index in range(len(rows)):
        angle = None if angles is None else float(angles[index])
        records.append(
            {
                "path": paths[index],
                "wind": float(winds[index]),
                "raw_wind": float(raw[index]),
                "scale": float(scale[index]),
                "label": labels[index],
                "weight": float(row_weights[index]),
                "on_fix": on_fix_values[index],
                "angle": angle,
            }
        )
    return records


def training_angles(n_rows: int, seed: int, enabled: bool) -> np.ndarray | None:
    """One seeded degree per train row. Val and test pass ``enabled`` false."""
    if not enabled or n_rows < 1:
        return None
    return np.random.default_rng(int(seed)).uniform(0.0, 360.0, size=int(n_rows))


def _parity_side(config: dict, frame: pd.DataFrame) -> int:
    side = parse_image_size(config["data"]["image_size"])
    if side is not None:
        return int(side)
    if "orig_size" in frame.columns and len(frame):
        return int(frame["orig_size"].iloc[0])
    if "native_height" in frame.columns and len(frame):
        return int(frame["native_height"].iloc[0])
    raise ValueError("cannot infer the frame size for the device parity check")


def _current_periods(report: dict) -> set[str]:
    periods: set[str] = set()
    for entry in report.values():
        periods.update(str(value) for value in entry["wind_averaging"])
    return periods


def run_is_synthetic(dataset: str, frame: pd.DataFrame) -> bool:
    """Smoke is synthetic. INCYDE aug copies do not mark a real run synthetic.

    ``manifest_is_synthetic`` stays true when any row is synthetic. A real
    INCYDE extract has original frames plus train-only ``rot_180`` copies.
    Those copies are flagged and the run is still a real-data run.
    """
    if dataset == "smoke":
        return True
    if dataset == "incyde":
        flags = [parse_is_synthetic(value) for value in frame["is_synthetic"].tolist()]
        return not any(not flag for flag in flags)
    return manifest_is_synthetic(frame)


def normalization_frame(frame: pd.DataFrame, dataset: str) -> pd.DataFrame:
    """Train-split stats see original INCYDE frames, not ``rot_180`` copies."""
    if dataset != "incyde" or "is_synthetic" not in frame.columns:
        return frame
    flags = [parse_is_synthetic(value) for value in frame["is_synthetic"].tolist()]
    kept = frame.loc[[not flag for flag in flags]].reset_index(drop=True)
    if kept.empty or not bool((kept["split"].astype(str) == "train").any()):
        raise LeakageError("INCYDE normalization needs original train frames")
    return kept


def run_training(
    config: dict,
    *,
    dataset: str | None = None,
    model: str | None = None,
    max_steps: int | None = None,
    device: str | None = None,
    resume: str | Path | None = None,
    init_from: str | Path | None = None,
    allow_final_test: bool = False,
) -> Path:
    """Fit one dataset and write the run record under ``paths.runs``.

    ``resume`` continues the last finished epoch in that run directory.
    ``init_from`` copies weights from another run, refits normalization on
    this dataset's train storms, and does not load the optimizer.
    """
    import yaml

    if resume is not None and init_from is not None:
        raise ValueError("pass either --resume or --init-from, not both")
    assert_model_inputs(("image",))
    train_cfg = _require_train_block(config)
    assert_normalize(config)
    resolved = copy.deepcopy(config)
    saved = None
    if resume is not None:
        run_dir = Path(resume)
        saved = _load_torch_payload(run_dir / LAST_CHECKPOINT)
        if "state_dict" not in saved or "epoch" not in saved:
            raise RuntimeError(f"{run_dir / LAST_CHECKPOINT} is not a resume checkpoint")
    if dataset is not None:
        dataset_name = str(dataset).strip().lower()
    elif saved is not None:
        dataset_name = str(saved["dataset"]).strip().lower()
    else:
        dataset_name = str(resolved["data"]["dataset"]).strip().lower()
    if dataset_name not in _DATASETS:
        raise ValueError(f"dataset must be one of {', '.join(_DATASETS)}")
    if dataset_name == "incyde":
        resolved["data"]["wind_averaging"] = "3min"
    if saved is not None and str(saved["dataset"]) != dataset_name:
        raise RuntimeError(
            f"resume dataset is {saved['dataset']} but this command asked for {dataset_name}"
        )
    if model is not None:
        resolved["model"]["name"] = canonical_model_name(model)
    elif saved is not None:
        resolved["model"]["name"] = str(saved["model_name"])
    else:
        resolved["model"]["name"] = canonical_model_name(str(resolved["model"]["name"]))
    if resolved["model"]["name"] not in {"simple_cnn", "resnet18", "convlstm"}:
        raise ValueError("this entrypoint trains simplecnn, resnet18, or convlstm")
    if saved is not None and str(saved["model_name"]) != str(resolved["model"]["name"]):
        raise RuntimeError(
            "Refusing resume: architecture does not match "
            f"(checkpoint model {saved['model_name']}, training model {resolved['model']['name']})"
        )
    device_name = str(device if device is not None else resolved["train"]["device"])
    torch_device = resolve_device(device_name)
    policy = amp_policy_for(torch_device)
    if max_steps is None:
        max_steps = resolved["train"]["max_steps"]
    if max_steps is not None:
        max_steps = int(max_steps)
    resolved["data"]["dataset"] = dataset_name
    resolved["train"]["device"] = torch_device.type
    resolved["train"]["device_requested"] = device_name
    resolved["train"]["precision"] = policy.precision
    resolved["train"]["max_steps"] = max_steps
    digest = _config_hash(resolved)
    resolved["config_hash"] = digest
    print(f"device={torch_device.type} precision={policy.precision}")
    LOGGER.info("device=%s precision=%s", torch_device.type, policy.precision)

    if saved is None:
        frame, n_excluded = load_training_frame(dataset_name, resolved)
        frame = apply_frame_cache(frame, dataset_name, resolved["paths"].get("frame_cache"))
        refuse_mixed_resolution(
            frame, dataset_name, parse_image_size(resolved["data"]["image_size"])
        )
        wind_period = assert_wind_averaging(resolved, frame)
        synthetic = run_is_synthetic(dataset_name, frame)
        seed = int(resolved["project"]["seed"])
        _set_seed(seed)
        wind_column = training_wind_column(resolved)
        if dataset_name == "incyde":
            assigned = frame.copy()
        else:
            assigned = assign_project_split(frame, resolved)
        assigned["_class"] = project_labels(assigned, resolved, wind_column)
        groups = storm_ids_by_split(assigned)
        if not groups["train"] or not groups["val"] or not groups["test"]:
            raise LeakageError("train, val, and test storms are all required")
        # Frequencies are the assigned train split, so storm_cv's val fold
        # and the sealed test storms are already out. The CSV records them.
        assigned = annotate_balance(
            assigned, intensity_balance(assigned, resolved, wind_column), resolved
        )
        run_id = _run_id(dataset_name, str(resolved["model"]["name"]), digest)
        run_dir = Path(resolved["paths"]["runs"]) / run_id
        run_dir.mkdir(parents=True, exist_ok=False)
        manifest_path = run_dir / "split_manifest.csv"
        assigned.drop(columns=["_class"], errors="ignore").to_csv(manifest_path, index=False)
        labeled = assigned.copy()
        labeled["_class"] = project_labels(labeled, resolved, wind_column)
        start_epoch = 0
        prior_history: list = []
        restored_stopper = None
        steps_done = 0
        optimizer_state = None
        already_stopped = False
    else:
        if not run_dir.is_dir():
            raise FileNotFoundError(run_dir)
        manifest_path = run_dir / "split_manifest.csv"
        labeled = load_manifest(manifest_path)
        wind_period = assert_wind_averaging(resolved, labeled)
        synthetic = run_is_synthetic(dataset_name, labeled)
        seed = int(saved.get("seed", resolved["project"]["seed"]))
        _set_seed(seed)
        wind_column = training_wind_column(resolved)
        labeled["_class"] = project_labels(labeled, resolved, wind_column)
        groups = storm_ids_by_split(labeled)
        if not groups["train"] or not groups["val"] or not groups["test"]:
            raise LeakageError("train, val, and test storms are all required")
        run_id = str(saved["run_id"])
        n_excluded = int(saved.get("n_excluded", 0))
        start_epoch = int(saved["epoch"]) + 1
        prior_history = list(saved.get("history") or [])
        restored_stopper = EarlyStopping(int(train_cfg["patience"]))
        restored_stopper.best = float(saved["best_metric"])
        restored_stopper.waits = int(saved["waits"])
        restored_stopper.best_state = saved["best_state"]
        steps_done = int(saved.get("steps", 0))
        optimizer_state = saved.get("optimizer_state_dict")
        already_stopped = bool(saved.get("stopped_early"))

    size_head = False
    stats = fit_split_normalization(normalization_frame(labeled, dataset_name), manifest_path, resolved)
    if stats.source_split != "train":
        raise LeakageError("normalization stats may be fit on the train split only")
    dataset_stats = norm_by_dataset(dataset_name, stats)
    averaging = split_wind_averaging(labeled)
    known = [str(name) for name in resolved["data"]["imd5_names"]]
    image_size = parse_image_size(resolved["data"]["image_size"])
    max_missing = float(resolved["data"]["max_missing_fraction"])
    batch_size = int(train_cfg["batch_size"])
    workers = int(train_cfg["num_workers"])
    torch = _torch()
    generator = torch.Generator()
    generator.manual_seed(seed)
    balance = intensity_balance(labeled, resolved, wind_column)
    balance_payload = balance_record(balance)
    train_rows = labeled.loc[labeled["split"] == "train"].reset_index(drop=True)
    train_labels = [None if pd.isna(value) else str(value) for value in train_rows["_class"]]
    if balance["loss_weighting"] == "none":
        train_loss_weights = np.ones(len(train_rows), dtype=np.float64)
    else:
        train_loss_weights = align_bin_weights(train_labels, balance["weights"])
    if uses_sequences(resolved):
        train_images, train_winds, train_labels, train_size = _load_examples(
            resolved, labeled, manifest_path, "train", stats, size_head
        )
        val_images, val_winds, val_labels, val_size = _load_examples(
            resolved, labeled, manifest_path, "val", stats, size_head
        )
        if balance["loss_weighting"] == "none":
            train_loss_weights = np.ones(len(train_winds), dtype=np.float64)
        else:
            train_loss_weights = align_bin_weights(train_labels, balance["weights"])
        val_weight = np.ones(len(val_winds), dtype=np.float64)
        train_sampler = None
        shuffle_train = True
        if balance["balanced_sampling"]:
            train_sampler = make_balanced_sampler(
                align_bin_weights(train_labels, balance["sampling_weights"]),
                len(train_winds),
                seed,
            )
            shuffle_train = False
        train_loader = build_loader(
            _dataset(train_images, train_winds, train_labels, known, train_loss_weights, train_size),
            batch_size=batch_size,
            shuffle=shuffle_train,
            num_workers=workers,
            generator=None if train_sampler is not None else generator,
            sampler=train_sampler,
        )
        val_loader = build_loader(
            _dataset(val_images, val_winds, val_labels, known, val_weight, val_size),
            batch_size=batch_size,
            shuffle=False,
            num_workers=workers,
        )
        score_test = True
        test_refusal = None
        try:
            assert_test_score_allowed(dataset_name, allow_final_test)
        except RuntimeError as exc:
            score_test = False
            test_refusal = str(exc)
        test_records = None
        test_loader = None
        if score_test:
            try:
                test_images, test_winds, test_labels, test_size = _load_examples(
                    resolved, labeled, manifest_path, "test", stats, size_head
                )
                test_weight = np.ones(len(test_winds), dtype=np.float64)
                test_loader = build_loader(
                    _dataset(test_images, test_winds, test_labels, known, test_weight, test_size),
                    batch_size=batch_size,
                    shuffle=False,
                    num_workers=workers,
                )
            except Exception as exc:
                score_test = False
                test_refusal = str(exc)
    else:
        train_count = int(len(train_rows))
        train_records = _path_records(
            labeled,
            manifest_path,
            "train",
            wind_column,
            training_angles(train_count, seed, dataset_name == "incyde"),
            train_loss_weights,
        )
        val_records = _path_records(labeled, manifest_path, "val", wind_column, None)
        train_sampler = None
        shuffle_train = True
        if balance["balanced_sampling"]:
            train_sampler = make_balanced_sampler(
                align_bin_weights(train_labels, balance["sampling_weights"]),
                len(train_rows),
                seed,
            )
            shuffle_train = False
        train_loader = build_loader(
            PathFrames(train_records, image_size, stats.mean, stats.std, max_missing, known),
            batch_size=batch_size,
            shuffle=shuffle_train,
            num_workers=workers,
            generator=None if train_sampler is not None else generator,
            sampler=train_sampler,
        )
        val_loader = build_loader(
            PathFrames(val_records, image_size, stats.mean, stats.std, max_missing, known),
            batch_size=batch_size,
            shuffle=False,
            num_workers=workers,
        )
        score_test = True
        test_refusal = None
        try:
            assert_test_score_allowed(dataset_name, allow_final_test)
        except RuntimeError as exc:
            score_test = False
            test_refusal = str(exc)
        test_records = None
        test_loader = None
        if score_test:
            test_records = _path_records(labeled, manifest_path, "test", wind_column, None)
            test_loader = build_loader(
                PathFrames(test_records, image_size, stats.mean, stats.std, max_missing, known),
                batch_size=batch_size,
                shuffle=False,
                num_workers=workers,
            )
    model = build_net(resolved, size_head=size_head)
    if not any(layer.__class__.__name__ == "Dropout" for layer in model.modules()):
        raise RuntimeError("MC-dropout needs a Dropout layer left in the network")
    parent_run_id = None
    parent_sha = None
    parent_periods: set[str] = set()
    parent_label = None
    if init_from is not None:
        parent_run_id, parent_sha, parent_periods, parent_label = load_init_weights(
            model, init_from, resolved
        )
    if saved is not None:
        model.load_state_dict(saved["state_dict"])
    label_column = wind_column
    mismatch = _warn_wind_mismatch(
        parent_periods, _current_periods(averaging), parent_label, label_column
    )
    parity = None
    if torch_device.type != "cpu":
        images, winds = seeded_parity_batch(
            min(2, batch_size),
            int(resolved["data"]["channels"]),
            _parity_side(resolved, labeled),
            seed=0,
            n_frames=model_n_frames(resolved),
        )
        parity = compare_model_parity(
            model,
            images,
            winds,
            torch_device,
            float(train_cfg["device_parity_tol"]),
            policy=policy,
        )

    def _on_epoch_end(*, epoch, model, optimizer, history, stopper, steps, stopped_early) -> None:
        blob = {
            "state_dict": {key: value.detach().cpu() for key, value in model.state_dict().items()},
            "optimizer_state_dict": _optimizer_cpu_state(optimizer),
            "epoch": int(epoch),
            "history": list(history),
            "best_state": stopper.best_state,
            "best_metric": float(stopper.best),
            "waits": int(stopper.waits),
            "steps": int(steps),
            "stopped_early": bool(stopped_early),
            "run_id": run_id,
            "dataset": dataset_name,
            "model_name": str(resolved["model"]["name"]),
            "seed": seed,
            "n_excluded": int(n_excluded),
        }
        torch.save(blob, run_dir / LAST_CHECKPOINT)

    model, history, stopped_early, best_val_mae, peak_bytes = _fit_run(
        model,
        train_loader,
        val_loader,
        train_cfg,
        torch_device,
        max_steps,
        start_epoch=start_epoch,
        history=prior_history,
        stopper=restored_stopper,
        steps_done=steps_done,
        optimizer_state=optimizer_state,
        on_epoch_end=_on_epoch_end,
        already_stopped=already_stopped,
        loss_weighting=balance["loss_weighting"],
    )
    if not history:
        raise RuntimeError("training produced no loss curve")
    val_truth, val_pred = _collect_predictions(model, val_loader, torch_device, policy)
    if uses_sequences(resolved):
        val_windows = frame_windows(labeled, "val", model_n_frames(resolved))
        indexed = labeled.set_index(labeled["sample_id"].astype(str), drop=False)
        last_rows = [_row(indexed, w[-1]) for w in val_windows]
        if wind_column == "wind_kt_3min" and "wind_kt_scale" in labeled.columns:
            val_scales = np.array([float(r.get("wind_kt_scale", 1.0)) for r in last_rows], dtype=np.float64)
        else:
            val_scales = np.ones(len(last_rows), dtype=np.float64)
        val_raw_truth = np.array([float(r["wind_speed_kt"]) for r in last_rows], dtype=np.float64)
        val_raw_pred = back_converted_prediction(val_pred, val_scales)
    else:
        val_raw_pred = back_converted_prediction(
            val_pred, np.array([row["scale"] for row in val_records], dtype=np.float64)
        )
        val_raw_truth = np.array([row["raw_wind"] for row in val_records], dtype=np.float64)
    if score_test and test_loader is not None:
        test_truth, test_pred = _collect_predictions(model, test_loader, torch_device, policy)
        if uses_sequences(resolved):
            test_windows = frame_windows(labeled, "test", model_n_frames(resolved))
            indexed = labeled.set_index(labeled["sample_id"].astype(str), drop=False)
            last_rows = [_row(indexed, w[-1]) for w in test_windows]
            if wind_column == "wind_kt_3min" and "wind_kt_scale" in labeled.columns:
                test_scales = np.array([float(r.get("wind_kt_scale", 1.0)) for r in last_rows], dtype=np.float64)
            else:
                test_scales = np.ones(len(last_rows), dtype=np.float64)
            test_raw_truth = np.array([float(r["wind_speed_kt"]) for r in last_rows], dtype=np.float64)
            test_raw_pred = back_converted_prediction(test_pred, test_scales)
        else:
            test_raw_pred = back_converted_prediction(
                test_pred, np.array([row["scale"] for row in test_records], dtype=np.float64)
            )
            test_raw_truth = np.array([row["raw_wind"] for row in test_records], dtype=np.float64)
        test_metrics = _score_split(test_truth, test_pred, resolved)
        test_raw_metrics = _score_split(test_raw_truth, test_raw_pred, resolved)
        residual_block = None
        try:
            np.savez(
                run_dir / "predictions.npz",
                y_true_test=test_truth,
                y_pred_test=test_pred,
                mc_samples_test=test_pred[None, :],
                y_true_val=val_truth,
                y_pred_val=val_pred,
                mc_samples_val=val_pred[None, :],
            )
            from src.evaluate import (
                _LEVELS,
                _TOLERANCE,
                compute_residual_quantiles,
            )

            val_storms = sorted(str(s) for s in groups.get("val", []))
            test_storms = sorted(str(s) for s in groups.get("test", []))
            if val_storms and test_storms:
                residual_block = compute_residual_quantiles(
                    y_true_val=val_truth,
                    y_pred_val=val_pred,
                    y_true_test=test_truth,
                    y_pred_test=test_pred,
                    val_storms=val_storms,
                    test_storms=test_storms,
                    levels=_LEVELS,
                    tolerance=_TOLERANCE,
                    is_synthetic=bool(synthetic),
                )
        except Exception:
            residual_block = None
    else:
        test_metrics = {"scored": False, "reason": test_refusal}
        test_raw_metrics = {"scored": False, "reason": test_refusal}
        residual_block = None
    checkpoint_name = str(resolved["paths"]["checkpoint_name"])
    if not checkpoint_name or checkpoint_name != Path(checkpoint_name).name:
        raise ValueError("paths.checkpoint_name must be a file name, not a path")
    checkpoint = run_dir / checkpoint_name
    split_ids = {name: sorted(groups[name]) for name in ("train", "val", "test")}
    train_winds = labeled.loc[labeled["split"] == "train", wind_column].to_numpy(dtype=np.float64)
    conversion_note = run_conversion_note(labeled)
    properties = xpu_device_properties(torch_device)
    commit = git_commit()
    payload = {
        "state_dict": {key: value.detach().cpu() for key, value in model.state_dict().items()},
        "model_name": str(resolved["model"]["name"]),
        "dropout": float(resolved["model"]["dropout"]),
        "pretrained": False,
        "in_channels": int(resolved["data"]["channels"]),
        "n_classes": len(known),
        "class_names": known,
        "edges_kt": [float(edge) for edge in resolved["data"]["imd5_edges_kt"]],
        "norm_mean": stats.mean,
        "norm_std": stats.std,
        "norm_source_split": stats.source_split,
        "norm_by_dataset": dataset_stats,
        "image_size": image_size,
        "max_missing_fraction": max_missing,
        "mean_baseline_kt": float(np.mean(train_winds)),
        "is_synthetic": bool(synthetic),
        "wind_averaging": wind_period,
        "wind_averaging_s": wind_averaging_seconds(wind_period),
        "wind_averaging_by_split": averaging,
        "wind_averaging_mismatch": bool(mismatch),
        "label_column": label_column,
        "wind_conversion": conversion_note,
        "split": {
            "strategy": str(resolved["split"]["strategy"]),
            "seed": int(resolved["split"]["seed"]),
            "test_fraction": float(resolved["split"]["test_fraction"]),
            "val_fraction": float(resolved["split"]["val_fraction"]),
        },
        "split_storm_ids": split_ids,
        "best_val_loss": best_val_mae,
        "best_val_mae": best_val_mae,
        "epoch": int(history[-1]["epoch"]),
        "present_as_forecast": False,
        "honesty": SMOKE_BANNER if synthetic else NOT_A_FORECAST,
        "n_frames": model_n_frames(resolved) if uses_sequences(resolved) else 1,
        "size_head": size_head,
        "hidden": int(resolved["model"]["hidden"]) if uses_sequences(resolved) else None,
        "config_hash": digest,
        "seed": seed,
        "dataset": dataset_name,
        "run_id": run_id,
        "result": False if synthetic else True,
        "device": torch_device.type,
        "device_requested": device_name,
        "precision": policy.precision,
        "use_grad_scaler": bool(policy.use_grad_scaler),
        "grad_accum_steps": int(train_cfg["grad_accum_steps"]),
        "peak_memory_bytes": peak_bytes,
        "git_commit": commit,
        "parent_run_id": None if parent_run_id is None else str(parent_run_id),
        "parent_checkpoint_sha256": parent_sha,
        "xpu_device_properties": properties,
        "device_parity_ok": None if parity is None else bool(parity["ok"]),
        "device_parity_max_abs_diff": None if parity is None else parity["max_abs_diff"],
        "device_parity_output_max_abs": None if parity is None else parity["output_max_abs"],
        "device_parity_loss_max_abs": None if parity is None else parity["loss_max_abs"],
        "device_parity_tol": float(train_cfg["device_parity_tol"]),
        "intensity_balance": balance_payload,
    }
    torch.save(payload, checkpoint)
    (run_dir / "resolved_config.yaml").write_text(
        yaml.safe_dump(resolved, sort_keys=False), encoding="utf-8"
    )
    _write_loss_curve(history, run_dir / "loss_curve.csv", run_dir / "loss_curve.png")
    metrics = {
        "result": False if synthetic else True,
        "is_synthetic": bool(synthetic),
        "quote_as_result": "no",
        "present_as_forecast": False,
        "dataset": dataset_name,
        "model": str(resolved["model"]["name"]),
        "seed": seed,
        "config_hash": digest,
        "git_commit": commit,
        "resolved_config": "resolved_config.yaml",
        "run_id": run_id,
        "wind_averaging": wind_period,
        "wind_averaging_s": wind_averaging_seconds(wind_period),
        "wind_averaging_by_split": averaging,
        "wind_averaging_mismatch": bool(mismatch),
        "label_column": label_column,
        "wind_conversion": conversion_note,
        "parent_run_id": None if parent_run_id is None else str(parent_run_id),
        "parent_checkpoint_sha256": parent_sha,
        "n_excluded": int(n_excluded),
        "stopped_early": bool(stopped_early),
        "best_val_mae": best_val_mae,
        "epochs_ran": int(len(history)),
        "split_storm_ids": split_ids,
        "scored_by": "src.evaluate.score_winds",
        "val": _score_split(val_truth, val_pred, resolved),
        "val_raw": _score_split(val_raw_truth, val_raw_pred, resolved),
        "test": test_metrics,
        "test_raw": test_raw_metrics,
        "intensity_balance": balance_payload,
        "device": torch_device.type,
        "device_requested": device_name,
        "precision": policy.precision,
        "use_grad_scaler": bool(policy.use_grad_scaler),
        "grad_accum_steps": int(train_cfg["grad_accum_steps"]),
        "peak_memory_bytes": peak_bytes,
        "xpu_device_properties": properties,
        "device_parity_ok": None if parity is None else bool(parity["ok"]),
        "device_parity_max_abs_diff": None if parity is None else parity["max_abs_diff"],
        "device_parity_output_max_abs": None if parity is None else parity["output_max_abs"],
        "device_parity_loss_max_abs": None if parity is None else parity["loss_max_abs"],
        "device_parity_tol": float(train_cfg["device_parity_tol"]),
        "norm_by_dataset": dataset_stats,
        "note": SMOKE_BANNER if synthetic else NOT_A_FORECAST,
    }
    on_fix_only = False
    if dataset_name == "incyde":
        on_fix_only = config_flag(
            (resolved.get("incyde") or {}).get("on_fix_only_eval", False),
            "incyde.on_fix_only_eval",
        )
    if on_fix_only and "on_fix" not in labeled.columns:
        raise ValueError("incyde.on_fix_only_eval needs on_fix on the INCYDE rows")
    metrics["on_fix_only_eval"] = bool(on_fix_only)
    if on_fix_only:
        # Overall val and val_raw stay the full validation split. This block
        # is an extra slice. Unknown on_fix rows are not treated as on-fix.
        flags = [row.get("on_fix") for row in val_records]
        metrics["val_on_fix"] = on_fix_metrics(val_truth, val_pred, flags, resolved)
        metrics["val_raw_on_fix"] = on_fix_metrics(val_raw_truth, val_raw_pred, flags, resolved)
    if str(resolved["split"]["strategy"]).strip().lower() == "year_holdout_2019":
        from src.incyde import YEAR_HOLDOUT_NOTE

        metrics["year_holdout_2019"] = YEAR_HOLDOUT_NOTE
        metrics["year_holdout_2019_indicative"] = True
    if residual_block is not None:
        from src.evaluate import _LEVELS, _TOLERANCE, merge_residual_quantiles

        metrics = merge_residual_quantiles(
            metrics, residual_block, tolerance=_TOLERANCE, levels=_LEVELS
        )
    metrics["synthetic"] = bool(synthetic)
    (run_dir / "metrics.json").write_text(json.dumps(metrics, indent=2) + "\n", encoding="utf-8")
    if synthetic:
        print(SMOKE_BANNER)
    else:
        print(NOT_A_FORECAST)
    print(f"Wrote run record {run_dir}")
    return run_dir


def main(argv: list[str] | None = None) -> Path:
    """``python -m src.train --config config/config.yaml``."""
    parser = argparse.ArgumentParser(
        description="Train a wind-speed model. Hyperparameters, paths, and seeds come from the YAML."
    )
    parser.add_argument("--config", type=Path, required=True)
    parser.add_argument("--dataset", choices=_DATASETS, default=None)
    parser.add_argument("--model", choices=("simplecnn", "resnet18", "convlstm"), default=None)
    parser.add_argument("--max-steps", type=int, default=None)
    parser.add_argument("--device", choices=("auto", "xpu", "cuda", "cpu"), default=None)
    parser.add_argument("--resume", type=Path, default=None)
    parser.add_argument("--init-from", type=Path, default=None)
    parser.add_argument(
        "--allow-final-test",
        action="store_true",
        help="Score INCYDE test storms. Without this flag the test split is withheld.",
    )
    args = parser.parse_args(argv)
    config = load_config(args.config)
    return run_training(
        config,
        dataset=args.dataset,
        model=args.model,
        max_steps=args.max_steps,
        device=args.device,
        resume=args.resume,
        init_from=args.init_from,
        allow_final_test=bool(args.allow_final_test),
    )


if __name__ == "__main__":
    main()