File size: 88,130 Bytes
764da61
 
 
 
 
 
 
 
 
aceceaf
0e8d6c4
 
764da61
 
 
 
 
 
 
799b5ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e8d6c4
 
764da61
 
0e8d6c4
799b5ff
0e8d6c4
 
 
799b5ff
764da61
 
 
53c5f13
 
 
 
 
0e8d6c4
 
 
 
 
 
 
 
 
 
53c5f13
799b5ff
764da61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ca35f0
 
53c5f13
1ca35f0
 
 
 
 
764da61
53c5f13
0e8d6c4
 
53c5f13
 
764da61
53c5f13
 
 
764da61
 
0e8d6c4
764da61
 
799b5ff
db0dd54
764da61
 
 
53c5f13
 
764da61
 
 
53c5f13
 
764da61
53c5f13
 
764da61
0e8d6c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
764da61
 
 
0e8d6c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a5889d
764da61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e8d6c4
764da61
 
 
 
 
 
0e8d6c4
764da61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
799b5ff
 
764da61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ca35f0
764da61
 
 
 
 
 
 
bc1c926
 
764da61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
799b5ff
 
764da61
b05370c
 
 
 
 
0e8d6c4
764da61
 
b05370c
 
53c5f13
b05370c
764da61
53c5f13
764da61
 
 
 
 
 
 
 
1ca35f0
 
 
 
 
 
 
 
 
 
764da61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e8d6c4
764da61
0e8d6c4
764da61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ca35f0
764da61
1ca35f0
764da61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e8d6c4
764da61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e8d6c4
764da61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e8d6c4
764da61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ca35f0
 
764da61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e8d6c4
764da61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e8d6c4
764da61
 
 
53c5f13
 
764da61
 
1ca35f0
 
 
 
6f1ce89
 
 
0e8d6c4
6f1ce89
 
 
 
53c5f13
 
6f1ce89
 
0e8d6c4
6f1ce89
 
1ca35f0
53c5f13
764da61
0e8d6c4
764da61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc1c926
764da61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e8d6c4
764da61
bc1c926
 
 
 
764da61
 
 
 
0e8d6c4
764da61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e8d6c4
1ca35f0
764da61
 
bc1c926
764da61
0e8d6c4
bc1c926
764da61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e8d6c4
764da61
0e8d6c4
 
 
 
 
 
 
764da61
 
 
 
 
 
 
 
 
 
0e8d6c4
 
764da61
 
 
 
 
 
 
799b5ff
 
764da61
799b5ff
 
 
 
 
 
 
 
 
 
 
 
 
764da61
 
799b5ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
764da61
 
1ca35f0
 
 
 
 
 
 
 
0e8d6c4
799b5ff
1ca35f0
b05370c
 
 
 
0e8d6c4
b05370c
 
 
 
 
 
 
 
 
0e8d6c4
 
 
 
 
b05370c
1ca35f0
 
0e8d6c4
 
 
1ca35f0
 
0e8d6c4
1ca35f0
 
b05370c
0e8d6c4
799b5ff
 
0e8d6c4
 
 
799b5ff
 
0e8d6c4
 
b05370c
764da61
 
b05370c
799b5ff
0e8d6c4
 
b05370c
 
1ca35f0
 
764da61
 
799b5ff
 
 
764da61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e8d6c4
 
764da61
 
 
1ca35f0
0e8d6c4
764da61
 
0e8d6c4
1ca35f0
764da61
0e8d6c4
b05370c
764da61
1ca35f0
 
0e8d6c4
 
 
 
764da61
0e8d6c4
1ca35f0
 
0e8d6c4
764da61
1ca35f0
764da61
 
1ca35f0
764da61
0e8d6c4
799b5ff
1ca35f0
799b5ff
1ca35f0
 
 
764da61
799b5ff
0e8d6c4
764da61
 
 
799b5ff
 
 
b05370c
764da61
 
 
1ca35f0
 
0e8d6c4
 
 
764da61
0e8d6c4
799b5ff
0e8d6c4
764da61
0e8d6c4
 
764da61
53c5f13
764da61
0e8d6c4
764da61
 
0e8d6c4
764da61
799b5ff
764da61
0e8d6c4
799b5ff
 
764da61
0e8d6c4
764da61
 
799b5ff
 
 
 
 
 
 
 
 
 
 
0e8d6c4
 
799b5ff
0e8d6c4
 
764da61
b05370c
764da61
 
 
 
 
 
 
 
 
0e8d6c4
764da61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b05370c
764da61
0e8d6c4
 
764da61
b05370c
764da61
 
 
 
 
 
 
 
1ca35f0
764da61
 
0e8d6c4
764da61
 
 
 
 
 
 
 
 
 
b05370c
0e8d6c4
764da61
 
 
 
 
 
 
 
 
 
 
 
 
 
0e8d6c4
764da61
bc1c926
 
0e8d6c4
bc1c926
 
 
 
0e8d6c4
bc1c926
 
799b5ff
0e8d6c4
 
bc1c926
0e8d6c4
bc1c926
 
 
 
 
 
764da61
bc1c926
0e8d6c4
 
 
764da61
1ca35f0
0e8d6c4
764da61
 
0e8d6c4
764da61
 
 
0e8d6c4
1ca35f0
0e8d6c4
799b5ff
0e8d6c4
 
bc1c926
0e8d6c4
764da61
 
 
 
 
 
 
 
 
 
 
 
 
 
1ca35f0
764da61
0e8d6c4
1ca35f0
764da61
1ca35f0
764da61
 
 
 
 
 
 
0e8d6c4
 
 
 
1ca35f0
0e8d6c4
 
 
1ca35f0
0e8d6c4
 
1ca35f0
0e8d6c4
1ca35f0
 
 
764da61
0e8d6c4
764da61
 
 
0e8d6c4
1ca35f0
0e8d6c4
764da61
 
 
 
0e8d6c4
764da61
0e8d6c4
764da61
 
 
0e8d6c4
764da61
 
 
 
 
 
0e8d6c4
799b5ff
0e8d6c4
764da61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e8d6c4
764da61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e8d6c4
 
764da61
 
 
 
 
 
 
 
0e8d6c4
 
764da61
 
 
 
 
 
 
 
 
 
 
 
53c5f13
0e8d6c4
 
53c5f13
 
 
0e8d6c4
 
53c5f13
0e8d6c4
 
 
 
 
 
 
 
764da61
 
0e8d6c4
764da61
bc1c926
764da61
53c5f13
764da61
 
 
1ca35f0
764da61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ca35f0
0e8d6c4
799b5ff
764da61
 
 
0e8d6c4
799b5ff
764da61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e8d6c4
 
 
764da61
 
799b5ff
 
764da61
799b5ff
0e8d6c4
 
 
 
 
764da61
 
0e8d6c4
764da61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
799b5ff
 
 
 
 
 
 
 
764da61
 
 
 
799b5ff
 
0e8d6c4
 
764da61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc1c926
764da61
 
 
 
 
 
 
0e8d6c4
764da61
 
 
 
 
 
 
 
 
bc1c926
 
 
 
764da61
 
 
 
 
 
0e8d6c4
764da61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e8d6c4
 
764da61
 
 
 
 
 
 
 
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
# /// script
# requires-python = ">=3.11,<3.13"
# dependencies = [
#   "torch>=2.8,<2.10",
#   "numpy>=2.0",
#   "huggingface-hub>=0.34",
#   "safetensors>=0.5",
#   "datasets>=2.19",
#   "tokenizers>=0.20",
#   "bitsandbytes",
#   "torchao",
#   "pyarrow",
# ]
# ///

"""
Smilyai-G1 : Fast Sparse General-Assistant Transformer β€” FSDP2 EDITION (8xH200)
~20B total params | ~2B active per token

v7 β€” DATA-MIX + OBSERVABILITY (on top of v6 host-RAM fixes):

 23. TOKEN-WEIGHTED SOURCE SCHEDULER. v6 picked a source per *document*; a
     stack-v3 document is a whole repository (~60K tokens) vs ~1K for a web
     page, so 20% of docs became ~70% of tokens. Session 3's train-loss drop
     (3.1 -> 1.7) was this, not model progress. Now a deficit scheduler picks
     the source furthest behind its TOKEN quota -> exact mix regardless of
     document length. Zero throughput cost.
 24. Repo cap 262K -> 64K chars so one repo can't monopolise ~15 consecutive
     micro-batches.
 25. stack-v3 arrow batch_size 64 -> 4 rows (each row is a whole repo; this
     was several hundred GB of host RAM across 32 readers).
 26. EOS: session 3 ran with eos_id=0 (no known EOS name found). Now scans the
     tokenizer's added tokens for anything that looks like end-of-text, logs
     what it picked, and honours G1_EOS_TOKEN=<token string> as an override.
 27. PER-SOURCE LOSS. The `folder` tag was the *last appended* document's
     source, not the batch's. Batches are now tagged by MAJORITY source of
     their tokens, and the log prints loss + batch share per source every
     log_every steps (rank-0 local window).
 28. Session-3 note: train loss is NOT comparable across sessions when the
     mix changes. Use [val] (fineweb-edu only) as the progress signal.

Invariant: *** EVERY collective must be executed by EVERY rank, in the same order. ***

RUN:
    export HF_TOKEN=...
    export G1_SESSION_ID=4
    export MAX_TRAINING_HOURS=138
    export G1_WORK_DIR=/some/real/local/disk     # NOT tmpfs (check: df -hT /tmp)
    export MALLOC_ARENA_MAX=2
    # optional: export G1_EOS_TOKEN='<|endoftext|>'
    torchrun --nproc_per_node=8 train_g1_fsdp.py
"""

import os

os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
os.environ.setdefault("TORCHINDUCTOR_COMPILE_THREADS", "1")
os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1")
os.environ.setdefault("HF_DATASETS_DISABLE_PROGRESS_BARS", "1")
os.environ.setdefault("ARROW_DEFAULT_MEMORY_POOL", "system")
os.environ.setdefault("OMP_NUM_THREADS", "4")
try:
    import ctypes
    _libc = ctypes.CDLL("libc.so.6")
    _libc.mallopt(-8, 2)            # M_ARENA_MAX
    _libc.mallopt(-1, 128 * 1024)   # M_TRIM_THRESHOLD
except Exception:
    pass

import gc, json, time, math, random, logging, threading, queue, shutil, collections, datetime as _dt
from dataclasses import dataclass, asdict
from typing import Optional, Tuple, List, Iterator

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributed as dist
import torch.multiprocessing as mp
from torch.utils.data import Dataset, DataLoader

try:
    from torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy
except ImportError:
    from torch.distributed._composable.fsdp import fully_shard, MixedPrecisionPolicy

from torch.distributed.tensor import DTensor, distribute_tensor
from torch.distributed.checkpoint.state_dict import (
    get_model_state_dict, set_model_state_dict,
    get_optimizer_state_dict, set_optimizer_state_dict,
    StateDictOptions,
)

import triton
import triton.language as tl

from huggingface_hub import HfApi, hf_hub_download, upload_file, login as hf_login

try:
    import bitsandbytes as bnb
    HAS_BNB = True
except ImportError:
    HAS_BNB = False

try:
    from safetensors.torch import save_file as st_save
    HAS_ST = True
except ImportError:
    HAS_ST = False

try:
    from flash_attn import flash_attn_func
    HAS_FLASH = True
except ImportError:
    HAS_FLASH = False

try:
    from torchao.float8 import convert_to_float8_training, Float8LinearConfig
    HAS_FP8 = True
except ImportError:
    HAS_FP8 = False
    convert_to_float8_training = None
    Float8LinearConfig = None

os.environ["TOKENIZERS_PARALLELISM"] = "false"
torch.set_float32_matmul_precision('high')
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
torch.backends.cuda.enable_flash_sdp(True)
torch.backends.cuda.enable_mem_efficient_sdp(True)

try:
    import torch._dynamo
    torch._dynamo.config.cache_size_limit = 64
    torch._dynamo.config.suppress_errors = True
    torch._dynamo.config.capture_scalar_outputs = True
except Exception:
    pass

logging.basicConfig(level=logging.INFO, format='%(asctime)s | %(message)s', datefmt='%H:%M:%S')
for _noisy in ("httpx", "httpcore", "urllib3", "filelock",
               "huggingface_hub", "huggingface_hub.hf_api",
               "huggingface_hub.file_download", "datasets", "fsspec"):
    logging.getLogger(_noisy).setLevel(logging.WARNING)

log = logging.getLogger("smilyai-g1-fsdp")
_MODULE_IS_MASTER = os.environ.get("RANK", "0") == "0"
if _MODULE_IS_MASTER:
    log.info(f"[env] flash_attn={HAS_FLASH} | bnb={HAS_BNB}")

# ─────────────────────────────────────────────────────────────────────────────
#  HF SETUP / WORK DIR / HOST-MEMORY TOOLS
# ─────────────────────────────────────────────────────────────────────────────
HF_TOKEN    = os.environ.get("HF_TOKEN", "")
SESSION_ID  = int(os.environ.get("G1_SESSION_ID", "4"))
REPO_PREFIX = "hugging-science/Smilyai-G1-20B-v2-session-"
HF_MODEL_REPO = f"{REPO_PREFIX}{SESSION_ID:03d}"

if not HF_TOKEN:
    if _MODULE_IS_MASTER:
        log.warning("[hf] HF_TOKEN not set β€” uploads/downloads will fail. export HF_TOKEN=...")
else:
    try:
        hf_login(token=HF_TOKEN)
        if _MODULE_IS_MASTER:
            log.info("[hf] logged in")
    except Exception as e:
        if _MODULE_IS_MASTER:
            log.warning(f"[hf] login failed: {e}")

hf_api = HfApi()

def _is_ram_backed(path: str) -> bool:
    try:
        best = ("", "")
        with open("/proc/mounts") as f:
            for line in f:
                parts = line.split()
                if len(parts) >= 3 and path.startswith(parts[1]) and len(parts[1]) > len(best[0]):
                    best = (parts[1], parts[2])
        return best[1] in ("tmpfs", "ramfs")
    except Exception:
        return False

_WORK = os.environ.get("G1_WORK_DIR", "/tmp")
if _is_ram_backed(_WORK):
    _fb = os.path.join(os.getcwd(), "g1_work")
    if _MODULE_IS_MASTER:
        log.warning(f"[disk] {_WORK} is RAM-backed β€” a 127GB checkpoint there IS host RAM. "
                    f"Falling back to {_fb}. Set G1_WORK_DIR to a real local disk.")
    _WORK = _fb
LOCAL_CACHE   = os.path.join(_WORK, "g1_cache")
TEMP_CKPT_DIR = os.path.join(_WORK, "g1_ckpts")
os.makedirs(LOCAL_CACHE, exist_ok=True)
os.makedirs(TEMP_CKPT_DIR, exist_ok=True)

def host_mem_str() -> str:
    out = []
    try:
        with open("/proc/self/status") as f:
            for line in f:
                if line.startswith("VmRSS:"):
                    out.append(f"rss={int(line.split()[1])/1024**2:.1f}GB"); break
        with open("/proc/meminfo") as f:
            for line in f:
                if line.startswith("MemAvailable:"):
                    out.append(f"avail={int(line.split()[1])/1024**2:.0f}GB"); break
        for cur, mx in (("/sys/fs/cgroup/memory.current", "/sys/fs/cgroup/memory.max"),
                        ("/sys/fs/cgroup/memory/memory.usage_in_bytes",
                         "/sys/fs/cgroup/memory/memory.limit_in_bytes")):
            try:
                c = int(open(cur).read()); m = open(mx).read().strip()
                if m != "max" and int(m) < (1 << 60):
                    out.append(f"cgroup={c/1024**3:.0f}/{int(m)/1024**3:.0f}GB"); break
            except Exception:
                continue
    except Exception:
        pass
    return "host " + " ".join(out) if out else "host=?"

def start_mem_watchdog(rank: int):
    def _loop():
        last = 0.0
        while True:
            time.sleep(15)
            try:
                avail, total = None, 0.0
                with open("/proc/meminfo") as f:
                    for line in f:
                        if line.startswith("MemTotal:"):     total = int(line.split()[1]) / 1024**2
                        if line.startswith("MemAvailable:"): avail = int(line.split()[1]) / 1024**2
                if avail is not None and avail < max(0.05 * total, 8.0) and time.time() - last > 60:
                    log.error(f"[mem-watchdog] rank={rank} HOST RAM CRITICAL β€” {host_mem_str()}")
                    last = time.time()
            except Exception:
                pass
    threading.Thread(target=_loop, daemon=True).start()

MAX_HOURS  = float(os.environ.get("MAX_TRAINING_HOURS", "138.0"))
START_TIME = time.time()
def elapsed_h():   return (time.time() - START_TIME) / 3600
def remaining_h(): return MAX_HOURS - elapsed_h()
def should_stop_local():
    if elapsed_h() >= MAX_HOURS:
        log.info("[time] budget done"); return True
    return False
def vram_gb():       return torch.cuda.memory_allocated() / 1024**3
def vram_total_gb(): return torch.cuda.get_device_properties(torch.cuda.current_device()).total_memory / 1024**3
def vram_str():      return f"{vram_gb():.1f}/{vram_total_gb():.0f}GB"

def ensure_repo():
    try:
        hf_api.repo_info(repo_id=HF_MODEL_REPO, repo_type="model", token=HF_TOKEN)
    except Exception:
        hf_api.create_repo(repo_id=HF_MODEL_REPO, repo_type="model", private=False, token=HF_TOKEN)
        log.info(f"[hf] created {HF_MODEL_REPO}")
    log.info(f"[hf] USING REPO: {HF_MODEL_REPO}")

def upload_to_hf(local: str, remote: str) -> bool:
    try:
        upload_file(path_or_fileobj=local, path_in_repo=remote,
                    repo_id=HF_MODEL_REPO, repo_type="model", token=HF_TOKEN)
        log.info(f"[hf] up {remote}")
        return True
    except Exception as e:
        log.error(f"[hf] upload failed: {e}")
        return False

METRICS_FILE = os.path.join(TEMP_CKPT_DIR, f"metrics_session_{SESSION_ID:03d}.jsonl")
def log_metrics(**kw):
    m = {'timestamp': time.time(), 'elapsed_hours': elapsed_h(), 'session_id': SESSION_ID, **kw}
    with open(METRICS_FILE, 'a') as f:
        f.write(json.dumps(m) + '\n')
    return m
def upload_metrics():
    if os.path.exists(METRICS_FILE):
        upload_to_hf(METRICS_FILE, f"metrics_session_{SESSION_ID:03d}.jsonl")

# ─────────────────────────────────────────────────────────────────────────────
#  MOTIVATION / PROGRESS BOARD
# ─────────────────────────────────────────────────────────────────────────────
import datetime
try:
    import matplotlib; matplotlib.use("Agg"); import matplotlib.pyplot as plt
    HAS_MPL = True
except ImportError:
    HAS_MPL = False

SAMPLES_FILE = os.path.join(TEMP_CKPT_DIR, "samples.md")
SUMMARY_FILE = os.path.join(TEMP_CKPT_DIR, "summary.jsonl")
PROGRESS_MD  = os.path.join(TEMP_CKPT_DIR, "PROGRESS.md")
_step_clock  = []
_tok         = None

def _real_steps_per_hour():
    if len(_step_clock) < 2: return None
    (s0, t0), (s1, t1) = _step_clock[0], _step_clock[-1]
    if t1 - t0 < 30 or s1 <= s0: return None
    return (s1 - s0) / (t1 - t0) * 3600

def sessions_left(step, total):
    sph = _real_steps_per_hour()
    if sph is None: return None
    usable_h = max(MAX_HOURS - 0.75, 8.0)
    return max(math.ceil((total - step) / max(sph * usable_h, 1)), 0)

def session_banner():
    try:
        files = hf_api.list_repo_files(repo_id=HF_MODEL_REPO, repo_type="model", token=HF_TOKEN)
        pts = [f for f in files if f.endswith(".pt")]
        latest = max([int(f.split("step")[-1].split(".")[0]) for f in pts]) if pts else 0
    except Exception:
        pts, latest = [], 0
    log.info("🌱" * 25)
    log.info(f"WELCOME BACK β€” feed #{len(pts)+1}. Smilyai survived {len(pts)} sessions.")
    log.info(f"Latest checkpoint on the Hub: step {latest:,}")
    log.info("🌱" * 25)

def _bootstrap_from_hub(local, remote):
    try:
        src = hf_hub_download(HF_MODEL_REPO, remote, cache_dir=TEMP_CKPT_DIR, token=HF_TOKEN)
        shutil.copy(src, local)
        log.info(f"[motiv] restored {remote}")
    except Exception:
        pass

def _get_tokenizer():
    global _tok
    if _tok is None:
        try:
            _tok = get_tokenizer(Config())
        except Exception as e:
            log.warning(f"[tokenizer] failed: {e}")
            _tok = None
    return _tok

DOMAIN_TOKEN = ""

@torch.no_grad()
def make_sample(model, prompt="def fibonacci(n):", max_new=48, temp=0.8, top_p=0.95):
    try:
        tok = _get_tokenizer()
        if tok is None: return None
        token_ids = tok.encode(DOMAIN_TOKEN + prompt, add_special_tokens=False).ids[-128:]
        if not token_ids: return None
        device = next(model.parameters()).device
        ids = torch.tensor([token_ids], device=device)
    except Exception as e:
        log.warning(f"[sample] tokenizer error: {e}"); return None

    gen = torch.Generator(device=device); gen.manual_seed(1234)
    was_training = model.training
    model.eval()
    try:
        for _ in range(max_new):
            with torch.amp.autocast('cuda', dtype=model.cfg.dtype):
                logits, _ = model(ids[:, -model.cfg.max_len:], None)
            p = F.softmax(logits[:, -1].float() / temp, dim=-1)
            sp, si = torch.sort(p, descending=True)
            keep = (torch.cumsum(sp, -1) - sp) < top_p
            sp = sp * keep
            sp = sp / sp.sum(-1, keepdim=True).clamp_min(1e-9)
            nxt = si.gather(-1, torch.multinomial(sp, 1, generator=gen))
            ids = torch.cat([ids, nxt], dim=1)
    finally:
        if was_training: model.train()
    try:
        return tok.decode(ids[0].tolist())
    except Exception as e:
        log.warning(f"[sample] decode error: {e}")
        return None

def record_sample(model, step, is_master: bool):
    txt = make_sample(model)
    if not is_master:
        return
    with open(SAMPLES_FILE, "a") as f:
        f.write(f"\n## step {step:,} β€” {datetime.datetime.now():%d %b %H:%M}\n> {txt or '(skipped)'}\n")
    upload_to_hf(SAMPLES_FILE, "samples.md")
    if txt: log.info(f"[motiv] sample Β» {txt[:120]!r}")

def make_loss_chart():
    if not (HAS_MPL and os.path.exists(METRICS_FILE)): return
    tr, va = [], []
    for line in open(METRICS_FILE):
        try: m = json.loads(line)
        except Exception: continue
        if "loss" in m and "step" in m: tr.append((m["step"], m["loss"]))
        elif "val_loss" in m and "step" in m: va.append((m["step"], m["val_loss"]))
    if not tr: return
    fig, ax = plt.subplots(figsize=(10, 5))
    ax.plot(*zip(*tr), lw=1, label="train")
    if va: ax.plot(*zip(*va), "o-", color="tab:red", label="val")
    ax.set_xlabel("step"); ax.set_ylabel("loss"); ax.grid(alpha=.3); ax.legend()
    ax.set_title("Smilyai-G1 20B learning curve 🌱")
    p = os.path.join(TEMP_CKPT_DIR, "loss_curve.png")
    fig.savefig(p, dpi=110, bbox_inches="tight"); plt.close(fig)
    upload_to_hf(p, "loss_curve.png"); os.remove(p)

def update_progress_md(cfg, step, epoch, tr_loss, val_loss):
    rec = {"t": f"{datetime.datetime.now():%d %b %H:%M}", "step": step, "epoch": epoch,
           "loss": round(tr_loss, 4) if tr_loss is not None else None,
           "val": round(val_loss, 4) if (val_loss is not None and val_loss == val_loss) else None}
    with open(SUMMARY_FILE, "a") as f: f.write(json.dumps(rec) + "\n")
    sl = sessions_left(step, cfg.total_steps); sl = f"~{sl}" if sl is not None else "?"
    lines = ["# Smilyai-G1 20B · live progress 🌱", "",
             f"**{100*step/cfg.total_steps:.1f}% trained** Β· estimated clicks left: **{sl}** πŸ–±οΈ", "",
             "> Note: train loss is only comparable within a session β€” the data mix changed between "
             "sessions 2, 3 and 4. Use **val loss** (fineweb-edu only) as the progress signal.", "",
             "| when | step | train loss | val loss |", "|---|---|---|---|"]
    for line in open(SUMMARY_FILE):
        try: r = json.loads(line)
        except Exception: continue
        lines.append(f"| {r['t']} | {r['step']:,} | {r['loss'] if r['loss'] is not None else 'β€”'} "
                     f"| {r['val'] if r['val'] is not None else 'β€”'} |")
    with open(PROGRESS_MD, "w") as f: f.write("\n".join(lines) + "\n")
    upload_to_hf(PROGRESS_MD, "PROGRESS.md")

# ─────────────────────────────────────────────────────────────────────────────
#  CONFIG
# ─────────────────────────────────────────────────────────────────────────────
@dataclass
class Config:
    vocab_size: int = 131_072

    d_model:    int   = 2048
    n_layers:   int   = 32
    n_heads:    int   = 16
    n_kv_heads: int   = 4
    max_len:    int   = 2048
    rope_theta: float = 500_000.0

    n_experts:          int   = 56
    top_k:              int   = 2
    expert_hidden_mult: float = 0.875
    shared_hidden_mult: float = 2.0
    n_shared_experts:   int   = 1
    aux_loss_coef:      float = 0.01
    bias_update_rate:  float = 0.001
    bias_update_every: int   = 10
    bias_cap:          float = 2.0
    bias_decay:        float = 0.0005
    usage_ema_decay:   float = 0.99
    moe_block_m:        int   = 64

    tie_embeddings:   bool  = True

    muon_lr:     float = 0.02
    muon_min_lr: float = 0.002
    muon_mom:    float = 0.95
    adamw_lr:    float = 1.5e-4
    adamw_min_lr:float = 1.5e-5
    beta1:       float = 0.9
    beta2:       float = 0.95
    wd:          float = 0.1
    grad_clip:   float = 1.0
    warmup:      int   = 3000
    total_steps: int   = 300_000

    micro_batch: int = 2
    grad_accum:  int = 16

    log_every:   int = 10
    eval_every:  int = 500
    ckpt_every:  int = 1000

    enable_dpo_bursts: bool = False
    dpo_start_step:    int  = 250_000
    dpo_every:         int  = 500
    dpo_beta:          float= 0.1

    # (repo_id, split, text_field, TOKEN weight, hf_config_name_or_None)
    # v7: weights are honoured by TOKEN count (deficit scheduler), not by document count.
    dataset_sources: tuple = (
        ("HuggingFaceFW/fineweb-edu",                  "train", "text",     200_000_000_000, None),
        ("HuggingFaceCode/stack-v3-train",             "train", "content",  100_000_000_000, None),
        ("opencsg/chinese-fineweb-edu",                "train", "text",      60_000_000_000, None),
        ("hotchpotch/fineweb-2-edu-japanese",          "train", "text",      40_000_000_000, None),
        ("KORMo-Team/korean-web-collection",           "train", "text",      30_000_000_000, None),
        ("HuggingFaceFW/fineweb",                      "train", "text",      70_000_000_000, "sample-350BT"),
    )
    tokenizer_repo: str = "Smilyai-labs/Smilyai-U1-B-Tokenizer"

    tokenizer_workers: int = 4
    prefetch_shards: int = 20
    shuffle_buffer: int = 500

    use_compile: bool = False
    use_fp8: bool = False

    @property
    def dtype(self): return torch.bfloat16
    @property
    def head_dim(self): return self.d_model // self.n_heads
    def tokens_per_step(self, bs, world_size=1): return bs * self.grad_accum * self.max_len * world_size

    def arch_fingerprint(self) -> dict:
        return {
            "vocab_size": self.vocab_size, "d_model": self.d_model,
            "n_layers": self.n_layers, "n_heads": self.n_heads,
            "n_kv_heads": self.n_kv_heads, "n_experts": self.n_experts,
            "top_k": self.top_k, "expert_hidden_mult": self.expert_hidden_mult,
            "shared_hidden_mult": self.shared_hidden_mult,
            "tie_embeddings": self.tie_embeddings,
        }

# ─────────────────────────────────────────────────────────────────────────────
#  DISTRIBUTED HELPERS
# ─────────────────────────────────────────────────────────────────────────────
def dist_ready() -> bool:
    return dist.is_available() and dist.is_initialized()

def distributed_mean(value: float, device: torch.device) -> float:
    t = torch.tensor(float(value), dtype=torch.float64, device=device)
    if dist_ready():
        dist.all_reduce(t, op=dist.ReduceOp.SUM)
        t /= dist.get_world_size()
    return t.item()

def broadcast_flag(value: bool, device: torch.device) -> bool:
    flag = torch.tensor(int(bool(value)), dtype=torch.int32, device=device)
    if dist_ready():
        dist.broadcast(flag, src=0)
    return bool(flag.item())

def all_ok(ok: bool, device: torch.device) -> bool:
    t = torch.tensor(int(bool(ok)), dtype=torch.int32, device=device)
    if dist_ready():
        dist.all_reduce(t, op=dist.ReduceOp.MIN)
    return bool(t.item())

def distributed_should_stop(device: torch.device, is_master: bool, step: int, total_steps: int) -> bool:
    stop = (should_stop_local() or step >= total_steps) if is_master else False
    return broadcast_flag(stop, device)

# ─────────────────────────────────────────────────────────────────────────────
#  TRITON KERNELS
# ─────────────────────────────────────────────────────────────────────────────
@triton.jit
def smilyai_rmsnorm_fwd(X, W, Y, RSTD, stride_row, N, eps, BLOCK_N: tl.constexpr):
    row = tl.program_id(0)
    X += row * stride_row; Y += row * stride_row
    cols = tl.arange(0, BLOCK_N); mask = cols < N
    x = tl.load(X + cols, mask=mask, other=0.0).to(tl.float32)
    var = tl.sum(x * x, axis=0) / N
    rstd = 1.0 / tl.sqrt(var + eps)
    tl.store(RSTD + row, rstd)
    w = tl.load(W + cols, mask=mask, other=0.0).to(tl.float32)
    tl.store(Y + cols, (x * rstd * w).to(Y.dtype.element_ty), mask=mask)

@triton.jit
def smilyai_rmsnorm_bwd(X, W, DY, DX, DW_PARTIAL, RSTD, stride_row, N, BLOCK_N: tl.constexpr):
    row = tl.program_id(0)
    X += row * stride_row; DY += row * stride_row; DX += row * stride_row
    cols = tl.arange(0, BLOCK_N); mask = cols < N
    x  = tl.load(X  + cols, mask=mask, other=0.0).to(tl.float32)
    dy = tl.load(DY + cols, mask=mask, other=0.0).to(tl.float32)
    w  = tl.load(W  + cols, mask=mask, other=0.0).to(tl.float32)
    rstd = tl.load(RSTD + row)
    wdy  = w * dy
    s    = tl.sum(x * wdy, axis=0)
    dx   = rstd * wdy - (rstd * rstd * rstd / N) * x * s
    tl.store(DX + cols, dx.to(DX.dtype.element_ty), mask=mask)
    tl.store(DW_PARTIAL + row * N + cols, dy * x * rstd, mask=mask)

@triton.jit
def smilyai_swiglu_fwd(GATE, UP, OUT, N, BLOCK: tl.constexpr):
    pid  = tl.program_id(0)
    offs = pid * BLOCK + tl.arange(0, BLOCK); mask = offs < N
    g = tl.load(GATE + offs, mask=mask, other=0.0).to(tl.float32)
    u = tl.load(UP   + offs, mask=mask, other=0.0).to(tl.float32)
    tl.store(OUT + offs, (g * tl.sigmoid(g) * u).to(OUT.dtype.element_ty), mask=mask)

@triton.jit
def smilyai_swiglu_bwd(GATE, UP, DOUT, DGATE, DUP, N, BLOCK: tl.constexpr):
    pid  = tl.program_id(0)
    offs = pid * BLOCK + tl.arange(0, BLOCK); mask = offs < N
    g    = tl.load(GATE + offs, mask=mask, other=0.0).to(tl.float32)
    u    = tl.load(UP   + offs, mask=mask, other=0.0).to(tl.float32)
    dout = tl.load(DOUT + offs, mask=mask, other=0.0).to(tl.float32)
    s    = tl.sigmoid(g); silu = g * s; dsilu = s * (1.0 + g * (1.0 - s))
    tl.store(DGATE + offs, (dout * u * dsilu).to(DGATE.dtype.element_ty), mask=mask)
    tl.store(DUP   + offs, (dout * silu    ).to(DUP.dtype.element_ty),   mask=mask)

class _TritonRMSNormFn(torch.autograd.Function):
    @staticmethod
    @torch.compiler.disable
    def forward(ctx, x, w, eps):
        orig = x.shape; x2 = x.reshape(-1, orig[-1]).contiguous()
        M, N = x2.shape; y = torch.empty_like(x2)
        rstd = torch.empty(M, device=x.device, dtype=torch.float32)
        BN = triton.next_power_of_2(N)
        w = w.contiguous()
        smilyai_rmsnorm_fwd[(M,)](x2, w, y, rstd, x2.stride(0), N, eps, BLOCK_N=BN)
        ctx.save_for_backward(x2, w, rstd); ctx.BN = BN; ctx.orig = orig
        return y.view(orig)

    @staticmethod
    @torch.compiler.disable
    def backward(ctx, dy):
        x2, w, rstd = ctx.saved_tensors; M, N = x2.shape
        dy2 = dy.reshape(M, N).contiguous()
        dx  = torch.empty_like(x2)
        dwp = torch.empty(M, N, device=x2.device, dtype=torch.float32)
        smilyai_rmsnorm_bwd[(M,)](x2, w, dy2, dx, dwp, rstd, x2.stride(0), N, BLOCK_N=ctx.BN)
        return dx.view(ctx.orig), dwp.sum(0).to(w.dtype), None

class RMSNorm(nn.Module):
    def __init__(self, dim: int, eps: float = 1e-6):
        super().__init__(); self.eps = eps; self.w = nn.Parameter(torch.ones(dim))
    def forward(self, x):
        if x.is_cuda: return _TritonRMSNormFn.apply(x, self.w, self.eps)
        x32 = x.float()
        return (x32 * torch.rsqrt(x32.pow(2).mean(-1, keepdim=True) + self.eps) * self.w).to(x.dtype)

class _FusedSwiGLUFn(torch.autograd.Function):
    @staticmethod
    @torch.compiler.disable
    def forward(ctx, gate, up):
        shape = gate.shape; g = gate.reshape(-1).contiguous(); u = up.reshape(-1).contiguous()
        N = g.numel(); out = torch.empty_like(g); BLOCK = 1024
        smilyai_swiglu_fwd[(triton.cdiv(N, BLOCK),)](g, u, out, N, BLOCK=BLOCK)
        ctx.save_for_backward(g, u); ctx.shape = shape; ctx.BLOCK = BLOCK
        return out.view(shape)

    @staticmethod
    @torch.compiler.disable
    def backward(ctx, dout):
        g, u = ctx.saved_tensors; N = g.numel()
        dout_flat = dout.reshape(-1).contiguous()
        dgate = torch.empty_like(g); dup = torch.empty_like(u)
        smilyai_swiglu_bwd[(triton.cdiv(N, ctx.BLOCK),)](g, u, dout_flat, dgate, dup, N, BLOCK=ctx.BLOCK)
        return dgate.view(ctx.shape), dup.view(ctx.shape)

def fused_swiglu(gate, up):
    return _FusedSwiGLUFn.apply(gate, up) if gate.is_cuda else F.silu(gate) * up

def precompute_rope(head_dim, max_len, theta, device):
    inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2, device=device, dtype=torch.float32) / head_dim))
    pos = torch.arange(max_len, device=device, dtype=torch.float32)
    freqs = torch.outer(pos, inv_freq)
    return freqs.cos(), freqs.sin()

def apply_rope(x, cos, sin):
    dt = x.dtype
    L = x.shape[1]; h = x.shape[-1] // 2
    c = cos[:L].unsqueeze(0).unsqueeze(2); s = sin[:L].unsqueeze(0).unsqueeze(2)
    x32 = x.float()
    x1, x2 = x32[..., :h], x32[..., h:]
    return torch.cat([x1 * c - x2 * s, x2 * c + x1 * s], dim=-1).to(dt)

class GQAAttention(nn.Module):
    def __init__(self, cfg: Config, layer_idx: int):
        super().__init__()
        self.n_heads    = cfg.n_heads
        self.n_kv_heads = cfg.n_kv_heads
        self.hd         = cfg.head_dim
        d = cfg.d_model
        self.wq = nn.Linear(d, self.n_heads    * self.hd, bias=False)
        self.wk = nn.Linear(d, self.n_kv_heads * self.hd, bias=False)
        self.wv = nn.Linear(d, self.n_kv_heads * self.hd, bias=False)
        self.wo = nn.Linear(self.n_heads * self.hd, d, bias=False)
        self.q_norm = RMSNorm(self.hd)
        self.k_norm = RMSNorm(self.hd)
        std = 0.02
        for m in [self.wq, self.wk, self.wv]: nn.init.normal_(m.weight, std=std)
        nn.init.normal_(self.wo.weight, std=std / math.sqrt(2 * cfg.n_layers))

    def _attend(self, q, k, v):
        if HAS_FLASH and q.is_cuda and q.dtype in (torch.bfloat16, torch.float16):
            return flash_attn_func(q, k, v, causal=True)
        B, L, Hq, D = q.shape; Hkv = k.shape[2]
        qt = q.transpose(1,2); kt = k.transpose(1,2); vt = v.transpose(1,2)
        if Hq != Hkv:
            rep = Hq // Hkv
            kt = kt.repeat_interleave(rep, 1); vt = vt.repeat_interleave(rep, 1)
        out = F.scaled_dot_product_attention(qt, kt, vt, is_causal=True)
        return out.transpose(1, 2)

    def forward(self, x, cos, sin):
        B, L, _ = x.shape
        q = self.wq(x).view(B, L, self.n_heads,    self.hd)
        k = self.wk(x).view(B, L, self.n_kv_heads, self.hd)
        v = self.wv(x).view(B, L, self.n_kv_heads, self.hd)
        q, k = self.q_norm(q), self.k_norm(k)
        q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin)
        out = self._attend(q, k, v)
        return self.wo(out.reshape(B, L, -1))

# ─────────────────────────────────────────────────────────────────────────────
#  FUSED GROUPED-GEMM MOE DISPATCH
# ─────────────────────────────────────────────────────────────────────────────
_moe_autotune_configs = [
    triton.Config({"BLOCK_N": 64,  "BLOCK_K": 32}, num_warps=4, num_stages=3),
    triton.Config({"BLOCK_N": 128, "BLOCK_K": 32}, num_warps=8, num_stages=3),
    triton.Config({"BLOCK_N": 128, "BLOCK_K": 64}, num_warps=8, num_stages=4),
    triton.Config({"BLOCK_N": 64,  "BLOCK_K": 64}, num_warps=4, num_stages=4),
]

@triton.autotune(configs=_moe_autotune_configs, key=["K", "N"])
@triton.jit
def _moe_gemm_kernel(
    A_ptr, B_ptr, C_ptr, block_expert_ptr,
    M_padded, K, N,
    stride_am, stride_ak,
    stride_be, stride_bk, stride_bn,
    stride_cm, stride_cn,
    BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr,
):
    pid_m = tl.program_id(0)
    pid_n = tl.program_id(1)
    e     = tl.load(block_expert_ptr + pid_m).to(tl.int64)
    offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
    offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    offs_k = tl.arange(0, BLOCK_K)
    m_mask = offs_m < M_padded
    n_mask = offs_n < N
    a_ptrs = A_ptr + offs_m[:, None] * stride_am + offs_k[None, :] * stride_ak
    b_ptrs = B_ptr + e * stride_be + offs_k[:, None] * stride_bk + offs_n[None, :] * stride_bn
    acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
    for k0 in range(0, K, BLOCK_K):
        k_mask = (k0 + offs_k) < K
        a = tl.load(a_ptrs, mask=m_mask[:, None] & k_mask[None, :], other=0.0)
        b = tl.load(b_ptrs, mask=k_mask[:, None] & n_mask[None, :], other=0.0)
        acc    = tl.dot(a, b, acc)
        a_ptrs += BLOCK_K * stride_ak
        b_ptrs += BLOCK_K * stride_bk
    tl.store(
        C_ptr + offs_m[:, None] * stride_cm + offs_n[None, :] * stride_cn,
        acc.to(tl.bfloat16), mask=m_mask[:, None] & n_mask[None, :],
    )

def _grouped_linear_raw(A, W, block_expert, M_padded, transpose, BM):
    E, OUT, IN = W.shape
    if not transpose:
        K, N = IN, OUT; stride_bk = W.stride(2); stride_bn = W.stride(1)
    else:
        K, N = OUT, IN; stride_bk = W.stride(1); stride_bn = W.stride(2)
    C    = torch.empty((M_padded, N), device=A.device, dtype=torch.bfloat16)
    grid = lambda META: (triton.cdiv(M_padded, BM), triton.cdiv(N, META["BLOCK_N"]))
    _moe_gemm_kernel[grid](
        A, W, C, block_expert, M_padded, K, N,
        A.stride(0), A.stride(1),
        W.stride(0), stride_bk, stride_bn,
        C.stride(0), C.stride(1),
        BLOCK_M=BM,
    )
    return C

@triton.autotune(configs=_moe_autotune_configs, key=["K", "N"], reset_to_zero=["DW_ptr"])
@triton.jit
def _moe_dw_kernel(
    A_ptr, DC_ptr, DW_ptr, block_expert_ptr,
    M_padded, K, N,
    stride_am, stride_ak,
    stride_dcm, stride_dcn,
    stride_dwe, stride_dwn, stride_dwk,
    BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr,
):
    pid_m = tl.program_id(0)
    pid_n = tl.program_id(1)
    pid_k = tl.program_id(2)
    e     = tl.load(block_expert_ptr + pid_m).to(tl.int64)
    offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
    offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    offs_k = pid_k * BLOCK_K + tl.arange(0, BLOCK_K)
    m_mask = offs_m < M_padded
    n_mask = offs_n < N
    k_mask = offs_k < K
    a  = tl.load(A_ptr  + offs_m[:, None] * stride_am  + offs_k[None, :] * stride_ak,
                 mask=m_mask[:, None] & k_mask[None, :], other=0.0)
    dc = tl.load(DC_ptr + offs_m[:, None] * stride_dcm + offs_n[None, :] * stride_dcn,
                 mask=m_mask[:, None] & n_mask[None, :], other=0.0)
    tl.atomic_add(
        DW_ptr + e * stride_dwe + offs_n[:, None] * stride_dwn + offs_k[None, :] * stride_dwk,
        tl.dot(tl.trans(dc), a),
        mask=n_mask[:, None] & k_mask[None, :],
    )

def _grouped_dw_raw(A, dC, block_expert, E, OUT, IN, M_padded, BM):
    DW   = torch.zeros((E, OUT, IN), device=A.device, dtype=torch.float32)
    grid = lambda META: (
        triton.cdiv(M_padded, BM),
        triton.cdiv(OUT, META["BLOCK_N"]),
        triton.cdiv(IN,  META["BLOCK_K"]),
    )
    _moe_dw_kernel[grid](
        A, dC, DW, block_expert, M_padded, IN, OUT,
        A.stride(0), A.stride(1),
        dC.stride(0), dC.stride(1),
        DW.stride(0), DW.stride(1), DW.stride(2),
        BLOCK_M=BM,
    )
    return DW

class GroupedLinearFn(torch.autograd.Function):
    @staticmethod
    def forward(ctx, A, W, block_expert, padded_offsets, M_padded, BM):
        A = A.contiguous().to(torch.bfloat16)
        W = W.contiguous()
        C = _grouped_linear_raw(A, W, block_expert, M_padded, False, BM)
        ctx.save_for_backward(A, W, block_expert, padded_offsets)
        ctx.M_padded = M_padded
        ctx.BM       = BM
        return C

    @staticmethod
    def backward(ctx, dC):
        A, W, block_expert, _ = ctx.saved_tensors
        dC = dC.contiguous().to(torch.bfloat16)
        dA = _grouped_linear_raw(dC, W, block_expert, ctx.M_padded, True, ctx.BM) \
             if ctx.needs_input_grad[0] else None
        dW = _grouped_dw_raw(A, dC, block_expert, W.shape[0], W.shape[1], W.shape[2],
                             ctx.M_padded, ctx.BM).to(W.dtype) \
             if ctx.needs_input_grad[1] else None
        return dA, dW, None, None, None, None

def moe_align_block_size(expert_ids, num_experts, block_size, device):
    counts        = torch.bincount(expert_ids, minlength=num_experts)
    padded_counts = ((counts + block_size - 1) // block_size) * block_size
    padded_offsets      = torch.zeros(num_experts + 1, dtype=torch.long, device=device)
    padded_offsets[1:]  = torch.cumsum(padded_counts, dim=0)
    orig_offsets        = torch.zeros(num_experts + 1, dtype=torch.long, device=device)
    orig_offsets[1:]    = torch.cumsum(counts, dim=0)
    total_padded          = int(padded_offsets[-1].item())
    sort_idx              = torch.argsort(expert_ids, stable=True)
    num_blocks_per_expert = padded_counts // block_size
    block_expert          = torch.repeat_interleave(
        torch.arange(num_experts, device=device), num_blocks_per_expert
    )
    n_rows               = expert_ids.numel()
    arange_total         = torch.arange(n_rows, device=device)
    sorted_expert_of_row = expert_ids[sort_idx]
    row_within_expert    = arange_total - orig_offsets[sorted_expert_of_row]
    dest                 = padded_offsets[sorted_expert_of_row] + row_within_expert
    perm       = torch.full((total_padded,), -1, dtype=torch.long, device=device)
    perm[dest] = sort_idx
    return perm, block_expert, total_padded, padded_offsets

class MoEFFN(nn.Module):
    def __init__(self, cfg: Config, layer_idx: int):
        super().__init__()
        d = cfg.d_model
        h = int(d * cfg.expert_hidden_mult)
        E = cfg.n_experts
        self.E = E; self.d = d; self.h = h
        self.top_k          = cfg.top_k
        self.aux_loss_coef  = cfg.aux_loss_coef
        self.block_m        = cfg.moe_block_m

        self.gate_w = nn.Parameter(torch.empty(E, h, d))
        self.up_w   = nn.Parameter(torch.empty(E, h, d))
        self.down_w = nn.Parameter(torch.empty(E, d, h))
        nn.init.normal_(self.gate_w, std=0.02)
        nn.init.normal_(self.up_w,   std=0.02)
        nn.init.normal_(self.down_w, std=0.02 / math.sqrt(2 * cfg.n_layers))

        self.router = nn.Linear(d, E, bias=False)
        nn.init.normal_(self.router.weight, std=0.02)

        sh = int(d * cfg.shared_hidden_mult)
        self.shared_gate = nn.Linear(d, sh, bias=False)
        self.shared_up   = nn.Linear(d, sh, bias=False)
        self.shared_down = nn.Linear(sh, d, bias=False)
        nn.init.normal_(self.shared_gate.weight, std=0.02)
        nn.init.normal_(self.shared_up.weight,   std=0.02)
        nn.init.normal_(self.shared_down.weight, std=0.02 / math.sqrt(2 * cfg.n_layers))

        self.bias_update_rate  = cfg.bias_update_rate
        self.bias_cap          = cfg.bias_cap
        self.bias_decay        = cfg.bias_decay
        self.usage_ema_decay   = cfg.usage_ema_decay
        self.register_buffer('expert_bias',      torch.zeros(E, dtype=torch.float32))
        self.register_buffer('expert_usage_ema', torch.zeros(E, dtype=torch.float32))
        self._bias_capped_warned = False
        self.last_aux_loss = torch.tensor(0.0, dtype=torch.float32)

    @torch.no_grad()
    def accumulate_usage(self, topk_i):
        counts = F.one_hot(topk_i, self.E).float().sum(dim=(0, 1))
        self.expert_usage_ema.mul_(self.usage_ema_decay).add_(counts, alpha=1 - self.usage_ema_decay)

    @torch.no_grad()
    def update_bias(self):
        if dist_ready():
            dist.all_reduce(self.expert_usage_ema, op=dist.ReduceOp.AVG)
        usage = self.expert_usage_ema
        avg   = usage.mean().clamp_min(1e-6)
        error = ((avg - usage) / avg).clamp(-1.0, 1.0)
        self.expert_bias.add_(self.bias_update_rate * error)
        self.expert_bias.mul_(1.0 - self.bias_decay)
        self.expert_bias.clamp_(-self.bias_cap, self.bias_cap)
        if not self._bias_capped_warned and bool((self.expert_bias.abs() >= self.bias_cap * 0.99).any()):
            log.warning(f"[moe] expert_bias hit cap ({self.bias_cap}) on some expert")
            self._bias_capped_warned = True

    def dead_expert_count(self, threshold: float = 1e-6) -> int:
        return int((self.expert_usage_ema < threshold).sum().item())

    def capped_expert_count(self) -> int:
        return int((self.expert_bias.abs() >= self.bias_cap * 0.99).sum().item())

    def forward(self, x):
        B, L, D = x.shape; T = B * L
        x_flat = x.reshape(T, D)
        E, top_k, BM = self.E, self.top_k, self.block_m
        device = x.device

        shared_out = self.shared_down(
            fused_swiglu(self.shared_gate(x_flat), self.shared_up(x_flat)))

        logits = self.router(x_flat).float()
        probs  = F.softmax(logits, dim=-1)

        biased    = logits + self.expert_bias.detach().float()
        _, topk_i = torch.topk(biased, top_k, dim=-1)
        topk_p    = probs.gather(-1, topk_i)
        topk_p    = topk_p / topk_p.sum(-1, keepdim=True).clamp_min(1e-9)

        with torch.no_grad():
            f_i = F.one_hot(topk_i, E).float().sum(1).mean(0)
        p_i = probs.mean(0)
        self.last_aux_loss = (E * (f_i * p_i).sum()) * self.aux_loss_coef

        if self.training:
            self.accumulate_usage(topk_i)

        expert_ids_flat = topk_i.reshape(-1)
        gate_flat       = topk_p.reshape(-1).to(x.dtype)
        token_idx_flat  = torch.arange(T, device=device).unsqueeze(1).expand(T, top_k).reshape(-1)

        perm, block_expert, total_padded, padded_offsets = moe_align_block_size(
            expert_ids_flat, E, BM, device)

        valid      = perm >= 0
        gather_idx = perm.clamp_min(0)
        src_token  = token_idx_flat[gather_idx]
        A_padded   = x_flat[src_token] * valid.unsqueeze(1).to(x_flat.dtype)

        gate = GroupedLinearFn.apply(A_padded, self.gate_w, block_expert, padded_offsets, total_padded, BM)
        up   = GroupedLinearFn.apply(A_padded, self.up_w,   block_expert, padded_offsets, total_padded, BM)
        down = GroupedLinearFn.apply(fused_swiglu(gate, up), self.down_w, block_expert, padded_offsets, total_padded, BM)

        gate_vals = (gate_flat[gather_idx] * valid.to(gate_flat.dtype)).unsqueeze(1)
        routed_out = torch.zeros(T, D, dtype=down.dtype, device=device)
        routed_out.index_add_(0, src_token, (down * gate_vals.to(down.dtype)))

        return (routed_out.to(x.dtype) + shared_out).view(B, L, D)

class Block(nn.Module):
    def __init__(self, cfg: Config, layer_idx: int):
        super().__init__()
        self.norm1 = RMSNorm(cfg.d_model)
        self.norm2 = RMSNorm(cfg.d_model)
        self.attn  = GQAAttention(cfg, layer_idx)
        self.ffn   = MoEFFN(cfg, layer_idx)

    def forward(self, x, cos, sin):
        x = x + self.attn(self.norm1(x), cos, sin)
        x = x + self.ffn (self.norm2(x))
        return x

class SmilyaiG1(nn.Module):
    def __init__(self, cfg: Config):
        super().__init__()
        self.cfg   = cfg
        self.embed = nn.Embedding(cfg.vocab_size, cfg.d_model)
        nn.init.normal_(self.embed.weight, std=0.02)
        self.blocks      = nn.ModuleList([Block(cfg, i) for i in range(cfg.n_layers)])
        self.final_norm  = RMSNorm(cfg.d_model)
        if not cfg.tie_embeddings:
            self.lm_head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False)
            nn.init.normal_(self.lm_head.weight, std=0.02 / math.sqrt(cfg.n_layers))
        else:
            self.lm_head = None
        self.register_buffer("rope_cos", torch.zeros(cfg.max_len, cfg.head_dim // 2, dtype=torch.float32), persistent=False)
        self.register_buffer("rope_sin", torch.zeros(cfg.max_len, cfg.head_dim // 2, dtype=torch.float32), persistent=False)
        self._rope_ready = False
        self._step = 0
        self._last_lm_loss  = None
        self._last_aux_loss = None
        self._log_summary()

    def _raw_blocks(self):
        return [getattr(b, "_orig_mod", b) for b in self.blocks]

    def init_rope(self, device):
        c, s = precompute_rope(self.cfg.head_dim, self.cfg.max_len, self.cfg.rope_theta, device)
        self.rope_cos = c.float()
        self.rope_sin = s.float()
        self._rope_ready = True

    def force_fp32_balancing_buffers(self):
        for b in self._raw_blocks():
            b.ffn.expert_bias      = b.ffn.expert_bias.float()
            b.ffn.expert_usage_ema = b.ffn.expert_usage_ema.float()

    def _log_summary(self):
        cfg = self.cfg
        total   = sum(p.numel() for p in self.parameters())
        attn_p  = sum(p.numel() for n, p in self.named_parameters() if 'attn'   in n)
        shared_p= sum(p.numel() for n, p in self.named_parameters() if 'shared' in n)
        h_e     = int(cfg.d_model * cfg.expert_hidden_mult)
        routed_total  = cfg.n_layers * cfg.n_experts * (2*cfg.d_model*h_e + h_e*cfg.d_model)
        routed_active = routed_total * (cfg.top_k / cfg.n_experts)
        active_est    = attn_p + shared_p + routed_active + cfg.d_model * cfg.vocab_size
        log.info("=" * 70)
        log.info("Smilyai-G1  20B β€” plain GQA + Sparse MoE (FSDP2)")
        log.info(f"  d={cfg.d_model} L={cfg.n_layers} heads={cfg.n_heads} kv={cfg.n_kv_heads}")
        log.info(f"  MoE: {cfg.n_experts} experts, top_k={cfg.top_k}, shared_mult={cfg.shared_hidden_mult}")
        log.info(f"  Total params: {total/1e9:.2f}B")
        log.info(f"  Active/token (estimate): {active_est/1e9:.2f}B  (target ~2B)")
        log.info(f"  vocab={cfg.vocab_size} | Flash: {HAS_FLASH}")
        log.info(f"  Muon LR: {cfg.muon_lr} (aspect-ratio scaling)")
        log.info(f"  Compile: {cfg.use_compile}")
        log.info("=" * 70)

    def count_params(self): return sum(p.numel() for p in self.parameters())
    def collect_aux_loss(self): return sum(b.ffn.last_aux_loss for b in self._raw_blocks())
    def set_step(self, s: int): self._step = s

    def update_expert_bias(self):
        for b in self._raw_blocks():
            b.ffn.update_bias()

    def dead_expert_report(self):
        raw    = self._raw_blocks()
        dead   = [b.ffn.dead_expert_count()   for b in raw]
        capped = [b.ffn.capped_expert_count() for b in raw]
        return dead, sum(dead), capped, sum(capped)

    def forward(self, tokens, targets=None):
        B, L  = tokens.shape; device = tokens.device
        if not self._rope_ready:
            self.init_rope(device)
        cos, sin = self.rope_cos[:L], self.rope_sin[:L]

        x = self.embed(tokens)
        for block in self.blocks:
            x = block(x, cos, sin)

        x     = self.final_norm(x)
        logits= F.linear(x, self.embed.weight) if self.lm_head is None else self.lm_head(x)

        if targets is None:
            return logits, None

        lm_loss  = F.cross_entropy(
            logits[:, :-1].reshape(-1, self.cfg.vocab_size).float(),
            targets[:, 1:].reshape(-1), ignore_index=-1)
        aux_loss   = self.collect_aux_loss()
        total_loss = lm_loss + aux_loss
        self._last_lm_loss  = lm_loss.detach()
        self._last_aux_loss = aux_loss.detach() if torch.is_tensor(aux_loss) \
                              else torch.tensor(float(aux_loss), device=device)
        return logits, total_loss

# ─────────────────────────────────────────────────────────────────────────────
#  FP8 / FSDP / COMPILE
# ─────────────────────────────────────────────────────────────────────────────
_FP8_SKIP = ("router", "lm_head", "embed")

def fp8_capable_gpu() -> bool:
    return torch.cuda.is_available() and \
           torch.cuda.get_device_capability(torch.cuda.current_device())[0] >= 9

def apply_fp8(model: SmilyaiG1, cfg: Config, is_master: bool) -> SmilyaiG1:
    if not cfg.use_fp8:
        if is_master: log.info("[fp8] disabled")
        return model
    if not HAS_FP8:
        if is_master: log.warning("[fp8] torchao not installed β€” staying bf16")
        return model
    if not fp8_capable_gpu():
        if is_master: log.warning("[fp8] pre-Hopper GPU β€” staying bf16")
        return model
    convert_to_float8_training(
        model,
        config=Float8LinearConfig.from_recipe_name("rowwise"),
        module_filter_fn=lambda m, fqn: (
            isinstance(m, nn.Linear) and not any(s in fqn for s in _FP8_SKIP)
        ),
    )
    if is_master:
        log.info("[fp8] converted dense nn.Linear layers to float8 (rowwise); MoE stays bf16")
    return model

def apply_fsdp(model: SmilyaiG1, cfg: Config) -> SmilyaiG1:
    if not dist_ready():
        log.warning("[fsdp] no process group β€” running unsharded (single GPU)")
        return model
    mp_policy = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32)
    for block in model.blocks:
        fully_shard(block, mp_policy=mp_policy)
    fully_shard(model, mp_policy=mp_policy)
    if torch.cuda.is_available():
        torch.cuda.empty_cache()
    return model

def apply_compile(model: SmilyaiG1, cfg: Config, is_master: bool) -> SmilyaiG1:
    if not cfg.use_compile:
        if is_master: log.info("[compile] disabled")
        return model
    compiled = 0
    for i, block in enumerate(model.blocks):
        try:
            model.blocks[i] = torch.compile(block, dynamic=True, mode="default", fullgraph=False)
            compiled += 1
        except Exception as e:
            if is_master:
                log.warning(f"[compile] block {i} failed, staying eager: {e}")
        if torch.cuda.is_available():
            torch.cuda.empty_cache()
    if is_master:
        if compiled > 0:
            log.info(f"[compile] compiled {compiled}/{len(model.blocks)} blocks")
        else:
            log.warning("[compile] ALL blocks fell back to eager")
    return model

# ─────────────────────────────────────────────────────────────────────────────
#  MUON β€” DTensor-aware
# ─────────────────────────────────────────────────────────────────────────────
def newton_schulz_5(G: torch.Tensor, steps: int = 5) -> torch.Tensor:
    a, b, c = 3.4445, -4.7750, 2.0315
    squeeze  = (G.ndim == 2)
    X = (G.unsqueeze(0) if squeeze else G).bfloat16()
    transposed = X.size(-2) < X.size(-1)
    if transposed: X = X.transpose(-2,-1)
    X = X / (X.norm(dim=(-2,-1), keepdim=True) + 1e-7)
    for _ in range(steps):
        A = X @ X.transpose(-2,-1)
        X = a*X + (b*A + c*A@A) @ X
    if transposed: X = X.transpose(-2,-1)
    return X.squeeze(0) if squeeze else X

@torch.no_grad()
def stochastic_round_to(dtype: torch.dtype, x_fp32: torch.Tensor) -> torch.Tensor:
    if dtype != torch.bfloat16:
        return x_fp32.to(dtype)
    bits = x_fp32.contiguous().view(torch.int32)
    noise = torch.randint(0, 1 << 16, bits.shape, device=bits.device, dtype=torch.int32)
    rounded = (bits + noise) & -65536
    return rounded.view(torch.float32).to(torch.bfloat16)

class Muon(torch.optim.Optimizer):
    def __init__(self, params, lr=0.02, momentum=0.95, wd=0.0):
        super().__init__(list(params), dict(lr=lr, momentum=momentum, wd=wd))

    @torch.no_grad()
    def step(self, closure=None):
        for g in self.param_groups:
            lr, mom, wd = g['lr'], g['momentum'], g['wd']
            for p in g['params']:
                if p.grad is None:
                    continue
                grad = p.grad
                is_dtensor = isinstance(p, DTensor)
                st = self.state[p]
                if 'buf' not in st:
                    st['buf'] = torch.zeros_like(grad, dtype=torch.float32)
                buf = st['buf']
                buf.mul_(mom).add_(grad.to(torch.float32))
                gnest = grad.to(torch.float32).add(buf, alpha=mom)
                full = gnest.full_tensor() if is_dtensor else gnest
                if full.ndim in (2, 3):
                    u = newton_schulz_5(full)
                    rows, cols = full.shape[-2], full.shape[-1]
                    scale  = max(1.0, rows / cols) ** 0.5
                    update = u.to(torch.float32) * (lr * 0.2 * scale)
                else:
                    update = full * lr
                del full
                if is_dtensor:
                    upd_local = distribute_tensor(update, p.device_mesh, p.placements).to_local()
                    p_local = p.to_local()
                else:
                    upd_local = update
                    p_local   = p.data
                if wd > 0:
                    p_local.mul_(1.0 - lr * wd)
                p_local.sub_(stochastic_round_to(p_local.dtype, upd_local.contiguous()))

def build_optimizers(model: SmilyaiG1, cfg: Config, is_master: bool):
    muon_p, adamw_p = [], []
    for name, p in model.named_parameters():
        if not p.requires_grad: continue
        if p.ndim in (2, 3) and 'embed' not in name and 'lm_head' not in name:
            muon_p.append(p)
        else:
            adamw_p.append(p)
    muon_opt = Muon(muon_p, lr=cfg.muon_lr, momentum=cfg.muon_mom, wd=cfg.wd)
    groups = [{'params': adamw_p, 'lr': cfg.adamw_lr}]
    if dist_ready():
        adamw_opt = torch.optim.AdamW(groups, betas=(cfg.beta1, cfg.beta2), weight_decay=cfg.wd, foreach=True)
        if is_master: log.info("[optim] Muon (FIXED scale) + foreach AdamW (DTensor-safe)")
    elif HAS_BNB:
        adamw_opt = bnb.optim.AdamW8bit(groups, betas=(cfg.beta1, cfg.beta2), weight_decay=cfg.wd)
        if is_master: log.info("[optim] Muon (FIXED) + 8-bit AdamW (single GPU)")
    else:
        adamw_opt = torch.optim.AdamW(groups, betas=(cfg.beta1, cfg.beta2), weight_decay=cfg.wd, fused=True)
        if is_master: log.info("[optim] Muon (FIXED) + fused AdamW (single GPU)")
    if is_master:
        log.info(f"[optim] Muon={sum(p.numel() for p in muon_p)/1e6:.1f}M | "
                 f"AdamW={sum(p.numel() for p in adamw_p)/1e6:.1f}M")
    return muon_opt, adamw_opt

def cosine_lr(step, warmup, total, peak, minimum):
    if step < warmup:  return peak * (step + 1) / warmup
    if step >= total:  return minimum
    t = (step - warmup) / (total - warmup)
    return minimum + 0.5 * (peak - minimum) * (1 + math.cos(math.pi * t))

# ─────────────────────────────────────────────────────────────────────────────
#  LIVE MULTI-SOURCE STREAMING
# ─────────────────────────────────────────────────────────────────────────────
try:
    from datasets import load_dataset
    import datasets as _hfds
    HAS_DATASETS = True
    try: _hfds.disable_progress_bars()
    except Exception: pass
    try:
        import pyarrow as _pa
        _pa.set_cpu_count(2); _pa.set_io_thread_count(4)
    except Exception:
        pass
except ImportError:
    HAS_DATASETS = False

_g1_tokenizer = None

def get_tokenizer(cfg: Config):
    global _g1_tokenizer
    if _g1_tokenizer is not None:
        return _g1_tokenizer
    from tokenizers import Tokenizer
    tok_path = hf_hub_download(repo_id=cfg.tokenizer_repo, filename="tokenizer.json",
                               cache_dir=LOCAL_CACHE, token=HF_TOKEN)
    _g1_tokenizer = Tokenizer.from_file(tok_path)
    got_vocab = _g1_tokenizer.get_vocab_size()
    if got_vocab != cfg.vocab_size:
        log.warning(f"[tokenizer] loaded vocab_size={got_vocab} != cfg.vocab_size="
                    f"{cfg.vocab_size} β€” fix Config.vocab_size to match the real tokenizer.")
    return _g1_tokenizer

_EOS_CACHE: Optional[int] = None

def _resolve_eos(tok) -> int:
    """v7: env override > known names > scan added tokens for anything EOS-like > id 0 (logged loudly)."""
    global _EOS_CACHE
    if _EOS_CACHE is not None:
        return _EOS_CACHE
    override = os.environ.get("G1_EOS_TOKEN", "").strip()
    if override:
        tid = tok.token_to_id(override)
        if tid is not None:
            log.info(f"[tokenizer] EOS from G1_EOS_TOKEN: {override!r} -> id {tid}")
            _EOS_CACHE = tid; return tid
        log.warning(f"[tokenizer] G1_EOS_TOKEN={override!r} not in vocab β€” falling back to auto-detect")
    for cand in ("<|endoftext|>", "<|end_of_text|>", "</s>", "<eos>", "<|eos|>", "<|eot_id|>",
                 "<|im_end|>", "[EOS]", "<end_of_text>", "<|end|>"):
        tid = tok.token_to_id(cand)
        if tid is not None:
            log.info(f"[tokenizer] EOS auto-detected: {cand!r} -> id {tid}")
            _EOS_CACHE = tid; return tid
    try:
        added = tok.get_added_tokens_decoder()
        names = {tid: t.content for tid, t in added.items()}
        for tid, name in names.items():
            low = name.lower()
            if ("eos" in low or "end" in low) and "pad" not in low and "unk" not in low:
                log.info(f"[tokenizer] EOS heuristically picked from added tokens: {name!r} -> id {tid}")
                _EOS_CACHE = tid; return tid
        log.error(f"[tokenizer] NO EOS TOKEN FOUND. Added tokens are: {names}. "
                  f"Set G1_EOS_TOKEN to the right one. Using id 0 as a document separator for now.")
    except Exception as e:
        log.error(f"[tokenizer] could not inspect added tokens ({e}); using id 0 as separator")
    _EOS_CACHE = 0
    return 0

_STACK_KEEP_LANGS = {
    "Python", "JavaScript", "TypeScript", "Java", "C", "C++", "C#",
    "Go", "Rust", "Ruby", "PHP", "Swift", "Kotlin", "Scala", "Shell",
    "SQL", "HTML", "CSS", "Markdown", "R", "Julia", "Lua", "Haskell",
    "Elixir", "Erlang", "Dart", "Zig", "CUDA", "Fortran",
}
_MIN_CODE_CHARS = 64
_MAX_CODE_CHARS = 65536
_MAX_DOC_CHARS  = 1_000_000   # any source: hard cap before tokenizing
_MAX_REPO_CHARS = 65_536      # v7: stack-v3 cap per repo (~16K tokens β‰ˆ 2 micro-batches)

def _extract_stack_v3_text(row: dict) -> Optional[str]:
    files = row.get("files")
    if not files:
        return None
    parts, total = [], 0
    for f in files:
        content = f.get("content", "")
        if not content:
            continue
        lang = f.get("language", "")
        if lang and lang not in _STACK_KEEP_LANGS:
            continue
        if len(content) < _MIN_CODE_CHARS or len(content) > _MAX_CODE_CHARS:
            continue
        parts.append(f"# {f.get('file_path', '')}\n{content}")
        total += len(content)
        if total >= _MAX_REPO_CHARS:
            break
    return "\n\n".join(parts) if parts else None

def _extract_text(row: dict, text_field: str, repo_id: str) -> Optional[str]:
    if "stack-v3" in repo_id:
        text = row.get("text") if ("text" in row and "files" not in row) else _extract_stack_v3_text(row)
    else:
        text = row.get(text_field)
    if not text or not isinstance(text, str):
        return None
    return text[:_MAX_DOC_CHARS] if len(text) > _MAX_DOC_CHARS else text

def _open_source_stream(repo_id: str, split: str, shard_index: int, num_shards: int,
                        shuffle_buffer: int = 0, shuffle_seed: int = 0,
                        config_name: Optional[str] = None, text_field: str = "text"):
    is_stack = "stack-v3" in repo_id
    need_col = "files" if is_stack else text_field
    args = (repo_id, config_name) if config_name else (repo_id,)
    kw = dict(split=split, streaming=True)
    try:
        # parquet: only the needed column; tiny arrow batches for stack-v3 (each row = a whole repo)
        ds = load_dataset(*args, columns=[need_col], batch_size=(4 if is_stack else 64), **kw)
    except Exception:
        ds = load_dataset(*args, **kw)

    if num_shards > 1:
        ds = ds.shard(num_shards=num_shards, index=shard_index)

    if is_stack:
        cols = ds.column_names
        ds = ds.map(lambda r: {"text": _extract_stack_v3_text(r) or ""}, remove_columns=cols)
        ds = ds.filter(lambda r: len(r["text"]) > 0)

    if shuffle_buffer > 0:
        ds = ds.shuffle(buffer_size=shuffle_buffer, seed=shuffle_seed)
    return ds

def _short_src(repo_id: str) -> str:
    return repo_id.split("/")[-1][:18]

class LiveStreamingDataset:
    def __init__(self, cfg: Config, batch_size: int, rank: int, world_size: int):
        if not HAS_DATASETS:
            raise RuntimeError("the `datasets` package is required for live streaming")
        self.cfg          = cfg
        self.batch_size   = batch_size
        self.rank         = rank
        self.world_size   = world_size
        self.max_len      = cfg.max_len
        self.n_workers    = max(1, cfg.tokenizer_workers)
        self.total_shards = world_size * self.n_workers
        self.tok          = get_tokenizer(cfg)
        self.eos_id       = _resolve_eos(self.tok)

        qsize = max(cfg.prefetch_shards, self.n_workers * 2)
        self._q: queue.Queue = queue.Queue(maxsize=qsize)
        self._stop = threading.Event()
        self._workers = [threading.Thread(target=self._fetch_loop, args=(w,), daemon=True)
                         for w in range(self.n_workers)]
        for t in self._workers:
            t.start()
        log.info(f"[stream] rank={rank}/{world_size}: {self.n_workers} tokenizer threads "
                 f"({self.total_shards} global shards) | {len(cfg.dataset_sources)} sources | "
                 f"shuffle_buffer={cfg.shuffle_buffer} eos_id={self.eos_id} session={SESSION_ID}")

    def _fetch_loop(self, worker_id: int):
        shard_index  = self.rank * self.n_workers + worker_id
        shuffle_seed = 1234 + shard_index + SESSION_ID * 97
        try:
            streams, failed = [], []
            for repo_id, split, text_field, w, config_name in self.cfg.dataset_sources:
                try:
                    streams.append([
                        _open_source_stream(repo_id, split, shard_index, self.total_shards,
                                            shuffle_buffer=self.cfg.shuffle_buffer,
                                            shuffle_seed=shuffle_seed,
                                            config_name=config_name, text_field=text_field),
                        text_field, repo_id, split, float(w), config_name])
                except Exception as e:
                    log.error(f"[stream] rank={self.rank}.w{worker_id} FAILED TO OPEN {repo_id}: {str(e)[:300]}")
                    failed.append(repo_id)
            if failed:
                log.error(f"[stream] rank={self.rank}.w{worker_id} MISSING SOURCES (0% contribution): {failed}")
            if not streams:
                log.error(f"[stream] rank={self.rank}.w{worker_id} NO SOURCES OPENED β€” worker is dead")
                return

            rng   = np.random.default_rng(shuffle_seed)
            iters = [iter(s[0]) for s in streams]
            probs = np.array([s[4] for s in streams], dtype=np.float64); probs /= probs.sum()
            consumed = np.zeros(len(iters), dtype=np.float64)     # tokens consumed per source
            if worker_id == 0 and self.rank == 0:
                log.info("[stream] target TOKEN mix (deficit-scheduled):")
                for s, p in zip(streams, probs):
                    log.info(f"  {s[2]:55s} {p*100:5.1f}%")

            buf: List[int] = []
            segs: List[List[int]] = []      # [source_idx, n_tokens] in buffer order
            pos = 0
            need = self.max_len * self.batch_size

            while not self._stop.is_set():
                # v7: deficit scheduler β€” the source furthest BEHIND its token quota goes next.
                deficit = (consumed + 1.0) / probs
                idx = int(np.argmin(deficit * rng.uniform(0.9, 1.1, size=len(iters))))
                _, text_field, repo_id, split, _w, config_name = streams[idx]
                try:
                    row = next(iters[idx])
                except StopIteration:
                    streams[idx][0] = _open_source_stream(
                        repo_id, split, shard_index, self.total_shards,
                        shuffle_buffer=self.cfg.shuffle_buffer, shuffle_seed=shuffle_seed + 1,
                        config_name=config_name, text_field=text_field)
                    iters[idx] = iter(streams[idx][0]); continue
                except Exception as e:
                    log.warning(f"[stream] rank={self.rank}.w{worker_id} read error on {repo_id}: {str(e)[:300]}")
                    consumed[idx] += need    # don't hammer a broken source
                    time.sleep(1.0); continue

                text = _extract_text(row, text_field, repo_id)
                del row
                if not text:
                    continue
                try:
                    ids = self.tok.encode(text, add_special_tokens=False).ids
                except Exception:
                    continue
                del text
                ids.append(self.eos_id)
                n = len(ids)
                buf.extend(ids)
                del ids
                segs.append([idx, n])
                consumed[idx] += n

                while len(buf) - pos >= need:
                    if self._stop.is_set():
                        return
                    # v7: tag the batch with the MAJORITY source of its tokens
                    counts: dict = {}
                    remaining = need
                    while remaining > 0 and segs:
                        s = segs[0]
                        take = min(s[1], remaining)
                        counts[s[0]] = counts.get(s[0], 0) + take
                        s[1] -= take; remaining -= take
                        if s[1] == 0:
                            segs.pop(0)
                    maj = max(counts, key=counts.get) if counts else idx
                    arr = np.array(buf[pos:pos + need], dtype=np.int64).reshape(self.batch_size, self.max_len)
                    pos += need
                    self._q.put((torch.from_numpy(arr), streams[maj][2]))
                if pos:                       # one O(n) compaction per document
                    del buf[:pos]; pos = 0
        except Exception as e:
            log.error(f"[stream] rank={self.rank}.w{worker_id} fetch loop crashed: {str(e)[:300]}")

    def __iter__(self) -> Iterator[Tuple[torch.Tensor, str]]:
        return self

    def __next__(self) -> Tuple[torch.Tensor, str]:
        while not self._stop.is_set():
            try:
                return self._q.get(timeout=60)
            except queue.Empty:
                log.warning(f"[stream] rank={self.rank} queue empty β€” waiting for data … ({host_mem_str()})")
        raise StopIteration

    def close(self):
        self._stop.set()
        try:
            while True: self._q.get_nowait()
        except queue.Empty:
            pass
        for t in self._workers:
            t.join(timeout=5)

def build_val_loader(cfg: Config) -> Optional[DataLoader]:
    if not HAS_DATASETS:
        return None
    tok = get_tokenizer(cfg)
    repo_id, split, text_field, _, config_name = max(cfg.dataset_sources, key=lambda s: s[3])
    try:
        ds = _open_source_stream(repo_id, split, 0, 1, shuffle_buffer=0,
                                 config_name=config_name, text_field=text_field)
    except Exception as e:
        log.warning(f"[val] could not open {repo_id}: {str(e)[:300]}")
        return None

    eos_id = _resolve_eos(tok)
    buf: List[int] = []
    rows = []
    n_val_seqs = 128
    try:
        for row in ds:
            text = _extract_text(row, text_field, repo_id)
            if not text:
                continue
            ids = tok.encode(text, add_special_tokens=False).ids
            ids.append(eos_id)
            buf.extend(ids)
            while len(buf) >= cfg.max_len:
                rows.append(np.array(buf[:cfg.max_len], dtype=np.int64))
                buf = buf[cfg.max_len:]
                if len(rows) >= n_val_seqs:
                    break
            if len(rows) >= n_val_seqs:
                break
    except Exception as e:
        log.warning(f"[val] stream error: {str(e)[:300]}")
    del ds

    if not rows:
        log.warning(f"[val] got no validation rows from {repo_id}")
        return None
    data = np.stack(rows, axis=0)

    class _ValDS(Dataset):
        def __len__(self):         return len(data)
        def __getitem__(self, i):  return torch.from_numpy(data[i])

    return DataLoader(_ValDS(), batch_size=min(cfg.micro_batch, 4),
                      shuffle=False, num_workers=0, pin_memory=True, drop_last=True)

# ─────────────────────────────────────────────────────────────────────────────
#  CHECKPOINTING β€” async on rank 0, heap-friendly
# ─────────────────────────────────────────────────────────────────────────────
_ckpt_thread: Optional[threading.Thread] = None

def _async_save_and_upload(payload: list, step, epoch, cfg_dict, loss):
    name  = f"g1_s{SESSION_ID:03d}_step{step:07d}"
    local = os.path.join(TEMP_CKPT_DIR, f"{name}.pt")
    try:
        t0 = time.time()
        model_sd, muon_sd, adamw_sd = payload.pop()
        torch.save({'model': model_sd, 'muon': muon_sd, 'adamw': adamw_sd,
                    'step': step, 'epoch': epoch, 'loss': loss, 'config': cfg_dict}, local)
        del model_sd, muon_sd, adamw_sd
        gc.collect()
        log.info(f"[ckpt-async] saved in {time.time()-t0:.1f}s, heap freed ({host_mem_str()}), uploading…")
        upload_to_hf(local, f"{name}.pt")
        log.info(f"[ckpt-async] step={step} uploaded ({time.time()-t0:.1f}s total)")
    except Exception as e:
        log.error(f"[ckpt-async] failed: {e}")
    finally:
        try: os.remove(local)
        except OSError: pass

def save_ckpt(model, muon, adamw, step, epoch, cfg, loss, is_master: bool):
    global _ckpt_thread
    if is_master and _ckpt_thread is not None and _ckpt_thread.is_alive():
        log.warning("[ckpt] previous checkpoint still in flight β€” waiting before gathering another")
        _ckpt_thread.join()
    opts = StateDictOptions(full_state_dict=True, cpu_offload=True)
    model_sd = get_model_state_dict(model, options=opts)
    try:    muon_sd = get_optimizer_state_dict(model, muon, options=opts)
    except Exception as e:
        log.warning(f"[ckpt] could not gather muon state: {e}"); muon_sd = {}
    try:    adamw_sd = get_optimizer_state_dict(model, adamw, options=opts)
    except Exception as e:
        log.warning(f"[ckpt] could not gather adamw state: {e}"); adamw_sd = {}
    if not is_master:
        del model_sd, muon_sd, adamw_sd
        return
    payload = [(model_sd, muon_sd, adamw_sd)]
    del model_sd, muon_sd, adamw_sd
    _ckpt_thread = threading.Thread(target=_async_save_and_upload,
                                    args=(payload, step, epoch, asdict(cfg), loss), daemon=True)
    _ckpt_thread.start()
    log.info(f"[ckpt] step={step} gathered ({host_mem_str()}), saving+uploading in background")

def _find_latest_ckpt():
    for sid in range(SESSION_ID, 0, -1):
        repo = f"{REPO_PREFIX}{sid:03d}"
        try:
            files = hf_api.list_repo_files(repo_id=repo, repo_type="model", token=HF_TOKEN)
        except Exception:
            continue
        ckpts = sorted([f for f in files if f.endswith(".pt") and "step" in f],
                       key=lambda x: int(x.split("step")[-1].split(".")[0]))
        if ckpts:
            return repo, ckpts[-1]
    return None, None

def load_ckpt(model, muon, adamw, cfg, device, is_master: bool):
    ckpt = None
    dl_dir = os.path.join(TEMP_CKPT_DIR, "resume_dl")
    meta = torch.zeros(3, dtype=torch.float64, device=device)
    loss_t = torch.zeros(1, dtype=torch.float64, device=device)
    mismatch_flag = torch.zeros(1, dtype=torch.int32, device=device)

    if is_master:
        repo, ckpt_name = _find_latest_ckpt()
        if repo is None:
            log.warning("[ckpt] no checkpoint in this or any earlier session repo β€” fresh start")
        else:
            try:
                shutil.rmtree(dl_dir, ignore_errors=True)
                path = hf_hub_download(repo, ckpt_name, local_dir=dl_dir, token=HF_TOKEN)
                ckpt = torch.load(path, map_location="cpu", weights_only=False, mmap=True)
                log.info(f"[ckpt] mapped {ckpt_name} ({host_mem_str()})")
                saved_cfg = ckpt.get('config', {})
                mismatches = [f"{k}: ckpt={saved_cfg[k]} vs live={v}"
                              for k, v in cfg.arch_fingerprint().items()
                              if k in saved_cfg and saved_cfg[k] != v]
                if mismatches:
                    log.error("[ckpt] ARCHITECTURE MISMATCH β€” refusing to resume: " + "; ".join(mismatches))
                    mismatch_flag[0] = 1; ckpt = None
                else:
                    meta[0] = 1.0; meta[1] = float(ckpt['step']); meta[2] = float(ckpt['epoch'])
                    loss_t[0] = float(ckpt['loss'])
                    if repo != HF_MODEL_REPO:
                        log.info(f"[ckpt] resuming from an EARLIER session's repo: {repo}/{ckpt_name}")
            except Exception as e:
                log.error(f"[ckpt] FOUND {repo}/{ckpt_name} BUT COULD NOT LOAD IT: {e} β€” fresh start")
                ckpt = None

    if dist_ready():
        dist.broadcast(meta, src=0); dist.broadcast(loss_t, src=0); dist.broadcast(mismatch_flag, src=0)
    if mismatch_flag.item() > 0:
        raise RuntimeError("Checkpoint architecture mismatch β€” see rank 0 log.")
    if meta[0].item() < 0.5:
        return 0, 0, float('inf')

    opts = StateDictOptions(full_state_dict=True, broadcast_from_rank0=True)
    set_model_state_dict(model, model_state_dict=(ckpt['model'] if is_master else {}), options=opts)
    try:
        set_optimizer_state_dict(model, muon, optim_state_dict=(ckpt['muon'] if is_master else {}), options=opts)
    except Exception as e:
        log.warning(f"[ckpt] muon state not restored: {e}")
    try:
        set_optimizer_state_dict(model, adamw, optim_state_dict=(ckpt['adamw'] if is_master else {}), options=opts)
    except Exception as e:
        log.warning(f"[ckpt] adamw state not restored: {e}")

    step, epoch, loss = int(meta[1].item()), int(meta[2].item()), float(loss_t[0].item())
    del ckpt
    gc.collect()
    if is_master:
        shutil.rmtree(dl_dir, ignore_errors=True)
        log.info(f"[ckpt] resumed step={step} loss={loss:.4f} βœ… | {host_mem_str()}")
    return step, epoch, loss

def save_final(model, cfg, step, epoch, loss, is_master: bool):
    opts = StateDictOptions(full_state_dict=True, cpu_offload=True)
    model_sd = get_model_state_dict(model, options=opts)
    if not is_master:
        return
    name  = f"g1_final_s{SESSION_ID:03d}_step{step:07d}"
    mname = f"{name}.safetensors" if HAS_ST else f"{name}.pt"
    mpath = os.path.join(TEMP_CKPT_DIR, mname)
    cpath = os.path.join(TEMP_CKPT_DIR, f"{name}_config.json")
    if HAS_ST:
        st_save({k: v.contiguous() for k, v in model_sd.items()}, mpath)
    else:
        torch.save(model_sd, mpath)
    del model_sd; gc.collect()
    with open(cpath, 'w') as f:
        json.dump({**asdict(cfg), 'step': step, 'epoch': epoch,
                   'loss': loss, 'arch': 'Smilyai-G1-20B'}, f, indent=2)
    upload_to_hf(mpath, mname); upload_to_hf(cpath, os.path.basename(cpath))
    for p in (mpath, cpath):
        try: os.remove(p)
        except OSError: pass

@torch.no_grad()
def validate(model, val_loader, device, cfg, n=100):
    if val_loader is None:
        return float('nan')
    was_training = model.training
    model.eval(); losses = []
    for i, batch in enumerate(val_loader):
        if i >= n: break
        batch = batch.to(device, non_blocking=True)
        with torch.amp.autocast('cuda', dtype=cfg.dtype):
            _, loss = model(batch, batch)
        lm = getattr(model, '_last_lm_loss', None)
        lm = lm if lm is not None else loss
        if lm is not None and torch.isfinite(lm):
            losses.append(lm.item())
    if was_training: model.train()
    local = float(np.mean(losses)) if losses else float('nan')
    if math.isnan(local):
        return local
    return distributed_mean(local, device)

# ─────────────────────────────────────────────────────────────────────────────
#  TRAIN
# ─────────────────────────────────────────────────────────────────────────────
def train():
    if not torch.cuda.is_available():
        raise RuntimeError("this script requires CUDA GPUs")

    local_rank = int(os.environ.get("LOCAL_RANK", "0"))
    rank       = int(os.environ.get("RANK", "0"))
    world_size = int(os.environ.get("WORLD_SIZE", "1"))
    torch.cuda.set_device(local_rank)
    device = torch.device("cuda", local_rank)
    if world_size > 1 and not dist_ready():
        dist.init_process_group(backend="nccl", init_method="env://", device_id=device,
                                timeout=_dt.timedelta(minutes=20))
    is_master = (rank == 0)
    if not is_master:
        log.setLevel(logging.WARNING)

    torch.manual_seed(42 + rank); np.random.seed(42 + rank); random.seed(42 + rank)

    log.info(f"[env] rank={rank}/{world_size} device={device} | "
             f"GPU={torch.cuda.get_device_name(local_rank)} | VRAM={vram_total_gb():.0f}GB")
    log.info(f"[env] {host_mem_str()} | work_dir={_WORK}")
    start_mem_watchdog(rank)

    if is_master:
        ensure_repo()
        session_banner()
        _bootstrap_from_hub(METRICS_FILE, os.path.basename(METRICS_FILE))
        _bootstrap_from_hub(SAMPLES_FILE, "samples.md")
        _bootstrap_from_hub(SUMMARY_FILE, "summary.jsonl")
    if dist_ready():
        dist.barrier()

    cfg = Config()

    if local_rank == 0:
        try: get_tokenizer(cfg)
        except Exception as e: log.warning(f"[tokenizer] pre-load failed, will retry lazily: {e}")
    if dist_ready():
        dist.barrier()
    if local_rank != 0:
        try: get_tokenizer(cfg)
        except Exception as e: log.warning(f"[tokenizer] pre-load failed, will retry lazily: {e}")

    _prev_dtype = torch.get_default_dtype()
    torch.set_default_dtype(cfg.dtype)
    try:
        model = SmilyaiG1(cfg)
    finally:
        torch.set_default_dtype(_prev_dtype)
    model = model.to(cfg.dtype).to(device)
    gc.collect()
    model.init_rope(device)
    model.force_fp32_balancing_buffers()
    log.info(f"[env] model on GPU | {vram_str()} | {host_mem_str()}")

    model = apply_fp8(model, cfg, is_master)
    model = apply_fsdp(model, cfg)
    model = apply_compile(model, cfg, is_master)

    muon, adamw = build_optimizers(model, cfg, is_master)

    start_step, start_epoch, best_loss = load_ckpt(model, muon, adamw, cfg, device, is_master)
    if dist_ready():
        dist.barrier()

    last_val = float('nan')
    bs = cfg.micro_batch

    stream = LiveStreamingDataset(cfg, batch_size=bs, rank=rank, world_size=world_size)
    val_loader = build_val_loader(cfg)

    if is_master:
        log.info("=" * 70)
        log.info(f"Smilyai-G1 | {model.count_params()/1e9:.2f}B total params | "
                 f"Session {SESSION_ID} | FSDP2 world={world_size}")
        log.info(f"  micro_batch={bs}/GPU  grad_accum={cfg.grad_accum}  "
                 f"eff_batch={bs*cfg.grad_accum*world_size}  max_len={cfg.max_len}")
        log.info(f"  {cfg.tokens_per_step(bs, world_size)/1e6:.1f}M tok/step | "
                 f"{MAX_HOURS}h budget | streaming=True | compile={cfg.use_compile}")
        log.info(f"  Muon LR={cfg.muon_lr} | resumed at step={start_step} | {host_mem_str()}")
        log.info("  NOTE: train loss is only comparable within a session β€” the mix changed. Watch [val].")
        log.info("=" * 70)

    step, epoch = start_step, start_epoch
    losses, aux_losses = [], []
    src_window: collections.deque = collections.deque(maxlen=200)   # (source, lm_loss) per micro-batch, rank 0
    model.train(); model.zero_grad(set_to_none=True)
    t0 = time.time(); last_ckpt = time.time()

    try:
        record_sample(model, step, is_master)
    except Exception as e:
        log.warning(f"[sample] {e}")

    accum_n = 0
    while not distributed_should_stop(device, is_master, step, cfg.total_steps):
        try:
            batch, folder = next(stream)
        except StopIteration:
            log.warning(f"[stream] rank={rank} exhausted β€” sleeping 60s")
            time.sleep(60); continue
        except Exception as e:
            log.error(f"[data] rank={rank} {e}"); time.sleep(5); continue

        batch = batch.to(device, non_blocking=True)

        try:
            with torch.amp.autocast('cuda', dtype=cfg.dtype):
                _, loss = model(batch, batch)
                loss_s  = loss / cfg.grad_accum
            loss_s.backward()
            micro_ok = bool(torch.isfinite(loss))
            if micro_ok:
                lm_only  = getattr(model, '_last_lm_loss', loss)
                aux_only = getattr(model, '_last_aux_loss', None)
                lm_f = float(lm_only)
                losses.append(lm_f)
                aux_losses.append(float(aux_only) if aux_only is not None else 0.0)
                src_window.append((folder, lm_f))
            del loss, loss_s
        except torch.OutOfMemoryError:
            log.error(f"[oom] rank={rank} step={step} CUDA OOM | {vram_str()} | {host_mem_str()}")
            log.error(torch.cuda.memory_summary(abbreviated=True))
            raise

        if not all_ok(micro_ok, device):
            if is_master: log.error(f"[skip] step={step} non-finite loss on >=1 rank")
            model.zero_grad(set_to_none=True); accum_n = 0
            continue

        accum_n += 1
        if accum_n < cfg.grad_accum:
            continue

        mlr = cosine_lr(step, cfg.warmup, cfg.total_steps, cfg.muon_lr, cfg.muon_min_lr)
        alr = cosine_lr(step, cfg.warmup, cfg.total_steps, cfg.adamw_lr, cfg.adamw_min_lr)
        for g in muon.param_groups:  g['lr'] = mlr
        for g in adamw.param_groups: g['lr'] = alr

        norm = torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.grad_clip)
        if isinstance(norm, DTensor):
            norm = norm.full_tensor()
        if not torch.isfinite(norm):
            if is_master: log.error("[nan] grad-norm non-finite β€” skipping step")
            model.zero_grad(set_to_none=True); accum_n = 0; continue

        muon.step(); adamw.step(); model.zero_grad(set_to_none=True)

        step += 1
        model.set_step(step)
        accum_n = 0
        if len(losses) > 500: losses = losses[-500:]
        if len(aux_losses) > 500: aux_losses = aux_losses[-500:]

        if step % cfg.bias_update_every == 0:
            model.update_expert_bias()

        if step % cfg.log_every == 0 and losses:
            avg     = distributed_mean(float(np.mean(losses[-50:])), device)
            avg_aux = distributed_mean(float(np.mean(aux_losses[-50:])), device) if aux_losses else 0.0
            _step_clock.append((step, time.time()))
            if len(_step_clock) > 300: _step_clock.pop(0)
            sph = _real_steps_per_hour()
            tps = (sph * cfg.tokens_per_step(bs, world_size) / 3600) if sph else \
                  (max(step - start_step, 1) * cfg.tokens_per_step(bs, world_size) / max(time.time() - t0, 1))
            if is_master:
                # per-source breakdown of the last 200 micro-batches on rank 0
                by_src: dict = collections.defaultdict(list)
                for s, l in src_window: by_src[s].append(l)
                n_tot = max(len(src_window), 1)
                per_src = " ".join(f"{_short_src(s)}:{np.mean(v):.2f}({100*len(v)/n_tot:.0f}%)"
                                   for s, v in sorted(by_src.items(), key=lambda kv: -len(kv[1])))
                log_metrics(step=step, loss=avg, aux=avg_aux, tok_s=tps, folder=folder,
                            per_source={s: [float(np.mean(v)), len(v) / n_tot] for s, v in by_src.items()})
                sl = sessions_left(step, cfg.total_steps)
                suffix = f" | ~{sl} more sessions" if sl is not None else ""
                log.info(f"step {step:06d} | ep {epoch+1} | lm {avg:.4f} | aux {avg_aux:.4f} | "
                         f"ppl {math.exp(min(avg,20)):.1f} | {tps/1e3:.1f}K tok/s | "
                         f"{vram_str()} | {remaining_h():.1f}h left{suffix}")
                log.info(f"  [mix] {per_src}")
                if step % (cfg.log_every * 10) == 0:
                    log.info(f"  [{host_mem_str()}]")

        if step % cfg.eval_every == 0:
            vl = validate(model, val_loader, device, cfg)
            if is_master and vl == vl:
                marker = " *NEW BEST*" if vl < best_loss else ""
                if vl < best_loss: best_loss = vl
                last_val = vl
                log_metrics(step=step, val_loss=vl)
                log.info(f"  [val] loss={vl:.4f} ppl={math.exp(min(vl,20)):.1f}{marker}")
                dead, total_dead, capped, total_capped = model.dead_expert_report()
                total_experts = cfg.n_experts * cfg.n_layers
                if total_dead > 0:
                    log.info(f"  [experts] dead={total_dead}/{total_experts}")
                else:
                    log.info(f"  [experts] all {total_experts} experts alive βœ…")
                if total_capped > 0:
                    log.info(f"  [experts] bias-capped={total_capped}/{total_experts}")
            try:
                record_sample(model, step, is_master)
            except Exception as e:
                log.warning(f"[sample] {e}")
            if dist_ready():
                dist.barrier()

        local_due = (step % cfg.ckpt_every == 0) or ((time.time() - last_ckpt) > 1800)
        if broadcast_flag(local_due if is_master else False, device):
            save_ckpt(model, muon, adamw, step, epoch, cfg, losses[-1] if losses else 0.0, is_master)
            if is_master:
                update_progress_md(cfg, step, epoch,
                                   float(np.mean(losses[-50:])) if losses else None, last_val)
                make_loss_chart(); upload_metrics()
            last_ckpt = time.time()

    log.info(f"[rank {rank}] DONE training loop")
    stream.close()

    if is_master and _ckpt_thread is not None and _ckpt_thread.is_alive():
        log.info("[ckpt] waiting for final in-flight checkpoint upload to finish…")
        _ckpt_thread.join()

    vm = validate(model, val_loader, device, cfg, n=300)
    if vm != vm:
        vm = losses[-1] if losses else 0.0
    save_final(model, cfg, step, epoch, vm, is_master)
    if is_master:
        try:
            update_progress_md(cfg, step, epoch, float(np.mean(losses[-50:])) if losses else None, vm)
            make_loss_chart(); upload_metrics()
        except Exception as e:
            log.warning(f"[motiv] final refresh failed: {e}")
        log.info(f"Steps={step:,} | Epochs={epoch+1} | Time={elapsed_h():.2f}h | Final val={vm:.4f}")

    if dist_ready():
        dist.barrier()
        dist.destroy_process_group()


def _spawn_worker(local_rank: int, world_size: int):
    os.environ["LOCAL_RANK"] = str(local_rank)
    os.environ["RANK"]       = str(local_rank)
    os.environ["WORLD_SIZE"] = str(world_size)
    train()


def launch():
    if "RANK" in os.environ and "WORLD_SIZE" in os.environ:
        train()
        return
    world_size = torch.cuda.device_count()
    if world_size < 1:
        raise RuntimeError("No CUDA GPUs are visible")
    expected_world = int(os.environ.get("EXPECTED_WORLD_SIZE", str(world_size)))
    if world_size != expected_world:
        raise RuntimeError(f"Expected {expected_world} visible GPUs, found {world_size}; "
                           "refusing to run with the wrong allocation")
    os.environ.setdefault("MASTER_ADDR", "127.0.0.1")
    os.environ.setdefault("MASTER_PORT", "29500")
    os.environ.setdefault("TORCH_NCCL_ASYNC_ERROR_HANDLING", "1")
    mp.spawn(_spawn_worker, args=(world_size,), nprocs=world_size, join=True)


if __name__ == "__main__":
    launch()