File size: 153,006 Bytes
991b64a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55251f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
991b64a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55251f6
 
 
 
 
 
991b64a
 
 
55251f6
 
 
 
 
 
 
 
 
 
 
 
 
991b64a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
"""On-GPU fine-tuning worker (RunPod or Vast.ai). Modes: sft | rl.

This module runs on the provisioned GPU (RunPod or Vast.ai) launched by the selected
``autoslm.providers`` backend. It uses the shared recipe (``autoslm.engine.recipe``) so
SFT targets and RL rewards are rendered and scored consistently.

Artifacts (adapter, metrics.json, heartbeat.json, checkpoints) are streamed to a
Hugging Face dataset repo. HF checkpoints give preemption resilience: if a worker is
recycled mid-run we resume from the latest uploaded checkpoint. Metrics are also
returned directly to the caller by the launching provider.

Core environment variables (set by the launching provider / runner):
  RUN_MODE      sft|rl
  SEED          int
  HF_REPO       Hugging Face dataset repo for artifacts, populated per-run from the
                JobSpec's [train] hf_repo by whichever provider launches the worker
  HUGGINGFACE_TOKEN
  RUN_ID        unique id for this run (namespacing in the repo)

The AUTOSLM_*/RL_*/SFT_* env vars are A/B overrides documented at their use sites; the
JobSpec [train] table is the source of truth for per-run knobs.
"""

from __future__ import annotations

import contextlib
import json
import os
import random
import sys
import threading
import time
import traceback

from autoslm.engine.accounting import RunMetrics

# Shared, substrate-neutral fine-tuning internals (live in this same package).
from autoslm.engine.recipe import RECIPE
from autoslm.envs.registry import load_environment
from autoslm.spec import load_job_spec_from_env

HF_REPO = os.environ.get("HF_REPO", "")
RUN_ID = os.environ.get("RUN_ID", "local")
SEED = int(os.environ.get("SEED", "0"))
RUN_MODE = os.environ.get("RUN_MODE", "sft")
JOB_SPEC = load_job_spec_from_env()
# PHASE is the stable artifact namespace (sft|rl) and matches RUN_MODE for a train run.
PHASE = os.environ.get(
    "PHASE",
    JOB_SPEC.phase if JOB_SPEC else (RUN_MODE if RUN_MODE in ("sft", "rl") else "sft"),
)


def _load_active_env():
    """Load the run's verifiers environment from the JobSpec; require an explicit env.

    There is no default/builtin environment (verifiers-only): a run MUST name a verifiers/
    Prime Hub env id. Failing here (instead of falling back to some default) prevents a paid
    worker from training/evaluating the wrong task.
    """
    if JOB_SPEC is None:
        # No JobSpec at all (e.g. the module imported for a non-run path / a unit test). There
        # is nothing to select; defer the hard requirement to the JobSpec-present branch so the
        # module stays importable. A real run always carries a JobSpec.
        return None
    env_id = JOB_SPEC.environment.id
    if not env_id:
        # Every supported algorithm (sft/grpo) trains/evaluates against a verifiers env, so a
        # missing env is always a misconfigured spec. Fail loudly rather than fall back to a
        # default and burn a paid worker on the wrong task.
        raise RuntimeError(
            "JobSpec sets no environment: provide [environment] id (a verifiers/Prime Hub "
            "slug, e.g. 'owner/name')."
        )
    return load_environment(env_id, JOB_SPEC.environment.params)


ACTIVE_ENV = _load_active_env()


def require_active_env():
    """Return the run's loaded environment, or raise a CLEAR error when there is none.

    ``ACTIVE_ENV`` is None on the no-JobSpec path (the module is imported with no
    AUTOSLM_JOB_SPEC_JSON/PATH, e.g. a misconfigured worker launch). Every train/eval consumer
    needs a real env; without this guard the first ``ACTIVE_ENV.<attr>`` access dies with an
    opaque ``AttributeError: 'NoneType' object has no attribute ...``. Fail loudly with an
    actionable message instead β€” mirrors the explicit RuntimeError raised when a JobSpec is
    present but names no environment.
    """
    if ACTIVE_ENV is None:
        raise RuntimeError(
            "no environment is loaded: this worker was started without a JobSpec "
            "(AUTOSLM_JOB_SPEC_JSON / AUTOSLM_JOB_SPEC_PATH is unset). A train/eval run must "
            "carry a JobSpec naming [environment] id (a verifiers/Prime Hub slug, e.g. "
            "'owner/name')."
        )
    return ACTIVE_ENV


# Thinking/reasoning mode: one flag per run, consumed identically by SFT rendering,
# RL rollouts, and serving. The env fallback serves the bench/no-JobSpec path.
THINKING = (
    JOB_SPEC.thinking
    if JOB_SPEC
    else os.environ.get("AUTOSLM_THINKING", "0") not in ("0", "false", "False")
)


# ---------------------------------------------------------------------------
# HF helpers (code-delivery + artifact channel; works without inbound network)
# ---------------------------------------------------------------------------
def error_artifact_name(mode: str) -> str:
    """Per-mode error filename (e.g. error_sft.txt) so a run's traceback is uploaded
    under a stable name even though heartbeat.json is single-file/overwritten."""
    return f"error_{mode}.txt"


def hf_api():
    from huggingface_hub import HfApi

    return HfApi(token=os.environ.get("HUGGINGFACE_TOKEN"))


def hf_prefix() -> str:
    return f"{PHASE}/{RUN_ID}/seed{SEED}"


def _hf_upload(do_upload, repo_subpath: str, required: bool, label: str) -> None:
    """Shared HF upload loop for files/folders: HF_REPO guard + retry/raise-or-warn.

    ``required=True`` (completion artifacts DONE/metrics.json, the trained adapter) retries
    and finally raises: a swallowed upload failure would make the control plane mark a
    finished run failed/retried, or mark the run done while deployment can never download
    the missing adapter. Optional artifacts (generations, logs) only warn.
    """
    if not HF_REPO:
        return
    attempts = 3 if required else 1
    for attempt in range(attempts):
        try:
            do_upload()
            return
        except Exception as e:
            if required and attempt + 1 < attempts:
                print(f"{label} retry {attempt + 1}/{attempts}: {e}")
                time.sleep(5 * (attempt + 1))
                continue
            if required:
                raise RuntimeError(f"required upload of {repo_subpath!r} failed: {e}") from e
            print(f"{label} warn:", e)
            return


def hf_upload_file(local_path: str, repo_subpath: str, required: bool = False):
    """Upload one file to the run's HF prefix."""
    _hf_upload(
        lambda: hf_api().upload_file(
            path_or_fileobj=local_path,
            path_in_repo=f"{hf_prefix()}/{repo_subpath}",
            repo_id=HF_REPO,
            repo_type="dataset",
        ),
        repo_subpath,
        required,
        "hf_upload_file",
    )


def hf_upload_folder(local_dir: str, repo_subpath: str, required: bool = False):
    """Upload a folder to the run's HF prefix."""
    _hf_upload(
        lambda: hf_api().upload_folder(
            folder_path=local_dir,
            path_in_repo=f"{hf_prefix()}/{repo_subpath}",
            repo_id=HF_REPO,
            repo_type="dataset",
        ),
        repo_subpath,
        required,
        "hf_upload_folder",
    )


def hf_resume_checkpoint() -> str | None:
    """Latest streamed trainer checkpoint for this run (or None).

    Checkpoints are uploaded DURING the run by ``make_checkpoint_upload_callback`` as
    ``<prefix>/checkpoint/checkpoint-<step>/``; a replacement worker downloads the
    newest one so a mid-run preemption costs at most one save interval.
    """
    if not HF_REPO:
        return None
    try:
        from huggingface_hub import snapshot_download

        snapshot_download(
            repo_id=HF_REPO,
            repo_type="dataset",
            allow_patterns=[f"{hf_prefix()}/checkpoint/**"],
            local_dir="/tmp/resume",
            token=os.environ.get("HUGGINGFACE_TOKEN"),
        )
        base = os.path.join("/tmp/resume", hf_prefix(), "checkpoint")
        if not os.path.isdir(base):
            return None
        cands = [d for d in os.listdir(base) if d.startswith("checkpoint-")]
        if not cands:
            return None
        latest = max(cands, key=lambda d: int(d.split("-")[-1]))
        path = os.path.join(base, latest)
        print(f"[resume] found streamed checkpoint: {path}")
        return path
    except Exception as e:
        print("hf_resume_checkpoint warn:", e)
        return None


def prefetch_model(model_id: str) -> float:
    """Pull the model weights into the local HF cache up front; return seconds spent.

    The trainer/vLLM would download lazily anyway β€” doing it explicitly (a) makes the
    download a first-class, timed stage in the heartbeat stream (the cold-start metric
    the speed work optimizes), and (b) fails fast with a clear disk/network error
    instead of dying inside trainer construction. Idempotent: a warm cache costs ~0 s.
    """
    from huggingface_hub import snapshot_download

    t0 = time.time()
    try:
        snapshot_download(
            repo_id=model_id,
            # weights + tokenizer/config only (same exclusions as the image bake)
            ignore_patterns=["*.pth", "*.gguf", "original/*", "*.onnx", "*.msgpack", "*.h5"],
        )
    except Exception as e:
        # Surface but don't fail here: gated/local-only models still load fine through
        # the normal from_pretrained path the trainer uses next.
        print("prefetch_model warn:", e)
    secs = round(time.time() - t0, 1)
    heartbeat(
        "model_prefetched",
        model=model_id,
        download_seconds=secs,
        hf_transfer=os.environ.get("HF_HUB_ENABLE_HF_TRANSFER", ""),
    )
    return secs


def make_checkpoint_upload_callback():
    """Stream each trainer save to HF so preemption loses <= one save interval.

    Uploads run in a background thread (the train loop never blocks on the network);
    older checkpoints are deleted in the same commit. If an upload is still in flight
    when the next save fires, the new save is skipped (the following one catches up).
    """
    import threading

    from transformers import TrainerCallback

    lock = threading.Lock()

    class _CheckpointUpload(TrainerCallback):
        def on_save(self, args, state, control, **kwargs):
            if not HF_REPO:
                return
            step = int(state.global_step)
            ckpt_dir = os.path.join(args.output_dir, f"checkpoint-{step}")
            if not os.path.isdir(ckpt_dir):
                return
            if not lock.acquire(blocking=False):
                print(f"[ckpt] upload busy; skipping step {step}")
                return

            def _upload():
                try:
                    hf_api().upload_folder(
                        folder_path=ckpt_dir,
                        path_in_repo=f"{hf_prefix()}/checkpoint/checkpoint-{step}",
                        repo_id=HF_REPO,
                        repo_type="dataset",
                        delete_patterns=[f"{hf_prefix()}/checkpoint/**"],
                    )
                    heartbeat("checkpoint_uploaded", step=step)
                except Exception as e:
                    print("ckpt upload warn:", e)
                finally:
                    lock.release()

            threading.Thread(target=_upload, daemon=True).start()

    return _CheckpointUpload()


# Heartbeat HF-commit throttle. Each heartbeat() commits heartbeat.json to the HF artifact
# repo; committing every training step (the reward callback fires per step) blows HuggingFace's
# per-repo commit rate limit (128/hour), especially when several runs share one HF_REPO. Only
# the per-step "rl_step" stage is high-frequency, so throttle JUST that one to once per
# AUTOSLM_HEARTBEAT_MIN_S (default 60s); every other stage β€” including milestones and the
# terminal done/already_done β€” always commits so the control plane never misses a transition.
# The local file + stdout line are always written regardless.
_HB_LAST_UPLOAD = 0.0
_HB_MIN_INTERVAL_S = float(os.environ.get("AUTOSLM_HEARTBEAT_MIN_S", "60"))
_HB_THROTTLED_STAGES = frozenset({"rl_step"})
# Terminal transitions the control plane must never miss β€” always committed.
_HB_TERMINAL_STAGES = frozenset({"done", "already_done"})
# Benchmark/fan-out mode: when many runs share one HF artifact repo, even the
# per-milestone commits sum past HuggingFace's 128-commits/hour repo cap and
# 429-fail the terminal metrics.json upload. Setting AUTOSLM_HEARTBEAT_TERMINAL_ONLY=1
# throttles EVERY non-terminal stage (not just rl_step) so each run costs ~1-2
# commits; terminal done/already_done/error_* still always commit.
# Opt-IN flag (default off): use an explicit truthy allow-list so only intentional enables count
# ("off"/"no"/typos stay OFF) β€” the inverse not-in-falsy form would wrongly enable on "off"/"no".
_HB_TERMINAL_ONLY = os.environ.get("AUTOSLM_HEARTBEAT_TERMINAL_ONLY", "0").strip().lower() in (
    "1",
    "true",
    "yes",
    "on",
)


def _env_float(name: str, default: float | None = None) -> float | None:
    """Parse a float env knob, returning ``default`` on unset/empty/non-numeric instead of raising.
    A typo'd numeric env (e.g. RL_EPSILON_HIGH=0.2.8) must not crash the run at config build."""
    v = os.environ.get(name)
    if v is None or v == "":
        return default
    try:
        return float(v)
    except (TypeError, ValueError):
        print(f"[rl] ignoring non-numeric {name}={v!r}")
        return default


def _hb_is_terminal(stage: str) -> bool:
    return stage in _HB_TERMINAL_STAGES or stage.startswith("error_")


# Serializes heartbeat.json writes and _HB_LAST_UPLOAD reads/updates. During GRPO,
# heartbeat() is called concurrently from the trainer thread (reward callback) and the
# checkpoint-upload daemon thread; without this lock two writers can interleave and
# truncate/garble heartbeat.json (and race _HB_LAST_UPLOAD).
_HB_LOCK = threading.Lock()
# Serializes the actual HF upload (a slow network commit) SEPARATELY from _HB_LOCK so the
# trainer's frequent local writes never block on the network. Without it, two heartbeat
# threads can upload heartbeat.json concurrently: a slower upload could land AFTER a newer
# one on HF (reorder), so this lock makes uploads strictly ordered.
_HB_UPLOAD_LOCK = threading.Lock()


def heartbeat(stage: str, **kw):
    global _HB_LAST_UPLOAD
    payload = {
        "stage": stage,
        "ts": time.time(),
        "run_id": RUN_ID,
        "mode": RUN_MODE,
        "seed": SEED,
        **kw,
    }
    os.makedirs("/tmp/hb", exist_ok=True)
    p = "/tmp/hb/heartbeat.json"
    # _HB_LOCK guards ONLY the fast local work (atomic write + _HB_LAST_UPLOAD + snapshot capture);
    # the slow HF commit runs OUTSIDE it so the trainer's per-step reward callback never blocks on
    # the network behind the checkpoint daemon's commit (a GRPO perf regression).
    with _HB_LOCK:
        # Atomic write: temp file + os.replace() so a concurrent reader never sees a partial file.
        tmp = p + f".{os.getpid()}.{threading.get_ident()}.tmp"
        snapshot = json.dumps(payload)
        with open(tmp, "w") as f:
            f.write(snapshot)
        os.replace(tmp, p)
        now = time.time()
        if _hb_is_terminal(stage):
            upload_due = True  # never miss a terminal transition
        elif _HB_TERMINAL_ONLY:
            # Benchmark fan-out: commit only the FIRST non-terminal heartbeat, then never again
            # (NOT time-gated) so a long run can't re-breach the 128-commits/hour cap.
            upload_due = _HB_LAST_UPLOAD == 0.0
        else:
            throttled = stage in _HB_THROTTLED_STAGES
            upload_due = not throttled or (now - _HB_LAST_UPLOAD) >= _HB_MIN_INTERVAL_S
        if upload_due:
            _HB_LAST_UPLOAD = now  # claim the slot under the lock (throttle stays atomic)
    if upload_due:
        # Serialize the network commit under a SEPARATE lock so uploads can't reorder, and
        # upload the captured snapshot (via a private temp file, since hf_upload_file takes
        # a path) rather than re-reading p β€” which a newer heartbeat may already have
        # overwritten between our slot-claim and this upload.
        with _HB_UPLOAD_LOCK:
            up = p + f".{os.getpid()}.{threading.get_ident()}.upload.tmp"
            with open(up, "w") as f:
                f.write(snapshot)
            try:
                hf_upload_file(up, "heartbeat.json")
            finally:
                with contextlib.suppress(OSError):
                    os.remove(up)
    print("HEARTBEAT", json.dumps(payload))


# ---------------------------------------------------------------------------
# Decoding parity: render with the model's own chat template and one run-wide thinking
# flag (off by default), so SFT targets and RL rollouts use identical prompt
# formatting within a run.
# ---------------------------------------------------------------------------
def render_prompt(tokenizer, item) -> str:
    item = item if isinstance(item, dict) else {"question": item}
    msgs = require_active_env().prompt_messages(item)
    return tokenizer.apply_chat_template(
        msgs, tokenize=False, add_generation_prompt=True, enable_thinking=THINKING
    )


def strip_think(completion: str | None) -> str | None:
    """Drop <think>...</think> reasoning before the environment grades/rewards a
    thinking-mode completion.

    - closed block(s): keep only the text after the LAST </think>. This also covers
      always-thinking templates that pre-open <think> inside the generation prompt,
      whose completions contain </think> with no opening tag.
    - unclosed <think> (completion budget exhausted): keep only the pre-think text
      (usually empty), so answer extraction fails and the completion scores 0 β€”
      deliberate reward pressure to close thinking within budget, and it keeps a
      last-number fallback from matching numbers inside the reasoning.
    - no tags: unchanged.
    """
    if completion is None:
        return None
    if "</think>" in completion:
        return completion.rsplit("</think>", 1)[1]
    if "<think>" in completion:
        return completion.split("<think>", 1)[0]
    return completion


def graded_text(completion: str | None) -> str | None:
    """What the env grader/reward sees: thinking runs strip <think> blocks first (a
    completion whose reasoning never closes grades 0 β€” see strip_think). Applied once
    here, before ACTIVE_ENV.grade/reward, so it works for every environment."""
    return strip_think(completion) if THINKING else completion


def _patch_peft_weight_converter_compat() -> None:
    """peft 0.19.1 x transformers 5.6-5.10: make MoE adapter loading work.

    peft's ``build_peft_weight_mapping`` reconstructs transformers ``WeightConverter``
    objects passing ``distributed_operation=`` / ``quantization_operation=`` β€” kwargs
    the WeightConverter in transformers <5.11 doesn't accept (init=False dataclass
    fields), so loading a LoRA adapter onto any arch WITH weight conversions (the MoE
    tier; dense models have none) dies with ``TypeError: unexpected keyword argument
    'distributed_operation'`` (observed live: Qwen3.6-35B-A3B eval on A100). The
    worker can't take transformers>=5.11 (vllm 0.19.1 compat), so accept-and-drop
    unknown kwargs; on a single GPU those fields are unused. No-op once signatures
    match.
    """
    import inspect

    try:
        from transformers import core_model_loading as cml
    except Exception:  # pragma: no cover - older stacks have no converter module
        return
    converter = getattr(cml, "WeightConverter", None)
    if converter is None or getattr(converter, "_autoslm_compat", False):
        return
    accepted = set(inspect.signature(converter.__init__).parameters)
    if "distributed_operation" in accepted:
        return
    orig_init = converter.__init__

    def _compat_init(self, *args, **kwargs):
        dropped = [k for k in kwargs if k not in accepted]
        for k in dropped:
            kwargs.pop(k)
        orig_init(self, *args, **kwargs)

    converter.__init__ = _compat_init
    converter._autoslm_compat = True
    print("[compat] WeightConverter patched (peft<->transformers signature drift)")


# ---------------------------------------------------------------------------
# SFT
# ---------------------------------------------------------------------------
# Module-path segments that must never receive LoRA on natively-multimodal checkpoints
# trained text-only: the vision tower / projector / MTP head. Critically, adapters that
# DO touch them cannot be loaded by vLLM in text-only (language_model_only) serving β€”
# its LoRA loader rejects "unexpected modules" (observed with Qwen3.5-2B).
_VL_EXCLUDE_SEGMENTS = ("visual", "vision_tower", "multi_modal_projector", "mtp")


def lora_exclude_modules(model_id: str) -> str | None:
    """Regex (peft fullmatch semantics) excluding vision-tower modules from LoRA.

    Returns None when no exclusion is needed (pure text architectures). NOTE: peft's
    list-form exclude_modules uses suffix matching (like target_modules), which does
    NOT match leaf modules under 'visual.*' β€” a regex string is required.
    """
    excludes = {
        "qwen3_5": _VL_EXCLUDE_SEGMENTS,
        "qwen3_5_moe": _VL_EXCLUDE_SEGMENTS,
        "qwen3_6": _VL_EXCLUDE_SEGMENTS,
    }
    try:
        from transformers import AutoConfig

        cfg = AutoConfig.from_pretrained(model_id, trust_remote_code=True)
        model_type = getattr(cfg, "model_type", "") or ""
    except Exception as e:
        print("lora_exclude_modules: config probe failed:", e)
        return None
    segments = excludes.get(model_type)
    if not segments:
        return None
    alt = "|".join(segments)
    return rf"(^|.*\.)({alt})(\..*|$)"


def is_vl_checkpoint(model_id: str) -> bool:
    """True for natively-multimodal checkpoints we train/serve text-only (Qwen3.5/3.6)."""
    return bool(lora_exclude_modules(model_id))


def vllm_language_model_only_kwargs(model_id: str) -> dict:
    """Engine kwargs to skip the vision tower for VL checkpoints (vLLM >= 0.19).

    Besides wasting VRAM, the vision tower's attention path hardcodes vLLM's bundled
    flash-attn, whose PTX needs a newer driver JIT than many RTX 5090 hosts have
    ("PTX compiled with unsupported toolchain") β€” text-only loading sidesteps it and
    is the officially supported way to run Qwen3.5 as a pure LLM.
    """
    if os.environ.get("AUTOSLM_TEXT_ONLY", "1") in ("0", "false", "False"):
        return {}
    return {"language_model_only": True} if is_vl_checkpoint(model_id) else {}


def _attn_impl_for_capability(major: int, minor: int) -> str | None:
    """Map a CUDA compute capability to the trainer ``attn_implementation``.

    Attention uses PyTorch SDPA (its flash/efficient backend is already selected automatically
    on Ampere/Ada/Hopper) β€” the HF Kernels-Hub FA path is disabled because the torch2.10-
    compatible ``kernels`` versions break transformers' import. So:
      sm120 (Blackwell consumer 5090/RTX Pro) -> "sdpa" (forced to the cuDNN backend at train
      time β€” its default SDPA can fall to the slow math kernel); all other archs -> None (let
      transformers pick SDPA, which already flash-backs on Ampere/Ada/Hopper). The big LoRA
      win comes from the Liger fused kernels, not the attention path. Pure function (no torch)
      so it's unit-testable on CPU; override the whole thing with AUTOSLM_ATTN_IMPL.
    """
    if major == 12:  # Blackwell consumer: force cuDNN SDPA (avoid the math fallback)
        return "sdpa"
    return None


def _flash_attn_available() -> bool:
    """True when the ``flash_attn`` wheel is importable (our worker image builds it from source).

    Gates the packing default: TRL's ``packing_strategy='bfd'`` produces flattened/padding-free
    batches whose example boundaries are carried by ``position_ids`` and enforced ONLY by an
    attention impl that honors them (FlashAttention-2 varlen / flex_attention). Under plain SDPA,
    packed examples attend ACROSS boundaries (silent quality loss). find_spec only β€” no import side
    effects (and no CUDA init)."""
    try:
        import importlib.util

        return importlib.util.find_spec("flash_attn") is not None
    except Exception:
        return False


def _flex_packing_enabled() -> bool:
    """Opt-in flex_attention packing (default OFF). The no-flash-attn path to boundary-correct
    example packing on torch 2.10, where flash-attn has no prebuilt wheel."""
    return os.environ.get("AUTOSLM_FLEX_PACKING", "0") not in ("0", "false", "False", "")


def _flex_attention_available() -> bool:
    """True when torch's native flex_attention is importable (torch>=2.5; we're on 2.10)."""
    try:
        import importlib.util

        return importlib.util.find_spec("torch.nn.attention.flex_attention") is not None
    except Exception:
        return False


def _flex_arch_supported(model_id: str) -> bool:
    """True only when transformers can dispatch this model through flex_attention.

    MEASURED: transformers 5.12 raises ``Qwen3_5ForConditionalGeneration does not support an
    attention implementation through torch's flex_attention`` for the whole Qwen3.5/3.6 catalog
    (the arch isn't wired for flex). So flex-packing would CRASH the run there. We probe the model
    class's ``_supports_flex_attn`` flag from its config (no weights download); on any uncertainty
    return False so flex-packing safely no-ops rather than killing a paid run."""
    try:
        from transformers import AutoConfig
        from transformers.models.auto.modeling_auto import (
            MODEL_FOR_CAUSAL_LM_MAPPING,
        )

        cfg = AutoConfig.from_pretrained(model_id, trust_remote_code=True)
        cls = MODEL_FOR_CAUSAL_LM_MAPPING.get(type(cfg))
        return bool(cls is not None and getattr(cls, "_supports_flex_attn", False))
    except Exception as e:
        print(f"[sft] flex arch probe inconclusive ({e}); treating as unsupported")
        return False


def flex_packing_collator(base_collator, fixed_len: int, pad_token_id: int):
    """Wrap TRL's padding-free collator so packed batches carry the group-id document mask that
    transformers' flex_attention path needs (it builds ``document_ids`` from a 2D attention mask).

    TRL ``packing='bfd'`` auto-enables padding_free: each batch is ONE flattened sequence whose
    ``position_ids`` reset to 0 at every example boundary. We derive the group id per token as
    ``(position_ids == 0).cumsum`` (-> 1,1,1,2,2,3,...) and expose it AS ``attention_mask`` so
    ``make_flex_block_causal_mask`` separates documents (``document_ids[q]==document_ids[kv]``).

    Also PADS every batch to a FIXED total length so flex's BlockMask doesn't recompile on each
    distinct packed length (pytorch#136196). Pad tokens get group id 0, which flex's padding_mask
    (``attention_mask_2d > 0``) excludes, and label -100 so they don't contribute to the loss.
    """
    import torch as _torch

    def _collate(features):
        batch = base_collator(features)
        pos = batch.get("position_ids")
        if pos is None:  # not the padding-free/packed path β€” nothing to do
            return batch
        # group ids: bump at every position_ids==0 (document start). 1-based so pad (0) is distinct.
        group = (pos == 0).long().cumsum(dim=-1)
        cur = pos.shape[-1]
        if cur < fixed_len:
            paddings = fixed_len - cur
            z = (pos.shape[0], paddings)
            batch["input_ids"] = _torch.cat(
                [batch["input_ids"], _torch.full(z, pad_token_id, dtype=batch["input_ids"].dtype)],
                dim=-1,
            )
            if "labels" in batch:
                batch["labels"] = _torch.cat(
                    [batch["labels"], _torch.full(z, -100, dtype=batch["labels"].dtype)], dim=-1
                )
            pos = _torch.cat([pos, _torch.zeros(z, dtype=pos.dtype)], dim=-1)
            group = _torch.cat([group, _torch.zeros(z, dtype=group.dtype)], dim=-1)  # pad -> id 0
            batch["position_ids"] = pos
        elif cur > fixed_len:  # truncate the rare over-long pack to keep shapes static
            batch["input_ids"] = batch["input_ids"][..., :fixed_len]
            if "labels" in batch:
                batch["labels"] = batch["labels"][..., :fixed_len]
            batch["position_ids"] = pos[..., :fixed_len]
            group = group[..., :fixed_len]
        batch["attention_mask"] = group  # group-id mask; flex reads it as document_ids
        return batch

    return _collate


def optimal_attn_impl() -> str | None:
    """Best ``attn_implementation`` for the live GPU (None = leave transformers' default).

    Overridable with ``AUTOSLM_ATTN_IMPL``; "", "0", "false" all force-disable the override
    (use transformers' default) β€” never pass "0" through as a literal impl name.
    """
    forced = os.environ.get("AUTOSLM_ATTN_IMPL")
    if forced is not None:
        return forced if forced not in ("", "0", "false", "False") else None
    try:
        import torch

        if not torch.cuda.is_available():
            return None
        major, minor = torch.cuda.get_device_capability(0)
    except Exception as e:
        print("optimal_attn_impl probe failed:", e)
        return None
    impl = _attn_impl_for_capability(major, minor)
    if impl:
        print(f"[attn] sm{major}{minor} -> attn_implementation={impl}")
    return impl


# Liger's fused linear cross-entropy is a MEMORY optimization (it never materializes the fp32
# [B,T,vocab] logits), not a fixed-batch speed win. PR #174 ledger: on a 1B model at fixed batch
# it is a measured NET LOSS on EVERY arch (min-of-3: A100 0.86x, H100 0.90x, RTX 3090 0.78x,
# RTX 4090 0.83x, RTX 5090 0.79x) β€” the per-step Triton overhead isn't repaid because the small
# model's logits don't dominate memory. Its value appears on LARGE models (lets a bigger batch
# fit / avoids OOM). So gate the default by estimated model size; explicit env always overrides.
_LIGER_MIN_PARAMS = float(os.environ.get("AUTOSLM_LIGER_MIN_PARAMS", "3e9"))  # ~3B


def _estimate_params(cfg) -> float:
    """Rough param count from a HF config: embeddings (+untied lm_head) + transformer blocks.
    For multimodal checkpoints (e.g. Qwen3.5-VL) the LM dims live under ``text_config`` β€” read it
    when the top-level dims are absent, else the gate underestimates and wrongly disables the
    memory path (GC/Liger) for the 4B/9B tiers."""
    tc = getattr(cfg, "text_config", None)
    src = cfg if getattr(cfg, "hidden_size", 0) else (tc or cfg)
    h = getattr(src, "hidden_size", 0) or 0
    v = getattr(src, "vocab_size", 0) or getattr(cfg, "vocab_size", 0) or 0
    n = getattr(src, "num_hidden_layers", 0) or 0
    tied = getattr(src, "tie_word_embeddings", getattr(cfg, "tie_word_embeddings", False))
    emb = v * h * (1 if tied else 2)
    blocks = n * 12 * h * h  # ~12 h^2 per transformer block (attn + MLP)
    return float(emb + blocks)


def _liger_default_for_model(model_id: str) -> bool:
    """Default Liger ON only for models large enough that fused-CE's memory win pays off
    (β‰₯ AUTOSLM_LIGER_MIN_PARAMS, ~3B). 1B-class models measured net-negative -> default OFF."""
    try:
        from transformers import AutoConfig

        cfg = AutoConfig.from_pretrained(model_id, trust_remote_code=True)
        return _estimate_params(cfg) >= _LIGER_MIN_PARAMS
    except Exception as e:
        print("liger model-size probe failed (default off):", e)
        return False


def liger_on(env_var: str, default_on: bool | None = None) -> bool:
    """Whether to enable a Liger kernel path. Gated by ``env_var`` ("0"/"false"/"" disable;
    any other value force-enables intent). When the env is unset, ``default_on`` decides β€” call
    sites pass :func:`_liger_default_for_model` (on only for models large enough that fused-CE's
    memory win pays off; 1B-class is a measured net loss). Even when enabled, require a CUDA GPU
    AND that ``liger_kernel`` is importable β€” the local ``autoslm-train[gpu]`` extra doesn't ship
    it, so blindly setting use_liger_kernel would crash a local GPU run. No GPU / absent -> off."""
    val = os.environ.get(env_var)
    if val is not None:
        if val in ("0", "false", "False", ""):
            return False
    else:
        if default_on is None:
            default_on = False  # conservative when the caller gives no model-size signal
        if not default_on:
            return False
    try:
        import importlib.util

        import torch

        return bool(
            torch.cuda.is_available() and importlib.util.find_spec("liger_kernel") is not None
        )
    except Exception:
        return False


def setup_perf_backends() -> None:
    """Universal, arch-agnostic throughput knobs β€” safe on every CUDA arch, no JIT/compile cost.

    - TF32 for fp32 matmuls/cuDNN (Ampere+): the residual fp32 ops in a bf16 LoRA run (some
      norms, the optimizer's fp32 master step, any fp32 GEMM) run on the TF32 tensor cores at
      ~no accuracy cost. No-op on pre-Ampere. AUTOSLM_TF32=0 disables.
    """
    if os.environ.get("AUTOSLM_TF32") in ("0", "false", "False"):
        return
    try:
        import torch

        if not torch.cuda.is_available():
            return
        torch.set_float32_matmul_precision("high")  # TF32 for fp32 matmuls
        torch.backends.cuda.matmul.allow_tf32 = True
        torch.backends.cudnn.allow_tf32 = True
        print("[perf] TF32 matmul/cuDNN enabled")
    except Exception as e:
        print("setup_perf_backends skipped:", e)


def maybe_regional_compile(model, phase: str = "sft") -> int:
    """Lever 2 (opt-in, default OFF): REGIONAL torch.compile of the repeated decoder block.

    Returns the number of layers compiled (0 = no-op / disabled / skipped).

    Why regional, not full-graph: full-graph ``torch.compile`` (the existing AUTOSLM_TORCH_COMPILE
    / GRPOConfig.torch_compile path) traces the WHOLE model into one graph, which graph-breaks and
    CRASHES on our stack β€” PEFT LoRA wrappers plus the Qwen Gated-DeltaNet / flash-linear-attention
    custom ops are not capturable as a single graph. Compiling just ONE repeated unit β€” each
    ``model.model.layers[i]`` decoder block β€” with ``fullgraph=False`` lets Inductor fuse the
    pointwise/norm/MLP ops INSIDE a block (where most of the steady-state win is) while tolerating
    graph breaks at the LoRA/fla boundaries, and because all N layers share the same compiled
    artifact the cold-start cost is ~1 block's compile (~10x lower than full-graph).

    Safety: fully guarded. No-op unless AUTOSLM_TORCH_COMPILE_REGIONAL is set; skipped (to avoid
    double-compiling the same module) when the full-graph AUTOSLM_TORCH_COMPILE is also set; and
    every step is wrapped in try/except so a compile failure NEVER blocks training (the eager
    model is used unchanged). ``torch.compile(layer, ...)`` returns an OptimizedModule wrapper that
    is module-API compatible, so swapping it back into the layer list is transparent to PEFT/TRL.
    """
    if os.environ.get("AUTOSLM_TORCH_COMPILE_REGIONAL") not in ("1", "true", "True"):
        return 0
    # Don't double-compile: the full-graph path already wraps the whole model via torch_compile.
    if os.environ.get("AUTOSLM_TORCH_COMPILE", "0") not in ("0", "false", "False", ""):
        print(f"[{phase}] regional compile skipped: AUTOSLM_TORCH_COMPILE (full) is also set")
        return 0
    try:
        import torch

        if not torch.cuda.is_available():
            return 0
        # Locate the decoder-layer ModuleList. For a PEFT-wrapped causal LM the chain is
        # model.base_model.model.model.layers; for a plain HF causal LM it's model.model.layers;
        # VL/text checkpoints nest the LM under .model.language_model.layers. Walk a few known
        # locations and use the first ``layers`` that looks like an indexable ModuleList of blocks.
        candidates = []
        base = getattr(model, "base_model", None)
        inner = getattr(base, "model", None) if base is not None else None
        for root in (inner, model):
            if root is None:
                continue
            m = getattr(root, "model", root)
            for path in (m, getattr(m, "language_model", None)):
                if path is None:
                    continue
                layers = getattr(path, "layers", None)
                if layers is not None and hasattr(layers, "__len__") and len(layers) > 0:
                    candidates.append(layers)
        if not candidates:
            print(f"[{phase}] regional compile: could not locate decoder layers; skipping")
            return 0
        layers = candidates[0]
        mode = os.environ.get("AUTOSLM_TORCH_COMPILE_REGIONAL_MODE", "default")
        n = 0
        for i in range(len(layers)):
            try:
                layers[i] = torch.compile(layers[i], fullgraph=False, mode=mode)
                n += 1
            except Exception as e:  # compile one bad layer? keep the rest eager
                print(f"[{phase}] regional compile: layer {i} failed ({e}); leaving it eager")
        if n:
            print(
                f"[{phase}] regional torch.compile enabled on {n} decoder block(s) "
                f"(fullgraph=False, mode={mode})"
            )
        return n
    except Exception as e:  # never block training on the compile wiring
        print(f"[{phase}] regional compile skipped (error):", e)
        return 0


def finalize_alloc_conf_for_sleep() -> None:
    """Sync the CUDA allocator conf with the worker's RESOLVED vLLM sleep default.

    The launcher (providers/*/train.py build_worker_env) must pick PYTORCH_ALLOC_CONF before this
    process starts, but it can't always know the GRPO sleep decision: for a small model with
    RL_VLLM_SLEEP unset the worker resolves sleep OFF (the speed default), yet the launcher
    conservatively assumes sleep ON and picks the non-expandable conf (safe, but fragments a long
    colocate run). When the launcher cedes the decision (it sets AUTOSLM_ALLOC_AUTO=1 β€” only when
    it applied a DEFAULT, never an operator override), we resolve the same sleep default here (we
    have the model config + GPU) and, if sleep is OFF, switch to expandable_segments β€” which only
    crashes WITH sleep on, a case we've just ruled out. PYTORCH_ALLOC_CONF is read lazily at the
    first CUDA allocation, so this must run before any allocation (it does β€” called at boot)."""
    if os.environ.get("AUTOSLM_ALLOC_AUTO") != "1":
        return
    try:
        model_id = os.environ.get("BENCH_HF_MODEL", "")
        # Resolve the GRPO context the SAME way the sleep gate does (run_rl): RL_VLLM_MAX_LEN OR
        # [train].max_length. Using only RL_VLLM_MAX_LEN (often unset at boot) would mis-resolve a
        # long-context run configured via train.max_length -> wrong sleep default -> wrong alloc conf.
        _spec_len = 0
        try:
            if JOB_SPEC and JOB_SPEC.train and JOB_SPEC.train.max_length:
                _spec_len = int(JOB_SPEC.train.max_length)
        except Exception:
            _spec_len = 0
        ctx = int(os.environ.get("RL_VLLM_MAX_LEN") or _spec_len or 0)
        if not _memory_mode(model_id, ctx):  # sleep resolves OFF -> expandable is safe + better
            conf = "expandable_segments:True"
            os.environ["PYTORCH_ALLOC_CONF"] = conf
            os.environ["PYTORCH_CUDA_ALLOC_CONF"] = conf
            print(f"[alloc] sleep resolves OFF -> {conf} (anti-fragmentation, matches worker gate)")
        else:
            print("[alloc] sleep resolves ON -> keeping launcher's non-expandable conf")
    except Exception as e:
        print("[alloc] auto-conf skipped:", e)


def probe_hopper_kernels() -> None:
    """Diagnose the Hopper Gated-DeltaNet fast-path stack, logging to the worker console.

    The 35B/Qwen3.5 GDN fast path on H100/H200 needs fla's TileLang backend (Triton>=3.4 is buggy,
    #640). Whether that engages hinges on `import tilelang` succeeding β€” which has aborted on the
    image (apache-tvm-ffi version skew, tilelang #2367). The bootstrap's pip fix prints to the Vast
    INSTANCE log, not console_<mode>.txt, so this probe (which runs in the worker) is the only place
    the actual import result is visible. Best-effort, never raises. Only meaningful on Hopper."""
    # When the operator has explicitly disabled fla (AUTOSLM_DISABLE_FLA), the TileLang fast path is
    # moot β€” skip the probe entirely so we never even spawn the tilelang import subprocess (and so
    # the disable, which runs first now, isn't second-guessed by a stale TileLang report).
    if os.environ.get("AUTOSLM_DISABLE_FLA") not in (None, "", "0", "false", "False"):
        print("[hopper-probe] skipped (AUTOSLM_DISABLE_FLA set; native delta path)", flush=True)
        return
    try:
        import torch

        if not torch.cuda.is_available():
            return
        major, _ = torch.cuda.get_device_capability(0)
        if major != 9:  # Hopper only; the #640/TileLang issue is sm90-specific
            return
    except Exception:
        return

    def _ver(mod):
        try:
            m = __import__(mod)
            return getattr(m, "__version__", "?")
        except Exception as e:
            return f"IMPORT-FAILED: {type(e).__name__}: {str(e)[:160]}"

    import importlib.metadata as _md

    def _dist(name):
        try:
            return _md.version(name)
        except Exception:
            return "absent"

    def _import_ok_isolated(mod):
        """Probe `import <mod>` in a SUBPROCESS so an uncatchable SIGABRT (tilelang's #2367 FFI
        double-registration aborts the interpreter β€” Python can't try/except it) reports a clean
        'abort' instead of killing the whole worker."""
        import subprocess as _sp

        try:
            r = _sp.run(
                [sys.executable, "-c", f"import {mod}"],
                capture_output=True,
                timeout=120,
            )
            if r.returncode == 0:
                return "ok"
            return f"FAILED rc={r.returncode}: {(r.stderr or b'').decode(errors='replace')[-120:]}"
        except Exception as e:
            return f"probe-error: {type(e).__name__}"

    print(
        "[hopper-probe] "
        + " | ".join(
            [
                f"triton={_ver('triton')}",
                f"flash_linear_attention={_dist('flash-linear-attention')}",
                f"apache-tvm-ffi={_dist('apache-tvm-ffi')}",
                f"tilelang(dist)={_dist('tilelang')}",
                f"tilelang(import)={_import_ok_isolated('tilelang') if _dist('tilelang') != 'absent' else 'absent'}",
            ]
        ),
        flush=True,
    )


def disable_fla_if_requested() -> None:
    """Hopper Gated-DeltaNet escape hatch β€” remove flash-linear-attention IN the worker process.

    flash-linear-attention's Triton backward is wrong on H100/H200 (Triton>=3.4, fla #640) and its
    tilelang fallback aborts in TVM FFI, so Qwen3.5/3.6 Gated-DeltaNet crashes in backward. With
    AUTOSLM_DISABLE_FLA=1 we make transformers fall back to its native pure-PyTorch delta rule β€”
    correct everywhere (slower, but the only working Hopper path).

    Why here and not in the bootstrap's `pip uninstall`: on the PyTorch image the bootstrap's pip
    targets one site-packages, but `fla` is importable from ANOTHER dir on the worker's sys.path
    (the image bakes it into /usr/local while the interpreter is conda), so the uninstall removed
    nothing the worker actually imports. Running here uses the worker's REAL sys.path and physically
    removes every `fla` package dir, so importlib.util.find_spec("fla") β€” which transformers' fla
    availability check uses β€” returns None and the native fallback engages. Logs land in
    console_<mode>.txt (the bootstrap's own prints do not), so the effect is observable.
    """
    if os.environ.get("AUTOSLM_DISABLE_FLA") not in ("1", "true", "True"):
        return
    import importlib
    import importlib.util
    import shutil

    removed = []
    for _ in range(6):  # a few passes: removing one copy can reveal another earlier on the path
        spec = importlib.util.find_spec("fla")
        if spec is None:
            break
        # Resolve the package directory (submodule_search_locations for a package, else the file dir).
        locs = list(getattr(spec, "submodule_search_locations", None) or [])
        if not locs and spec.origin:
            locs = [os.path.dirname(spec.origin)]
        progressed = False
        for loc in locs:
            if loc and os.path.isdir(loc) and os.path.basename(loc) == "fla":
                try:
                    shutil.rmtree(loc)
                    removed.append(loc)
                    progressed = True
                except Exception as e:
                    print(f"[fla] could not remove {loc}: {e}", flush=True)
        importlib.invalidate_caches()
        if not progressed:
            break
    still = importlib.util.find_spec("fla") is not None
    print(
        f"[fla] AUTOSLM_DISABLE_FLA: removed {removed or 'nothing'}; "
        f"find_spec('fla') -> {'STILL PRESENT' if still else 'gone (native delta-rule)'}",
        flush=True,
    )


# Long-context runs are memory-bound (activations + vLLM KV cache scale with sequence length), so
# they need the memory features even on a SMALL model β€” PR #174 measured a 1B model OOM on GRPO at
# 4096 ctx in speed mode, but it fits in memory mode. So "memory mode" = large model OR long ctx.
_LONG_CONTEXT_TOKENS = int(os.environ.get("AUTOSLM_LONG_CONTEXT_TOKENS", "2048"))


def _memory_mode(model_id: str, max_length: int = 0) -> bool:
    """Whether to default the memory-saving features (Liger, grad-checkpointing, vLLM sleep) ON:
    a large model (fused-CE memory win) OR a long context (activations/KV dominate). Small model +
    short context -> off (optimize for speed)."""
    if max_length and max_length >= _LONG_CONTEXT_TOKENS:
        return True
    return _liger_default_for_model(model_id)


def grad_checkpointing_on(model_id: str, max_length: int = 0) -> bool:
    """Gradient checkpointing recomputes the forward in backward (~25% slower) to save activation
    memory β€” a MEMORY feature, not speed. Default ON for large models / long context that need the
    headroom; OFF for small+short runs that fit without it (the speed win). Env AUTOSLM_GRAD_CKPT
    (1/0) always overrides. Mirrors the small=speed / large-or-long=memory principle."""
    val = os.environ.get("AUTOSLM_GRAD_CKPT")
    if val is not None:
        return val not in ("0", "false", "False")
    return _memory_mode(model_id, max_length)


def fused_optim_name(memory_default: bool = False) -> str:
    """TRL/HF ``optim`` value. Fused foreach AdamW (single-kernel optimizer step) by default;
    set AUTOSLM_FUSED_OPTIM=0 to fall back to plain ``adamw_torch`` (A/B baseline knob).
    AUTOSLM_OPTIM overrides entirely with any HF optim enum string (e.g. paged_adamw_8bit for QLoRA
    OOM-spike safety, ademamix / ademamix_8bit for token efficiency) β€” research-backed A/B levers.

    ``memory_default``: on the memory-tight paths (QLoRA / colocated GRPO) the default becomes
    8-bit paged AdamW (bitsandbytes int8 optimizer state paged to host RAM, so training fits a
    smaller GPU) instead of the fused-foreach speed default. AUTOSLM_OPTIM still overrides, and
    AUTOSLM_FUSED_OPTIM=0 still forces plain adamw_torch β€” so both the speed and memory knobs win."""
    override = os.environ.get("AUTOSLM_OPTIM")
    if override and override not in ("0", "false", "False"):
        return override
    val = os.environ.get("AUTOSLM_FUSED_OPTIM")
    if val is not None and val in ("0", "false", "False"):
        return "adamw_torch"
    if memory_default:
        return "paged_adamw_8bit"
    return "adamw_torch_fused"


def wandb_report_to() -> list[str]:
    """TRL/HF ``report_to`` targets. Restores the W&B logging the legacy freesolo training path had
    but the autoslm migration dropped: report to W&B when WANDB_API_KEY is present (and not
    explicitly disabled). No key / WANDB_DISABLED -> [] (silent, the metrics.json artifact is still
    the source of truth). Sets a default project so runs land in one place."""
    if not os.environ.get("WANDB_API_KEY"):
        return []
    if os.environ.get("WANDB_DISABLED") in ("1", "true", "True"):
        return []
    if os.environ.get("WANDB_MODE", "").strip().lower() == "disabled":
        return []
    import importlib.util

    if importlib.util.find_spec("wandb") is None:
        print("[wandb] WANDB_API_KEY set but the wandb package is missing; skipping W&B logging")
        return []
    os.environ.setdefault("WANDB_PROJECT", "autoslm")
    return ["wandb"]


def wandb_run_name() -> str:
    """Stable, human-readable W&B run name tying the dashboard run to the AutoSLM run id."""
    return f"autoslm-{PHASE}-{RUN_ID}-seed{SEED}"


def wandb_run_info() -> dict:
    """The live W&B run's {url, id, project} if W&B is active, else {}. Recorded in metrics.json so
    the W&B run is verifiable + the freesolo agent's `wandb_runs` / the SDK's link_wandb can point at
    the real dashboard URL β€” the link the autoslm migration otherwise dropped. Never raises."""
    try:
        import wandb

        run = getattr(wandb, "run", None)
        if run is None:
            return {}
        return {
            "wandb_url": getattr(run, "url", None),
            "wandb_id": getattr(run, "id", None),
            "wandb_project": getattr(run, "project", None),
        }
    except Exception:
        return {}


def _sdpa_cudnn_ctx(attn_impl: str | None):
    """Context forcing the cuDNN SDPA backend (real Blackwell-consumer kernels) when we fell
    back to plain SDPA on sm120; a no-op context otherwise. Best-effort."""
    if attn_impl != "sdpa":
        return contextlib.nullcontext()
    try:
        from torch.nn.attention import SDPBackend, sdpa_kernel

        return sdpa_kernel([SDPBackend.CUDNN_ATTENTION, SDPBackend.EFFICIENT_ATTENTION])
    except Exception as e:
        print("[attn] cuDNN SDPA backend unavailable, using default SDPA:", e)
        return contextlib.nullcontext()


def patch_vllm_language_model_only(model_id: str) -> bool:
    """Force ``language_model_only=True`` on vLLM engines created by third-party code
    (TRL's colocated GRPO rollout engine) for VL checkpoints. Returns True if patched."""
    extra = vllm_language_model_only_kwargs(model_id)
    if not extra:
        return False
    try:
        import vllm

        if getattr(vllm.LLM.__init__, "_autoslm_lmo_patched", False):
            return True
        orig = vllm.LLM.__init__

        def patched(self, *args, **kwargs):
            kwargs.setdefault("language_model_only", True)
            return orig(self, *args, **kwargs)

        patched._autoslm_lmo_patched = True
        vllm.LLM.__init__ = patched
        print(f"[vllm] language_model_only patch active for {model_id}")
        return True
    except Exception as e:
        print("patch_vllm_language_model_only warn:", e)
        return False


def make_lora(model_id: str | None = None):
    """LoRA config. We target 'all-linear' (every nn.Linear) rather than a hardcoded
    q/k/v/o list: it is architecture-agnostic, so the same recipe works for the dense
    default (Qwen3-4B-Instruct-2507) and for newer models with extra projection
    types (e.g. the Qwen3.5 hybrid Gated-DeltaNet) without missing any adapters.
    For natively-multimodal checkpoints the vision tower is excluded (see
    ``lora_exclude_modules``)."""
    from peft import LoraConfig

    # PEFT target_modules accepts the special string "all-linear" OR a LIST of module-name
    # suffixes. A comma-separated env (e.g. "q_proj,k_proj,v_proj,o_proj" to adapt attention only
    # and leave the MoE experts frozen) MUST be split into a list β€” else PEFT treats the whole
    # string as ONE module name and raises "Target modules ... not found in the base model".
    _parts = [t.strip() for t in os.environ.get("LORA_TARGETS", "all-linear").split(",") if t.strip()]
    # "all-linear" is a PEFT SPECIAL string, not a module name β€” keep it as a string (incl. when a
    # stray trailing comma made it the sole element, e.g. "all-linear," -> ["all-linear"]). Any
    # real multi-module value becomes a list of suffixes.
    targets = "all-linear" if (not _parts or _parts == ["all-linear"]) else _parts
    rank = JOB_SPEC.train.lora_rank if JOB_SPEC else RECIPE.lora.rank
    alpha = JOB_SPEC.train.lora_alpha if JOB_SPEC else RECIPE.lora.alpha
    kwargs = {
        "r": rank,
        "lora_alpha": alpha,
        "lora_dropout": RECIPE.lora.dropout,
        "target_modules": targets,
        "task_type": "CAUSAL_LM",
    }
    # Adapter initialization (convergence lever): AUTOSLM_LORA_INIT picks PEFT's init_lora_weights.
    # "pissa_niter_16" inits A/B from the base weight's top singular vectors (fast SVD, ~seconds) so
    # LoRA converges faster + to higher quality than the default zero-B init (arXiv 2404.02948);
    # "olora"/"eva"/"gaussian" also available. Default unset -> PEFT default (True). NOTE: PiSSA
    # mutates the effective base, so the saved adapter is a PiSSA-residual unless converted β€” fine for
    # our train+eval+serve-same-stack flow; rsLoRA via AUTOSLM_RSLORA=1 helps only at high rank.
    _init = os.environ.get("AUTOSLM_LORA_INIT")
    if _init and _init not in ("0", "false", "False"):
        kwargs["init_lora_weights"] = _init if _init not in ("true", "True", "1") else True
        print(f"[lora] init_lora_weights={kwargs['init_lora_weights']}")
    if os.environ.get("AUTOSLM_RSLORA") in ("1", "true", "True"):
        kwargs["use_rslora"] = True
        print("[lora] rsLoRA scaling enabled")
    if model_id and targets == "all-linear":
        exclude = lora_exclude_modules(model_id)
        if exclude:
            kwargs["exclude_modules"] = exclude
            print(f"[lora] excluding modules for {model_id}: {exclude}")
    return LoraConfig(**kwargs)


def model_quant(model_id: str) -> str:
    """Quantization tier for this model: catalog entry > AUTOSLM_QUANT env > bf16."""
    env_q = os.environ.get("AUTOSLM_QUANT")
    if env_q:
        return env_q
    try:
        from autoslm.catalog import MODELS

        info = MODELS.get(model_id)
        if info is not None:
            return info.quant
    except Exception as e:
        print("model_quant: catalog probe failed:", e)
    return "bf16"


def quant_weights_repo(model_id: str) -> str:
    """Pre-quantized weights repo for the QLoRA tier (or "" to quantize at load).

    AUTOSLM_QUANT_REPO env (A/B / one-off override) > catalog ``quant_repo``. The
    returned repo is what the trainer loads; the tokenizer/chat template still come
    from the base ``model_id``.
    """
    env_repo = os.environ.get("AUTOSLM_QUANT_REPO")
    if env_repo:
        return env_repo
    try:
        from autoslm.catalog import MODELS

        info = MODELS.get(model_id)
        return getattr(info, "quant_repo", "") if info else ""
    except Exception as e:
        print("quant_weights_repo: catalog probe failed:", e)
        return ""


def attn_impl() -> str:
    """Attention kernel for the trainer model load. Default SDPA: PyTorch's flash /
    memory-efficient attention (O(seq) attention memory instead of materializing the
    O(seq^2) score matrix) β€” a large activation saving at long context, with NO extra
    dependency. AUTOSLM_ATTN_IMPL overrides ("flash_attention_2" needs the flash-attn wheel;
    "eager" disables) β€” the SAME canonical var the launcher allowlist forwards and
    optimal_attn_impl() reads; AUTOSLM_ATTN is a legacy alias. vLLM already uses flash attention
    for the GRPO rollout engine."""
    forced = os.environ.get("AUTOSLM_ATTN_IMPL")
    if forced not in (None, "", "0", "false", "False"):
        return forced
    return os.environ.get("AUTOSLM_ATTN", "sdpa")


def resolve_weights_id(model_id: str) -> str:
    """Weights repo the trainer should load for ``model_id``.

    For the 4bit-qlora tier this is the pre-quantized export when one exists (~3.5x
    smaller download/disk); otherwise the base ``model_id``. The tokenizer/chat template
    always come from the base ``model_id``. ``prequantized`` is then ``weights_id != model_id``.
    """
    if model_quant(model_id) == "4bit-qlora":
        return quant_weights_repo(model_id) or model_id
    return model_id


def qlora_model_init_kwargs(prequantized: bool = False) -> dict:
    """Model-load kwargs for the 4-bit QLoRA tier (large MoEs on one consumer GPU).

    ``prequantized``: the checkpoint already carries a bitsandbytes quantization
    config (a ``quant_repo``), so we must not pass a second BitsAndBytesConfig β€”
    transformers would ignore the checkpoint's and warn.
    """
    import torch

    kwargs: dict = {"dtype": torch.bfloat16, "attn_implementation": attn_impl()}
    if not prequantized:
        from transformers import BitsAndBytesConfig

        kwargs["quantization_config"] = BitsAndBytesConfig(
            load_in_4bit=True,
            bnb_4bit_compute_dtype=torch.bfloat16,
            bnb_4bit_quant_type="nf4",
            bnb_4bit_use_double_quant=True,
        )
    return kwargs


def require_vllm_for_rollout_func(use_rollout_func: bool, use_vllm: bool, model_id: str) -> None:
    """Fail fast when a multi-turn GRPO run needs colocated vLLM but it's disabled.

    The multi-turn rollout closure (``multiturn_rollout.build_rollout_func``) drives generation
    through ``trainer.vllm_generation.llm``. TRL only creates that engine when ``use_vllm`` is
    True, so with vLLM disabled (catalog ``grpo_use_vllm=False`` β€” e.g. the MoE 35B tier β€” or
    ``RL_USE_VLLM=0``) the rollout would AttributeError at the first turn. Reject the combination
    up front with an actionable message instead of crashing deep in training.
    """
    if use_rollout_func and not use_vllm:
        raise RuntimeError(
            f"multi-turn GRPO needs colocated vLLM, which is disabled for {model_id} "
            "(grpo_use_vllm=False / RL_USE_VLLM=0). Use a single-turn environment for this "
            "model, or a model tier that keeps vLLM enabled for rollouts."
        )


def run_sft():
    from datasets import Dataset
    from transformers import AutoTokenizer
    from trl import SFTConfig as TRLSFTConfig
    from trl import SFTTrainer

    require_active_env()  # fail loudly (not AttributeError: NoneType) on the no-JobSpec path
    t_start = time.time()
    heartbeat("sft_start")
    # SFT only fits the single assistant `sft_target` per row; a multi-turn/ToolEnv env's
    # tool/env turns are not represented, so SFT on one would silently mis-train (imitating a
    # collapsed single-turn target). Warn loudly so it is not mistaken for proper multi-turn SFT.
    if getattr(ACTIVE_ENV, "multi_turn", False):
        print(
            "[sft][warn] this is a multi-turn / tool verifiers environment, but SFT only fits "
            "the single assistant target per row (tool/env turns are ignored). The model will be "
            "trained on collapsed single-turn targets; multi-turn SFT is not supported. Use a "
            "single-turn environment, or expect a single-turn-only fit."
        )
    wait_for_gpu()
    setup_perf_backends()
    model_id = JOB_SPEC.model if JOB_SPEC else RECIPE.hf_model_id
    # QLoRA tier may load a pre-quantized export (~3.5x smaller download/disk);
    # the tokenizer below still comes from the base id.
    weights_id = resolve_weights_id(model_id)
    download_seconds = prefetch_model(weights_id)
    tok = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
    if tok.pad_token is None:
        tok.pad_token = tok.eos_token

    # Build SFT text dataset (seeded shuffle for reproducibility)
    train = ACTIVE_ENV.dataset("train")
    rng = random.Random(SEED)
    rng.shuffle(train)
    max_examples = int(os.environ.get("SFT_MAX_EXAMPLES", "0"))
    if max_examples > 0:
        train = train[:max_examples]
    texts = []
    for ex in train:
        msgs = [
            *ACTIVE_ENV.prompt_messages(ex),
            {"role": "assistant", "content": ACTIVE_ENV.sft_target(ex)},
        ]
        texts.append(
            {
                "text": tok.apply_chat_template(
                    msgs, tokenize=False, add_generation_prompt=False, enable_thinking=THINKING
                )
            }
        )
    if THINKING and not any("<think>" in t["text"] for t in texts[:256]):
        print(
            "WARN: thinking mode is ON but no sampled SFT target contains a <think> "
            "trace β€” training on non-reasoning targets teaches the model to SKIP "
            "thinking. Use a dataset with reasoning traces, or set thinking = false."
        )
    ds = Dataset.from_list(texts)

    setup_seconds = time.time() - t_start
    heartbeat("sft_model_load", setup_seconds=setup_seconds)

    default_epochs = (
        JOB_SPEC.train.epochs
        if JOB_SPEC and JOB_SPEC.train.epochs is not None
        else RECIPE.sft.num_epochs
    )
    epochs = int(os.environ.get("SFT_EPOCHS", str(default_epochs)))
    # SDK [train] knobs override the recipe default; an operator env var still wins last.
    _t = JOB_SPEC.train if JOB_SPEC else None
    per_device_bs = int(os.environ.get("SFT_PER_DEVICE_BS", "4"))
    # batch_size is the GLOBAL/effective batch: grad-accum is sized to reach it. Cap the
    # per-device micro-batch at the target (so a target < per_device doesn't overshoot) and
    # use CEIL division so the realized global batch is never BELOW the requested one (floor
    # would undershoot when target isn't a multiple of per_device, e.g. 16/6 -> 12).
    effective_batch = (
        _t.batch_size if _t and _t.batch_size is not None else RECIPE.sft.effective_batch
    )
    per_device_bs = max(1, min(per_device_bs, effective_batch))
    grad_accum = max(1, -(-effective_batch // per_device_bs))
    sft_lr = _t.learning_rate if _t and _t.learning_rate is not None else RECIPE.sft.learning_rate
    sft_max_len = (
        _t.max_length
        if _t and _t.max_length is not None
        else (RECIPE.sft.max_seq_len_thinking if THINKING else RECIPE.sft.max_seq_len)
    )
    sft_save_default = _t.save_every if _t and _t.save_every is not None else 50
    out_dir = f"/tmp/sft_seed{SEED}"
    resume_ckpt = hf_resume_checkpoint()

    # SFT_MAX_STEPS>0 caps optimizer steps (used by the cheap pre-flight smoke).
    max_steps = int(os.environ.get("SFT_MAX_STEPS", "0"))
    cfg_kwargs = {
        "output_dir": out_dir,
        "num_train_epochs": epochs,
        "per_device_train_batch_size": per_device_bs,
        "gradient_accumulation_steps": grad_accum,
        "learning_rate": sft_lr,
        "warmup_ratio": RECIPE.sft.warmup_frac,
        "logging_steps": 10,
        "save_steps": int(os.environ.get("SFT_SAVE_STEPS", str(sft_save_default))),
        "save_total_limit": 1,
        # Memory-light checkpoints: save ONLY the (small LoRA) model, not the optimizer /
        # scheduler / RNG state β€” skips the optimizer-state serialization spike at save and
        # writes just the adapter. (We don't resume mid-run; seeds restart cleanly.)
        "save_only_model": True,
        "max_length": sft_max_len,
        "bf16": True,
        "report_to": wandb_report_to(),  # W&B when WANDB_API_KEY present (restored post-autoslm-migration)
        "run_name": wandb_run_name(),
        # Dataloader parallelism: overlap host-side collation/tokenization with GPU compute so a
        # real (large) training set isn't dataloader-bound. Pure throughput, zero quality change.
        # Negligible on the tiny benchmark (pre-tokenized, in-memory); a real win at production
        # dataset sizes. SFT_DATALOADER_WORKERS overrides (0 = main-process, the old behavior).
        "dataloader_num_workers": int(os.environ.get("SFT_DATALOADER_WORKERS", "4")),
        "dataloader_pin_memory": True,
        "dataloader_persistent_workers": int(os.environ.get("SFT_DATALOADER_WORKERS", "4")) > 0,
        "seed": SEED,
        "gradient_checkpointing": grad_checkpointing_on(model_id, sft_max_len),
        "completion_only_loss": False,
        # Optimizer: fused foreach AdamW (free single-kernel step) for the speed-default tiers,
        # 8-bit paged AdamW (int8 state paged to host RAM -> fits a smaller GPU) for the
        # memory-tight QLoRA tier. AUTOSLM_OPTIM overrides; AUTOSLM_FUSED_OPTIM=0 -> plain adamw_torch.
        "optim": fused_optim_name(memory_default=model_quant(model_id) == "4bit-qlora"),
    }
    if max_steps > 0:
        cfg_kwargs["max_steps"] = max_steps
    # Example packing: concatenate short examples into full max_length sequences so a batch isn't
    # mostly pad tokens β€” PR #174 measured a 4.4-10.7x SFT speedup (h100 8.2x, 4090 10.7x) because
    # instruction targets are far shorter than max_seq_len; unpacked batches waste most of their
    # FLOPs on padding. TRL's 'bfd' strategy makes padding-free batches whose example boundaries are
    # honored ONLY by an attention impl that reads them β€” under plain SDPA packed examples
    # cross-contaminate (silent quality loss). Two correct backends:
    #   - FlashAttention-2 varlen (reads position_ids). FASTEST, but flash-attn has NO prebuilt wheel
    #     for torch 2.10 (PyPI sdist-only; Dao-AILab wheels stop at torch 2.9) so it would build from
    #     source on every cold start (~20 min, fragile) β€” it is NOT in the worker image. So _fa_ok is
    #     False on the current stack and the FA path is effectively unavailable until flash-attn is
    #     baked into a prebuilt image.
    #   - flex_attention (torch>=2.5 native, no install): boundary-correct via a group-id document
    #     mask. TRL doesn't emit that mask, so we synthesize it from the per-doc-reset position_ids
    #     ((position_ids==0).cumsum) in a collator wrapper below, gated on AUTOSLM_FLEX_PACKING=1.
    # Default: packing ON when FA2 is importable; else flex-packing when AUTOSLM_FLEX_PACKING=1; else
    # SKIP (don't silently cross-contaminate). SFT_PACKING=0 disables; SFT_PACKING=1 forces.
    _packing_env = os.environ.get("SFT_PACKING")
    _want_packing = (_packing_env or "1") not in ("0", "false", "False")
    _packing_forced = _packing_env not in (None, "")
    _fa_ok = _flash_attn_available()
    _flex_packing = False
    if _want_packing and _fa_ok:
        cfg_kwargs["packing"] = True
        print("[sft] example packing enabled (FA2 varlen; SFT_PACKING=0 to disable)")
    elif (
        _want_packing
        and _flex_packing_enabled()
        and _flex_attention_available()
        and _flex_arch_supported(model_id)
    ):
        cfg_kwargs["packing"] = True
        _flex_packing = True
        print("[sft] example packing enabled (flex_attention group-mask, no flash-attn needed)")
    elif (
        _want_packing
        and _flex_packing_enabled()
        and not _flex_arch_supported(model_id)
        and not _packing_forced
    ):
        # DEFAULT (not explicitly forced): flex requested but the arch can't use flex_attention here
        # -> skip rather than crash. An explicit SFT_PACKING=1 falls through to the forced branch
        # below (bfd packing under SDPA, with the cross-contamination warning) β€” honor the override.
        print(
            f"[sft] flex-packing requested but {model_id}'s arch isn't flex_attention-capable in "
            "this transformers (e.g. Qwen3.5/3.6); skipping packing (would crash). Needs flash-attn."
        )
    elif _want_packing and _packing_forced:
        cfg_kwargs["packing"] = True
        print(
            "[sft] WARNING: packing forced without FA2 or flex β€” 'bfd' boundaries need varlen/flex; "
            "examples may cross-contaminate under SDPA. Set AUTOSLM_FLEX_PACKING=1 or SFT_PACKING=0."
        )
    elif _want_packing:
        print(
            "[sft] packing SKIPPED: no boundary-correct attn backend (flash-attn absent on torch "
            "2.10; flex off). Set AUTOSLM_FLEX_PACKING=1 to pack via flex_attention."
        )
    # torch.compile (Inductor): fuses pointwise ops + emits per-arch kernels; a real steady-state
    # win on long runs, but pays a one-time graph-compile cost (so off by default β€” A/B it via
    # AUTOSLM_TORCH_COMPILE=1). Especially promising on sm120/Blackwell where stock kernels lag.
    if os.environ.get("AUTOSLM_TORCH_COMPILE", "0") not in ("0", "false", "False", ""):
        cfg_kwargs["torch_compile"] = True
        print("[sft] torch.compile (Inductor) enabled")
    # Liger fused CE/RMSNorm/RoPE kernels (default on for GPU; SFT_LIGER=0 to disable). The
    # fused linear cross-entropy is the big large-vocab (Qwen ~152k) memory/throughput win.
    # Skip it when AUTOSLM_CCE=1: Cut Cross-Entropy patches the SAME loss path (post-trainer),
    # so enabling both would double-patch the LM head β€” CCE wins the loss, Liger would conflict.
    from autoslm.engine.cce import cce_will_install

    if not cce_will_install() and liger_on(
        "SFT_LIGER", default_on=_memory_mode(model_id, sft_max_len)
    ):
        cfg_kwargs["use_liger_kernel"] = True
        print("[sft] liger fused kernels enabled")
    _attn = optimal_attn_impl()  # arch-aware FlashAttention (Kernels Hub) / SDPA
    # Packing correctness: 'bfd' packed batches are boundary-correct ONLY under a varlen/flex attn.
    # With FA2 importable force flash_attention_2 (fastest); else, when flex-packing is on, force
    # flex_attention (the collator wrap below feeds it the group-id document mask). Either is a pure
    # win over the SDPA default which would cross-contaminate packed examples.
    if cfg_kwargs.get("packing") and _fa_ok:
        _attn = "flash_attention_2"
        print("[sft] attn_implementation=flash_attention_2 (packing boundary-correct varlen)")
    elif _flex_packing:
        _attn = "flex_attention"
        print("[sft] attn_implementation=flex_attention (packing boundary-correct document mask)")
    quant = model_quant(model_id)
    if quant == "4bit-qlora":
        # Large-MoE tier: 4-bit NF4 base + LoRA adapters (e.g. Qwen3.6-35B-A3B on a 5090).
        _patch_peft_weight_converter_compat()  # MoE adapter (re)load, e.g. ckpt resume
        mik = qlora_model_init_kwargs(prequantized=weights_id != model_id)
        print(f"[sft] loading {weights_id} in 4-bit (QLoRA tier)")
    else:
        # Explicit bf16 + no auto device-map: TRL/transformers-5 string loading can
        # otherwise fall back to fp32 (2x VRAM; observed 18.6 GB for a 4.66B model) or
        # accelerate-offload large models to meta ("expected device meta but got
        # cuda:0" in backward on the 9B).
        mik = {"dtype": "bfloat16", "device_map": None}
    if _attn:
        mik["attn_implementation"] = _attn
    cfg_kwargs["model_init_kwargs"] = mik
    # Activation offloading (MEMORY lever, prioritized): TRL moves checkpointed activations to CPU
    # during the forward and fetches them back in the backward (torchtune OffloadActivations, pinned
    # + stream-overlapped). Frees activation VRAM so a memory-tight tier (large model / long context)
    # can fit a bigger batch or longer sequence; ~<1% slowdown when it overlaps compute (only pays off
    # WITH gradient checkpointing, so gate on the same memory-mode signal). Feature-detected so an
    # older TRL without the field doesn't crash. AUTOSLM_ACT_OFFLOAD=1/0 overrides the gate.
    import dataclasses as _dc

    _sft_fields = {f.name for f in _dc.fields(TRLSFTConfig)}
    if "activation_offloading" in _sft_fields:
        _ao_env = os.environ.get("AUTOSLM_ACT_OFFLOAD")
        _ao = (
            _ao_env not in ("0", "false", "False")
            if _ao_env is not None
            else (cfg_kwargs.get("gradient_checkpointing") and _memory_mode(model_id, sft_max_len))
        )
        if _ao:
            cfg_kwargs["activation_offloading"] = True
            print("[sft] activation offloading enabled (memory: activations -> CPU)")
    # NEFTune (arXiv 2310.05914): add uniform noise (scaled by alpha) to the embedding activations
    # during the forward at TRAIN time only β€” a free instruction-tuning quality win, removed at
    # inference so it never affects serving or adds memory. Opt-in via SFT_NEFTUNE_ALPHA (HF/TRL
    # recommends 5). Feature-detected so an older TRL without the field is simply skipped.
    _neftune = os.environ.get("SFT_NEFTUNE_ALPHA")
    if (
        _neftune
        and _neftune not in ("0", "false", "False")
        and "neftune_noise_alpha" in _sft_fields
    ):
        try:
            cfg_kwargs["neftune_noise_alpha"] = float(_neftune)
            print(f"[sft] NEFTune embedding noise alpha={_neftune} (train-only quality lever)")
        except ValueError:
            print(f"[sft] ignoring non-numeric SFT_NEFTUNE_ALPHA={_neftune!r}")
    cfg = TRLSFTConfig(**cfg_kwargs)

    # LoRA+ (convergence lever, arXiv 2402.12354): give the LoRA B matrices a higher LR than A
    # (ratio AUTOSLM_LORAPLUS_RATIO, ~16). Reported ~2x fewer steps to target at identical per-step
    # FLOPs. TRL builds the model from a string inside __init__, so the optimizer (which needs the
    # instantiated params) can't be pre-built β€” override create_optimizer to construct it from
    # self.model once it exists. Falls back to the stock fused-AdamW path when the knob is unset.
    # LoRA+ only when a MEANINGFUL ratio (>1) is set: "0"/"1"/"" are truthy strings but mean "off"
    # (ratio 1 == plain LoRA), so parse to float and gate on >1 β€” else a stray "0" would enable a
    # degenerate B-LR=0 optimizer.
    try:
        _lp_ratio = float(os.environ.get("AUTOSLM_LORAPLUS_RATIO") or "0")
    except ValueError:
        _lp_ratio = 0.0
    _SFT = SFTTrainer
    if _lp_ratio > 1:

        class _SFT(SFTTrainer):  # local LoRA+ subclass
            def create_optimizer(self):
                if self.optimizer is None:
                    try:
                        import torch as _torch
                        from peft.optimizers import create_loraplus_optimizer

                        # PEFT's create_loraplus_optimizer forwards extra kwargs to the optimizer;
                        # the lr keyword name has shifted across PEFT versions, so pass it via
                        # optimizer_kwargs (the stable form) and fall back to a top-level lr=.
                        try:
                            self.optimizer = create_loraplus_optimizer(
                                model=self.model,
                                optimizer_cls=_torch.optim.AdamW,
                                optimizer_kwargs={"lr": self.args.learning_rate},
                                loraplus_lr_ratio=_lp_ratio,
                            )
                        except TypeError:
                            self.optimizer = create_loraplus_optimizer(
                                model=self.model,
                                optimizer_cls=_torch.optim.AdamW,
                                lr=self.args.learning_rate,
                                loraplus_lr_ratio=_lp_ratio,
                            )
                        print(f"[lora+] optimizer enabled (B-matrix LR ratio={_lp_ratio})")
                        return self.optimizer
                    except Exception as e:  # never block training on the LoRA+ wiring
                        print("[lora+] setup failed, falling back to default optimizer:", e)
                return super().create_optimizer()

    # Pass model as a string id + tokenizer as processing_class so TRL takes the
    # text/causal-LM path (not the VLM processor path) for this multimodal checkpoint.
    trainer = _SFT(
        model=weights_id,
        args=cfg,
        train_dataset=ds,
        peft_config=make_lora(model_id),
        processing_class=tok,
        callbacks=[make_checkpoint_upload_callback()],
    )

    if _flex_packing:
        # Feed flex_attention the group-id document mask (TRL's padding-free collator emits only
        # position_ids). Bucket to a FIXED total length so flex's BlockMask doesn't recompile per
        # distinct packed length; raise dynamo's cache cap so any residual shape variation doesn't
        # blow the compile cache (Axolotl uses 256 for exactly this).
        import torch as _t

        _t._dynamo.config.accumulated_cache_size_limit = max(
            256, _t._dynamo.config.accumulated_cache_size_limit
        )
        _fixed_len = max(1, int(cfg_kwargs.get("max_length") or sft_max_len)) * max(
            1, int(cfg_kwargs.get("per_device_train_batch_size") or 1)
        )
        trainer.data_collator = flex_packing_collator(
            trainer.data_collator, _fixed_len, int(tok.pad_token_id or 0)
        )
        print(f"[sft] flex-packing collator installed (bucketed to {_fixed_len} tokens)")

    from autoslm.engine.cce import install_cce
    from autoslm.engine.triton_kernels import install_custom_rmsnorm

    install_custom_rmsnorm()  # opt-in fused Triton RMSNorm (self-tests, falls back to eager)
    install_cce(
        trainer.model, model_id
    )  # opt-in Cut Cross-Entropy (AUTOSLM_CCE=1; dense, self-tests)
    maybe_regional_compile(
        trainer.model, "sft"
    )  # opt-in regional torch.compile (Lever 2; default off)
    t_train = time.time()
    with _sdpa_cudnn_ctx(_attn):  # force cuDNN SDPA on sm120 (no-op otherwise)
        trainer.train(resume_from_checkpoint=resume_ckpt)
    train_wall = time.time() - t_train

    adapter_dir = f"{out_dir}/adapter"
    trainer.model.save_pretrained(adapter_dir)
    tok.save_pretrained(adapter_dir)
    hf_upload_folder(adapter_dir, "adapter", required=True)
    heartbeat("sft_trained", train_wall=train_wall)

    # count train tokens
    train_tokens = int(sum(len(tok(t["text"])["input_ids"]) for t in texts) * epochs)

    # Write train metadata + the completion sentinel (metrics.json/DONE) for this phase.
    write_train_meta(
        phase="sft",
        adapter_dir=adapter_dir,
        model_id=model_id,
        train_wall=train_wall,
        setup_seconds=setup_seconds,
        train_tokens=train_tokens,
        generated_tokens=0,
        notes={
            "epochs": epochs,
            "resumed": bool(resume_ckpt),
            "download_seconds": download_seconds,
            "hf_transfer": os.environ.get("HF_HUB_ENABLE_HF_TRANSFER", ""),
            "thinking": THINKING,
            # Persist the loss curve so a CONVERGENCE A/B (PiSSA / LoRA+ init, etc.) is measurable
            # without a checkpoint: trainer_state.json is only written on a save_step, and the
            # console is only uploaded on failure, so a short successful run otherwise drops its
            # loss history entirely.
            "loss_curve": _metric_curve(trainer, "loss"),
            **wandb_run_info(),
        },
    )
    free_gpu(trainer)


# ---------------------------------------------------------------------------
# RL (GRPO) with TRL + colocated vLLM
# ---------------------------------------------------------------------------
def compute_grpo_batching(prompts_per_step: int, group_size: int, per_device_comps: int) -> dict:
    """Translate an intended ``prompts_per_step`` into a TRL GRPO batch configuration.

    TRL's GRPO batch sizing is denominated in **completions (prompt-completion pairs), not
    prompts**. The number of *unique prompts* optimized per step is

        (per_device_train_batch_size * gradient_accumulation_steps * num_processes)
        / num_generations

    So to actually optimize ``prompts_per_step`` prompts per step, the global *completion*
    batch must equal ``prompts_per_step * group_size``. We keep ``per_device`` small (it,
    not grad-accum, sets peak VRAM) and put the rest in gradient accumulation.

    The bug this fixes: ``grad_accum = prompts_per_step // per_device`` treated
    ``per_device_train_batch_size`` as a *prompt* count, omitting the ``* group_size``
    factor, so a run intended as 64 prompts/step actually optimized only
    ``64 / group_size = 8`` prompts/step (an 8x smaller effective batch).
    """
    import math

    group_size = max(1, int(group_size))
    prompts_per_step = max(1, int(prompts_per_step))
    per_device = max(1, int(per_device_comps))
    target_comps = prompts_per_step * group_size  # total completions / optimizer step
    # Never let the per-device completion micro-batch exceed the target completion batch:
    # a small prompts_per_step would otherwise overshoot it (mirrors run_sft's
    # `min(per_device_bs, effective_batch)`). No-op at the default (prompts_per_step=64).
    per_device = max(1, min(per_device, target_comps))
    grad_accum = max(1, target_comps // per_device)
    # TRL rejects a global completion batch (per_device * grad_accum) that is not
    # divisible by num_generations (= group_size), failing only AFTER the paid worker
    # is provisioned. per_device is the fixed VRAM knob, so round grad_accum UP to the
    # next multiple that makes the batch divisible (grad_accum must be a multiple of
    # group_size // gcd(per_device, group_size)). This only ever raises the effective
    # batch slightly; the common per_device|group_size cases are unchanged.
    accum_step = group_size // math.gcd(per_device, group_size)
    grad_accum = ((grad_accum + accum_step - 1) // accum_step) * accum_step
    generations_per_step = per_device * grad_accum
    unique_prompts_per_step = generations_per_step // group_size
    return {
        "per_device_train_batch_size": per_device,
        "gradient_accumulation_steps": grad_accum,
        "generations_per_step": generations_per_step,
        "unique_prompts_per_step": unique_prompts_per_step,
        # TRL requires the global completion batch be divisible by num_generations.
        "divisible_by_group": (generations_per_step % group_size == 0),
    }


def rl_per_device_comps(completion_len: int = 0, vocab: int = 152_000) -> int:
    """Per-device *completion* micro-batch for GRPO (TRL counts completions, not prompts).

    This, not grad-accum, sets peak trainer VRAM: the logprob pass materializes fp32 logits
    of shape [per_device, completion_len, vocab]. At Qwen's ~152k vocab a long completion is
    enormous (measured: per_device 8 x 4096 tok x 152k x 4 B = ~20 GiB single alloc -> OOMs
    a small card). So we MEMORY-CAP per_device to a logits budget (RL_LOGITS_BUDGET_GB,
    default 6) for the given completion length, then push the difference into grad-accum
    (compute_grpo_batching) so the effective batch is unchanged. This keeps long-completion
    GRPO on a cheaper GPU. RL_PER_DEVICE_PROMPTS forces an explicit value.
    """
    base = int(os.environ.get("RL_PER_DEVICE_PROMPTS", "2" if THINKING else "8"))
    if completion_len > 0:
        budget = float(os.environ.get("RL_LOGITS_BUDGET_GB", "6")) * 1e9
        cap = max(1, int(budget / (max(1, completion_len) * vocab * 4)))
        base = min(base, cap)
    return max(1, base)


def make_reward_heartbeat_callback():
    """A TRL/transformers callback that streams the per-step mean reward to the HF heartbeat
    channel, giving the worker a live RL signal (no pod log API) and recording a
    ``reward_history``. Built lazily so the module imports without transformers installed."""
    from transformers import TrainerCallback

    class _RewardHeartbeat(TrainerCallback):
        def __init__(self):
            self.reward_history = []

        def on_log(self, args, state, control, logs=None, **kwargs):
            if not logs:
                return
            r = logs.get("reward")
            if r is None:
                return
            try:
                r = float(r)
            except (TypeError, ValueError):
                return
            self.reward_history.append(r)
            step = int(getattr(state, "global_step", len(self.reward_history)))
            heartbeat("rl_step", step=step, reward=r, reward_last=self.reward_history[-8:])

    return _RewardHeartbeat()


def grpo_overrides() -> dict:
    """The GRPO recipe knobs, read off the job spec's ``[train]`` table (``TrainSpec``).
    A field left unset (None) is omitted here so the recipe default applies downstream.

    Knobs: group_size, temperature, max_tokens (completion budget), kl_penalty_coef (the KL
    beta), advantage_clip (centered-advantage clip), and thinking_length_penalty_coef
    (a per-<think>-token reward deduction). These live in ``[train]`` β€” NOT in
    ``[environment.params]``, which is forwarded verbatim to the verifiers env loader."""
    if not JOB_SPEC:
        return {}
    train = JOB_SPEC.train
    cfg = {
        "group_size": train.group_size,
        "temperature": train.temperature,
        "max_tokens": train.max_tokens,
        "kl_penalty_coef": train.kl_penalty_coef,
        "advantage_clip": train.advantage_clip,
        "thinking_length_penalty_coef": train.thinking_length_penalty_coef,
    }
    return {k: v for k, v in cfg.items() if v is not None}


def think_token_count(completion: str | None, tokenizer) -> int:
    """Number of tokens inside the completion's <think>...</think> span (0 if none).

    Used for the thinking-length reward deduction: long reasoning is penalized in
    proportion to the tokens it spent, mirroring the SDK's thinking_length_penalty_coef.
    """
    if not completion or "<think>" not in completion:
        return 0
    after = completion.split("<think>", 1)[1]
    think_text = after.split("</think>", 1)[0] if "</think>" in after else after
    if not think_text:
        return 0
    return len(tokenizer(think_text, add_special_tokens=False)["input_ids"])


def _init_adapter_model(model_id: str):
    """Base model + the ``train.init_from_adapter`` adapter loaded as a trainable
    PeftModel, or the plain ``model_id`` string + a fresh LoRA when it is unset.

    GRPO continuing an SFT adapter: TRL trains the LOADED adapter (peft_config=None)
    instead of attaching a fresh one."""
    prefix = JOB_SPEC.train.init_from_adapter if JOB_SPEC else ""
    if not prefix:
        return model_id, make_lora(model_id)
    adir = _download_adapter(prefix)
    if not adir:
        # The user explicitly asked GRPO to continue from this adapter; silently
        # falling back to a fresh base-model LoRA would spend a full paid run
        # optimizing the wrong starting point. Fail hard instead.
        raise RuntimeError(
            f"train.init_from_adapter={prefix!r} could not be downloaded from the artifact "
            "store (wrong/missing prefix or no access); refusing to silently start GRPO from "
            "the base model. Fix the adapter prefix / HF credentials, or omit "
            "init_from_adapter to train a fresh LoRA."
        )
    from peft import PeftModel
    from transformers import AutoModelForCausalLM

    print(f"[init-adapter] initializing LoRA from {prefix}")
    # 4-bit-QLoRA tier: load the frozen base in NF4 so a continued-adapter GRPO run fits
    # the same memory budget as a fresh-LoRA one (and TRL still sees Linear4bit modules ->
    # bitsandbytes vLLM rollout).
    if model_quant(model_id) == "4bit-qlora":
        _patch_peft_weight_converter_compat()
        _attn = optimal_attn_impl()  # arch-aware attention on the QLoRA path too
        # qlora_model_init_kwargs() ALREADY carries attn_implementation (via attn_impl()), so
        # override it in the dict rather than passing a 2nd attn_implementation kwarg β€” a duplicate
        # keyword raises TypeError whenever _attn is non-null (sm120 / AUTOSLM_ATTN_IMPL set).
        _mik = qlora_model_init_kwargs()
        if _attn:
            _mik["attn_implementation"] = _attn
        base = AutoModelForCausalLM.from_pretrained(
            model_id,
            trust_remote_code=True,
            **_mik,
        )
    else:
        _attn = optimal_attn_impl()
        base = AutoModelForCausalLM.from_pretrained(
            model_id,
            dtype="bfloat16",
            trust_remote_code=True,
            **({"attn_implementation": _attn} if _attn else {}),
        )
    model = PeftModel.from_pretrained(base, adir, is_trainable=True)
    return model, None


def _grpo_rmpad_enabled(attn_impl: str | None) -> bool:
    """Whether to take the GRPO remove-padding / varlen logprob path (Lever 1).

    Opt-in via AUTOSLM_GRPO_RMPAD=1 (default OFF). The varlen forward flattens the batch and
    runs FlashAttention with cu_seqlens, which ONLY exists in the FA2/FA3 kernels β€” SDPA/eager
    have no varlen entry point β€” so we require attn_implementation in {flash_attention_2,
    flash_attention_3}. Anything else (the SDPA default, eager, unset) -> skip with a warning so
    the run silently falls back to TRL's normal padded logprob path instead of mis-training.
    """
    if os.environ.get("AUTOSLM_GRPO_RMPAD") not in ("1", "true", "True"):
        return False
    if attn_impl not in ("flash_attention_2", "flash_attention_3"):
        print(
            f"[rl][rmpad] AUTOSLM_GRPO_RMPAD set but attn_implementation={attn_impl!r} is not "
            "FlashAttention (varlen/cu_seqlens needs FA2/FA3); skipping rmpad, using TRL's "
            "normal padded logprob path. Set AUTOSLM_ATTN_IMPL=flash_attention_2 to enable."
        )
        return False
    return True


def make_rmpad_grpo_trainer(GRPOTrainer):
    """Return a GRPOTrainer subclass whose per-token logprob forward is UNPADDED (Lever 1).

    Context: GRPO scores `group_size` completions per prompt whose lengths vary a lot. TRL's
    `_get_per_token_logps_and_entropies` left-pads every (prompt+completion) row to the batch max
    and runs the policy + reference forward over the full padded `[B, T]` block β€” so on a
    high-variance batch most of the attention/MLP FLOPs are spent on pad tokens. verl's
    `use_remove_padding` instead flattens all real tokens into one packed sequence and runs
    FlashAttention in varlen mode (cu_seqlens marks the per-row boundaries, so no token attends
    across rows), wasting zero compute on padding β€” ~1.5-2x on the policy forward for skewed
    rollouts, single-GPU.

    We mirror the LoRA+ `_SFT(SFTTrainer)` local-subclass pattern: override ONE method and fall
    back to `super()` on any mismatch. This is correct-by-construction + default-OFF + FA-gated +
    try/except, because getting the token->logprob mapping wrong silently corrupts the GRPO
    gradient (it would optimize the wrong logprobs against the right advantages).

    INVARIANT we preserve (verified against TRL 1.6 `_get_per_token_logps_and_entropies`): the
    method returns `(logps, entropies)` where `logps[i, j]` is the log-prob the model assigns to
    `input_ids[i, -logits_to_keep + j]` GIVEN the preceding context β€” i.e. logps is shape
    `[B, logits_to_keep]`, the prediction for the LAST `logits_to_keep` positions of row i, using
    the standard next-token shift (logits[:, :-1] predicts input_ids[:, 1:]) and
    `logits.div_(self.temperature)`. The caller multiplies this elementwise by completion_mask, so
    we MUST return EXACTLY that padded `[B, logits_to_keep]` layout β€” same dtype/device, same
    masked positions (we leave masked/pad positions at 0.0; they are zeroed by completion_mask
    downstream regardless). We do NOT touch entropies/pixel/multimodal kwargs: if ANY of those are
    requested, or batch_size chunking is requested, or shapes don't line up, we defer to super()
    so we never silently diverge from TRL's reference math on a path we didn't validate.
    """
    import torch

    class _RmpadGRPO(GRPOTrainer):  # local remove-padding / varlen subclass
        # Set True the first time we successfully fall back, so we don't spam the log per step.
        _rmpad_warned = False

        def _rmpad_fallback(self, reason, *args, **kwargs):
            if not _RmpadGRPO._rmpad_warned:
                print(f"[rl][rmpad] falling back to padded logprob path: {reason}")
                _RmpadGRPO._rmpad_warned = True
            return super()._get_per_token_logps_and_entropies(*args, **kwargs)

        def _get_per_token_logps_and_entropies(
            self,
            model,
            input_ids,
            attention_mask,
            logits_to_keep,
            batch_size=None,
            compute_entropy=False,
            **kwargs,
        ):
            # Capture the original call once so every fallback re-invokes super() with the EXACT
            # arguments TRL passed (no chance of dropping a kwarg on the deferral path).
            _args = (model, input_ids, attention_mask, logits_to_keep)
            _kw = {"batch_size": batch_size, "compute_entropy": compute_entropy, **kwargs}
            fb = lambda why: self._rmpad_fallback(why, *_args, **_kw)  # noqa: E731
            # Only handle the plain text, no-entropy, no-multimodal, single-chunk case. Anything
            # else -> defer to TRL's reference implementation (correctness over coverage).
            if compute_entropy:
                return fb("entropy requested")
            # Any multimodal / token_type kwarg present and non-None -> defer (varlen path here is
            # text-only; the VL tiers are trained text-only but TRL may still pass these through).
            if any(v is not None for v in kwargs.values()):
                return fb("multimodal/extra kwargs present")
            try:
                B, T = input_ids.shape
                if attention_mask is None or attention_mask.shape != input_ids.shape:
                    return fb("missing/mismatched attention_mask")
                # Per-row real-token lengths (GRPO left-pads prompts, so the real tokens are a
                # contiguous RIGHT-aligned span; we assert that to avoid a wrong scatter).
                seqlens = attention_mask.sum(dim=1).to(torch.int32)  # (B,)
                if int(seqlens.min()) <= int(logits_to_keep):
                    # A row with <= logits_to_keep real tokens means the completion region would
                    # spill into pad β€” outside the contract we validated. Defer.
                    return fb("row shorter than logits_to_keep")
                # Verify the left-pad assumption: for each row the real tokens must be the LAST
                # seqlen positions (mask is 0...0 1...1). If any row isn't right-aligned, the
                # flatten/scatter indices below would be wrong -> defer rather than risk it.
                idx = torch.arange(T, device=input_ids.device).unsqueeze(0).expand(B, -1)
                right_aligned = (idx >= (T - seqlens.unsqueeze(1))).int()
                if not torch.equal(right_aligned, attention_mask.int()):
                    return fb("attention_mask not left-padded (right-aligned) as expected")

                # ---- Flatten: pack every row's REAL tokens into one [1, total] sequence. ----
                flat_ids = input_ids[attention_mask.bool()].unsqueeze(0)  # (1, total)
                # cu_seqlens: prefix-sum boundaries FA varlen uses so row i's tokens only attend to
                # row i (no cross-row leakage). position_ids restart at 0 per row (RoPE per row).
                cu_seqlens = torch.zeros(B + 1, dtype=torch.int32, device=input_ids.device)
                cu_seqlens[1:] = torch.cumsum(seqlens, dim=0)
                position_ids = torch.cat(
                    [torch.arange(int(n), device=input_ids.device) for n in seqlens]
                ).unsqueeze(0)  # (1, total)

                # Run the UNPADDED forward. transformers' FA2/FA3 path reads varlen geometry from a
                # 2D position_ids that restarts per packed sequence (the documented padding-free
                # forward); we pass it WITHOUT an attention_mask so FA builds cu_seqlens from the
                # position resets. logits_to_keep is per-row, so request all logits and slice below.
                out = model(input_ids=flat_ids, position_ids=position_ids, use_cache=False)
                logits = out.logits  # (1, total, V)
                if logits.shape[1] != flat_ids.shape[1]:
                    return fb("unpadded forward returned unexpected length")
                logits = logits.squeeze(0)  # (total, V)
                logits = logits.div_(self.temperature)

                # ---- Scatter logprobs back to the padded [B, logits_to_keep] layout. ----
                # For row i (real tokens occupy flat slice [c_i, c_{i+1})), the per-token logprob
                # for predicting the LAST `logits_to_keep` tokens uses logits at the positions
                # IMMEDIATELY BEFORE each target (next-token shift). The j-th kept logprob
                # (j in [0, logits_to_keep)) targets the token at row offset (n_i - logits_to_keep + j)
                # and is read from the logit at offset (n_i - logits_to_keep + j - 1). This exactly
                # mirrors TRL's logits[:, :-1] shift + selective_log_softmax(logits, completion_ids).
                from trl.trainer.utils import selective_log_softmax

                out_logps = torch.zeros(B, logits_to_keep, dtype=logits.dtype, device=logits.device)
                starts = cu_seqlens[:-1]
                for i in range(B):
                    c = int(starts[i])
                    n = int(seqlens[i])
                    # target token offsets within the row: the last logits_to_keep tokens
                    tgt_offsets = torch.arange(n - logits_to_keep, n, device=logits.device)
                    target_ids = flat_ids[0, c + tgt_offsets]  # (logits_to_keep,)
                    # predicting logits sit one position earlier (next-token shift)
                    pred_logits = logits[c + tgt_offsets - 1]  # (logits_to_keep, V)
                    out_logps[i] = selective_log_softmax(
                        pred_logits.unsqueeze(0), target_ids.unsqueeze(0)
                    ).squeeze(0)
                return out_logps, None
            except Exception as e:  # never corrupt/kill training on the rmpad path
                return fb(f"exception in rmpad forward ({type(e).__name__}: {e})")

    return _RmpadGRPO


def run_rl():
    from datasets import Dataset
    from transformers import AutoTokenizer
    from trl import GRPOConfig, GRPOTrainer

    require_active_env()  # fail loudly (not AttributeError: NoneType) on the no-JobSpec path
    t_start = time.time()
    heartbeat("rl_start")
    # GRPO rollout strategy by env shape (trl 1.6 adds the hooks these need):
    #   * single-turn          -> TRL single-shot generation + per-completion reward (below);
    #   * tool (ToolEnv & subs:
    #     Stateful/Sandbox/Python) -> TRL drives the tool-call loop natively via
    #     GRPOTrainer(tools=...) (it parses tool calls, executes the tools, and masks the
    #     tool-result tokens itself); the reward scores the full transcript;
    #   * pure multi-turn      -> a custom rollout_func (autoslm.engine.multiturn_rollout)
    #     drives THIS env's turn loop on the colocate engine and returns the interleaved
    #     token sequence with an env_mask so only the model's tokens are trained.
    is_tool_env = getattr(ACTIVE_ENV, "is_tool_env", False)
    is_multi_turn = getattr(ACTIVE_ENV, "multi_turn", False)
    conversational = is_multi_turn  # message-list prompts (tool + pure multi-turn) vs strings
    wait_for_gpu()
    setup_perf_backends()
    model_id = JOB_SPEC.model if JOB_SPEC else RECIPE.hf_model_id
    # QLoRA tier: prefetch a pre-quantized export when one exists (~3.5x smaller), else the
    # base bf16 checkpoint (vLLM/transformers quantize it to 4-bit NF4 at load).
    quant = model_quant(model_id)
    weights_id = resolve_weights_id(model_id)
    download_seconds = prefetch_model(weights_id)
    rl = RECIPE.rl
    steps = int(os.environ.get("RL_STEPS", str(rl.num_steps)))
    # Throughput/quality knobs (env-overridable): the number of prompts optimized per step,
    # completions per prompt, and whether vLLM offloads weights between steps. Sleep mode
    # frees memory for the optimizer but reloads ~weights each step (a large per-step cost);
    # disable it (RL_VLLM_SLEEP=0) with a higher RL_VLLM_GPU_UTIL when both fit resident.
    # SDK-supplied GRPO knobs (datums parity) override the recipe; env vars still win.
    gcfg = grpo_overrides()
    _t = JOB_SPEC.train if JOB_SPEC else None
    # batch_size = prompts per optimizer step for GRPO.
    _pps_default = _t.batch_size if _t and _t.batch_size is not None else rl.prompts_per_step
    prompts_per_step = int(os.environ.get("RL_PROMPTS_PER_STEP", str(_pps_default)))
    group_size = int(os.environ.get("RL_GROUP_SIZE", gcfg.get("group_size") or rl.group_size))
    # temperature: explicit None check, NOT `or` β€” a configured 0.0 (greedy/deterministic
    # rollouts) must be honored, not fall back to the recipe sampling temperature.
    _gcfg_temp = gcfg.get("temperature")
    _temperature = float(_gcfg_temp if _gcfg_temp is not None else rl.sampling_temperature)
    _kl_beta = float(gcfg.get("kl_penalty_coef") or 0.0)
    _adv_clip = float(gcfg.get("advantage_clip") or 0.0)
    _think_penalty = float(gcfg.get("thinking_length_penalty_coef") or 0.0)
    # vLLM sleep mode offloads the rollout engine's weights between steps to free memory for the
    # optimizer, but reloading each step is a large per-step cost β€” PR #174 measured ~2-2.6x faster
    # GRPO with it OFF on models that fit. Default it by model size (same small=speed / large=memory
    # gate as gradient checkpointing): OFF for small/fitting models, ON for large. RL_VLLM_SLEEP wins.
    _sleep_env = os.environ.get("RL_VLLM_SLEEP")
    if _sleep_env is not None:
        sleep_mode = _sleep_env not in ("0", "false", "False")
    else:
        # Gate on the RESOLVED GRPO rollout context (RL_VLLM_MAX_LEN sizes the engine + KV cache),
        # not just _t.max_length: a long-context GRPO run set via RL_VLLM_MAX_LEN is memory-tight and
        # needs sleep mode even when _t.max_length is unset/small. Matches the liger-loss gate below.
        _grpo_ctx = int(
            os.environ.get("RL_VLLM_MAX_LEN") or (_t.max_length if _t and _t.max_length else 0) or 0
        )
        sleep_mode = _memory_mode(model_id, _grpo_ctx)
    # Rollout backend: colocated vLLM (fast) unless the catalog disables it for this model
    # (e.g. fused-MoE tiers whose experts bnb can't 4-bit, so a 2nd vLLM copy won't fit one
    # GPU) β€” then TRL generates with the trainer model via transformers. Env RL_USE_VLLM wins.
    from autoslm.catalog import MODELS as _CATALOG

    _info = _CATALOG.get(model_id)
    _catalog_use_vllm = _info.grpo_use_vllm if _info is not None else True
    use_vllm = os.environ.get("RL_USE_VLLM", "1" if _catalog_use_vllm else "0") not in (
        "0",
        "false",
        "False",
    )
    print(f"[rl] rollout backend: {'colocated vLLM' if use_vllm else 'transformers generation'}")
    # 4-bit fused-MoE + vLLM is IMPOSSIBLE: vLLM cannot load the bitsandbytes-packed fused MoE
    # experts (verified on B200 β€” vLLM load_fused_expert_weights raises "shape [512,1] doesn't
    # match broadcast [512,2048]" at engine init). The catalog marks such tiers grpo_use_vllm=False.
    # When an operator FORCES vLLM (RL_USE_VLLM=1) on that 4-bit tier without a vLLM-loadable AWQ/
    # GPTQ export, auto-promote the base to BF16 β€” vLLM's standard MoE loader then works and the
    # 2x bf16 copies fit a >=180 GB GPU (verified: 35B-A3B GRPO trains on a B200 at ctx
    # 1024/2048/4096). weights_id is already the bf16 base (no quant_repo), so only `quant` flips.
    # AUTOSLM_QUANT (explicit pin) and an AWQ quant_repo both opt out.
    if (
        use_vllm
        and not _catalog_use_vllm
        and quant == "4bit-qlora"
        and not quant_weights_repo(model_id)
        and os.environ.get("AUTOSLM_QUANT") is None
    ):
        print(
            "[rl] vLLM forced on a 4-bit fused-MoE tier vLLM cannot load -> auto-promoting base to "
            "bf16 (needs a >=180 GB GPU, e.g. B200). Pin AUTOSLM_QUANT=4bit-qlora to override "
            "(vLLM will then fail the MoE load), or supply an AWQ/GPTQ quant_repo."
        )
        quant = "bf16"
        # Propagate via the env too so EVERY downstream load path resolves bf16, not just this local
        # `quant`. The continued-adapter path (`_init_adapter_model` -> qlora_model_init_kwargs) and
        # `resolve_weights_id` call `model_quant()` again (re-reading the catalog's 4bit-qlora); set
        # AUTOSLM_QUANT so those return bf16 too β€” else a continued-adapter run still loads 4-bit and
        # crashes vLLM's MoE loader. (The launcher already sized a >=180GB GPU via vram.py.)
        os.environ["AUTOSLM_QUANT"] = "bf16"
    tok = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
    if tok.pad_token is None:
        tok.pad_token = tok.eos_token

    train = ACTIVE_ENV.dataset("train")
    rng = random.Random(SEED)
    rng.shuffle(train)
    if conversational:
        # Message-list prompts so the chat template applies roles + (for tool envs) the tool
        # schemas; per-turn length is managed by the tool loop / rollout_func, not a flat budget.
        prompts = [{"prompt": ACTIVE_ENV.prompt_messages(ex), "example": ex} for ex in train]
    else:
        prompts = [{"prompt": render_prompt(tok, ex), "example": ex} for ex in train]
    # The colocated vLLM engine's model length is the hard cap on prompt+completion at
    # rollout. Size it (honoring RL_VLLM_MAX_LEN) and derive the prompt budget from it so a
    # bigger engine or a smaller completion automatically admits longer prompts (rather than
    # a fixed rl.max_prompt_len that no env override could lift).
    _max_completion = int(
        os.environ.get(
            "RL_MAX_COMPLETION",
            gcfg.get("max_tokens")
            or (rl.max_completion_len_thinking if THINKING else rl.max_completion_len),
        )
    )
    # Engine context = RL_VLLM_MAX_LEN if set, else the run's [train].max_length (so a long-context
    # GRPO config sized/paid for by the allocator actually RUNS at that length), else the recipe
    # default. Without the train.max_length fallback the allocator provisions a big GPU for the long
    # context but the engine runs short β€” paying for headroom we never use.
    _train_ctx = _t.max_length if (_t and _t.max_length) else 0
    vllm_max_len = int(
        os.environ.get("RL_VLLM_MAX_LEN")
        or _train_ctx
        or max(1024, rl.max_prompt_len + _max_completion)
    )
    # The engine must fit completion + at least some prompt. If RL_VLLM_MAX_LEN is set below
    # the completion budget, no prompt can ever fit β€” fail fast here rather than passing a
    # 1-token budget that lets prompts through and then OOMs/overflows mid-rollout.
    if vllm_max_len <= _max_completion:
        raise ValueError(
            f"RL_VLLM_MAX_LEN={vllm_max_len} leaves no room for the {_max_completion}-token "
            "completion; raise RL_VLLM_MAX_LEN or lower RL_MAX_COMPLETION"
        )
    prompt_budget = vllm_max_len - _max_completion

    # TRL 1.5's GRPOConfig has no max_prompt_length and does NOT truncate prompts, so a prompt
    # that leaves no room for the completion within the engine length would fail mid-rollout
    # AFTER the paid worker is provisioned. Drop prompts that don't fit the budget up front.
    # render_prompt returns an apply_chat_template(tokenize=False) string that already carries
    # the special tokens, so tokenize with add_special_tokens=False (the default re-adds
    # BOS/EOS and over-counts).
    # Drop prompts that leave no room for the completion within the engine length β€” applies to
    # BOTH single-turn (string prompts) and conversational (message-list) prompts, so a tool /
    # multi-turn rollout can't overflow the colocate engine mid-generation. Conversational
    # prompts are length-checked via the chat template (with the generation prompt).
    # Tool schemas TRL injects into the prompt for native tools= GRPO β€” include them in the
    # budget for a tool env so a prompt isn't undercounted at filter time vs. rollout time.
    _oai_tools = (
        getattr(getattr(ACTIVE_ENV, "_env", None), "oai_tools", None) if is_tool_env else None
    )

    def _prompt_tokens(p) -> int:
        if conversational:
            # Render to text then tokenize β€” the SAME path the rollout uses β€” so the filter
            # count matches the rollout's count (avoids a tokenize=True vs text mismatch).
            kw = {"tools": _oai_tools} if _oai_tools else {}
            try:
                text = tok.apply_chat_template(
                    p["prompt"],
                    add_generation_prompt=True,
                    tokenize=False,
                    enable_thinking=THINKING,
                    **kw,
                )
            except Exception as exc:
                # Fail fast WITH context: a tokenizer/template incompatibility would render every
                # prompt uncountable and otherwise surface as a misleading "all prompts exceed
                # budget" β€” raise so the model/template can be fixed before a paid run trains on
                # a degenerate dataset.
                raise RuntimeError(
                    "failed to render a conversational prompt with this model's chat template "
                    f"(fix the model/template or the env's prompts): {exc}"
                ) from exc
            return len(tok(text, add_special_tokens=False).input_ids)
        return len(tok(p["prompt"], add_special_tokens=False).input_ids)

    kept = [p for p in prompts if 0 < _prompt_tokens(p) <= prompt_budget]
    if len(kept) < len(prompts):
        print(
            f"[rl] dropped {len(prompts) - len(kept)} prompts over the {prompt_budget}-token "
            f"prompt budget (engine {vllm_max_len} - completion {_max_completion})"
        )
    if not kept:
        raise ValueError(
            f"every training prompt exceeds the {prompt_budget}-token prompt budget (engine "
            f"{vllm_max_len} - completion {_max_completion}); raise RL_VLLM_MAX_LEN, lower "
            "RL_MAX_COMPLETION, or shorten the environment's prompts"
        )
    prompts = kept
    ds = Dataset.from_list(prompts)

    def reward_fn(completions, **kwargs):
        # rollout_func (pure multi-turn) path: the per-rollout reward is computed by the env
        # during the rollout and forwarded as the "reward" extra field β€” pass it through.
        if kwargs.get("reward") is not None:
            return [float(r) for r in kwargs["reward"]]
        # Score the <think>-stripped text (graded_text), then β€” datums parity β€” deduct
        # the thinking-length penalty computed from the RAW completion's <think> span.
        examples = kwargs.get("example")
        rewards = []
        for comp, ex in zip(completions, examples, strict=False):
            if isinstance(comp, list):
                # Tool / conversational transcript (TRL passes a list of messages): score the
                # whole transcript via the rubric (no <think> stripping β€” multi-turn content).
                rewards.append(ACTIVE_ENV.reward_from_messages(comp, ex))
                continue
            r = ACTIVE_ENV.reward(graded_text(comp), ex)
            if _think_penalty > 0 and THINKING:
                r -= _think_penalty * think_token_count(comp, tok)
            rewards.append(r)
        return rewards

    # TRL's per_device_train_batch_size counts COMPLETIONS, not prompts. Size grad-accum so
    # the global completion batch = prompts_per_step * group_size, i.e. each optimizer step
    # actually optimizes `prompts_per_step` prompts. The per-device *completion* micro-batch
    # is the VRAM knob (thinking-aware; see rl_per_device_comps).
    per_device_comps = rl_per_device_comps(_max_completion)
    batching = compute_grpo_batching(prompts_per_step, group_size, per_device_comps)
    if not batching["divisible_by_group"]:
        print("WARN: generation batch not divisible by group size; check RL_PER_DEVICE_PROMPTS")
    print(
        f"[rl] GRPO batching: per_device={batching['per_device_train_batch_size']} "
        f"grad_accum={batching['gradient_accumulation_steps']} "
        f"generations/step={batching['generations_per_step']} "
        f"unique_prompts/step={batching['unique_prompts_per_step']} "
        f"(target prompts/step={prompts_per_step}, group={group_size}, sleep={sleep_mode})"
    )
    out_dir = f"/tmp/rl_seed{SEED}"
    resume_ckpt = hf_resume_checkpoint()

    grpo_kwargs = {
        "output_dir": out_dir,
        "learning_rate": (
            _t.learning_rate if _t and _t.learning_rate is not None else rl.learning_rate
        ),
        "per_device_train_batch_size": batching["per_device_train_batch_size"],
        "gradient_accumulation_steps": batching["gradient_accumulation_steps"],
        "num_generations": group_size,
        # NB: GRPOConfig has no max_prompt_length field (TRL 1.5) and does not truncate
        # prompts; the dataset is pre-filtered above to prompts that fit prompt_budget
        # (vllm_max_len - completion), so every prompt fits the engine sized here.
        "max_completion_length": _max_completion,
        "max_steps": steps,
        "temperature": _temperature,
        "top_p": rl.sampling_top_p,
        "use_vllm": use_vllm,
        "logging_steps": 1,
        "save_steps": int(
            os.environ.get(
                "RL_SAVE_STEPS", str(_t.save_every if _t and _t.save_every is not None else 20)
            )
        ),
        "save_total_limit": 1,
        # Memory-light checkpoints: adapter only, no optimizer/scheduler/RNG state -> no
        # serialization spike at save (the save-step OOM guard).
        "save_only_model": True,
        "bf16": True,
        "report_to": wandb_report_to(),  # W&B when WANDB_API_KEY present (restored post-autoslm-migration)
        "run_name": wandb_run_name(),
        "seed": SEED,
        "gradient_checkpointing": grad_checkpointing_on(model_id, vllm_max_len),
        # Pin a stable, well-conditioned GRPO recipe instead of inheriting TRL's defaults
        # (which on a short run suppress the lift): constant LR (TRL default 'linear' decays
        # to 0 over the run), advantages centered by group mean only (no std scaling, which
        # biases by difficulty/length β€” matches datums.centered_advantages), and no
        # length-normalized loss. beta is the KL-to-reference coef (datums kl_masks ->
        # kl_penalty_coef).
        "lr_scheduler_type": "constant",
        "warmup_ratio": 0.0,
        "beta": _kl_beta,
        "scale_rewards": "none",
        "loss_type": "dr_grpo",
        # Optimizer: colocated GRPO is memory-tight (trainer + vLLM share one GPU), so default to
        # 8-bit paged AdamW (int8 state paged to host RAM -> fits a smaller GPU). AUTOSLM_OPTIM
        # overrides; AUTOSLM_FUSED_OPTIM=0 -> plain adamw_torch.
        "optim": fused_optim_name(memory_default=True),
    }
    # Liger fused GRPO loss: fuses the lm_head + per-token logprob so the fp32
    # [batch, seq, ~152k vocab] logits never materialize β€” the documented GRPO OOM driver.
    # TRL 1.6's GRPOConfig flag is `use_liger_kernel` (NOT `use_liger_loss`, which doesn't
    # exist in 1.6). Default on for GPU (RL_LIGER=0 to disable). Lets RL_PER_DEVICE_PROMPTS rise.
    if liger_on("RL_LIGER", default_on=_memory_mode(model_id, vllm_max_len)):
        grpo_kwargs["use_liger_kernel"] = True
        print("[rl] liger fused GRPO loss enabled")
    if use_vllm:
        # Colocate shares one GPU between the policy model and the vLLM rollout engine.
        # vllm_max_model_length bounds the KV cache to what GRPO needs (else vLLM sizes for
        # the model's FULL context and won't start on a consumer GPU). RL_VLLM_GPU_UTIL
        # sizes vLLM's pool; RL_VLLM_SLEEP offloads its weights between steps.
        grpo_kwargs.update(
            vllm_mode="colocate",
            vllm_max_model_length=vllm_max_len,
            vllm_gpu_memory_utilization=float(os.environ.get("RL_VLLM_GPU_UTIL", "0.45")),
            vllm_enable_sleep_mode=sleep_mode,
        )
        # Extra rollout-memory savers, applied ONLY if this TRL exposes the field (so an
        # older TRL never crashes on an unknown kwarg) and the run opts in:
        #   RL_VLLM_KV_FP8=1     -> fp8 KV cache, ~halves the rollout KV pool. OFF by default
        #                          because Ampere (A100) has no native fp8; enable on
        #                          Ada/Hopper/Blackwell (Pro 6000 WK, H200) for a free ~2x KV.
        #   RL_VLLM_ENFORCE_EAGER=1 -> skip CUDA-graph capture (saves graph memory, a little
        #                          slower) β€” useful to squeeze a tight colocate fit.
        _grpo_fields = set(getattr(GRPOConfig, "__dataclass_fields__", {}))
        # GPU-SPECIFIC: fp8 KV cache only where the silicon has native fp8 (compute
        # capability >= 8.9: Ada / Hopper / Blackwell). RL_VLLM_KV_FP8="auto" (default)
        # arch-gates it; "1"/"0" force. Ampere (A100/A5000/3090, sm80) lacks fp8, so it
        # stays fp16 there (forcing it on would error / silently emulate).
        _kv_fp8 = os.environ.get("RL_VLLM_KV_FP8", "auto")
        if _kv_fp8 == "auto":
            try:
                import torch as _torch

                _want_fp8 = _torch.cuda.get_device_capability() >= (8, 9)
            except Exception:
                _want_fp8 = False
        else:
            _want_fp8 = _kv_fp8 not in ("0", "false", "False")
        if _want_fp8:
            for _f in ("vllm_kv_cache_dtype", "kv_cache_dtype"):
                if _f in _grpo_fields:
                    grpo_kwargs[_f] = "fp8"
                    print(f"[rl] fp8 KV cache (arch-gated native fp8, {_f})")
                    break
        if os.environ.get("RL_VLLM_ENFORCE_EAGER", "0") not in ("0", "false", "False"):
            for _f in ("vllm_enforce_eager", "enforce_eager"):
                if _f in _grpo_fields:
                    grpo_kwargs[_f] = True
                    print(f"[rl] vLLM enforce_eager enabled ({_f})")
                    break

        # vLLM rollout throughput knobs (verl-validated for GRPO colocate; PR #174). Each is
        # feature-detected against GRPOConfig so an older TRL that lacks the field is silently
        # skipped (it would reject an unknown kwarg otherwise).
        #  - PREFIX CACHING (default ON): in GRPO every group of `num_generations` rollouts shares
        #    the SAME prompt prefix, so caching the prompt KV computes it once and reuses it across
        #    the group β€” cuts prompt-prefill cost by ~(n-1)/n per step. The dominant rollout win on
        #    one GPU. RL_VLLM_PREFIX_CACHE=0 disables.
        #  - CHUNKED PREFILL (default ON): interleaves prefill with decode so a long prompt doesn't
        #    stall the batch; smooths colocate latency. RL_VLLM_CHUNKED_PREFILL=0 disables.
        #  - MAX_NUM_BATCHED_TOKENS (RL_VLLM_MAX_BATCHED_TOKENS): vLLM scheduler token budget; verl
        #    defaults 8192. Only applied when explicitly set (vLLM auto-sizes a sane default).
        def _set_vllm_field(names, value, label):
            for _f in names:
                if _f in _grpo_fields:
                    grpo_kwargs[_f] = value
                    print(f"[rl] {label} ({_f}={value})")
                    return True
            return False

        if os.environ.get("RL_VLLM_PREFIX_CACHE", "1") not in ("0", "false", "False"):
            _set_vllm_field(
                ("vllm_enable_prefix_caching", "enable_prefix_caching"),
                True,
                "vLLM prefix caching (shared GRPO prompt KV reuse)",
            )
        if os.environ.get("RL_VLLM_CHUNKED_PREFILL", "1") not in ("0", "false", "False"):
            _set_vllm_field(
                ("vllm_enable_chunked_prefill", "enable_chunked_prefill"),
                True,
                "vLLM chunked prefill",
            )
        _mbt = os.environ.get("RL_VLLM_MAX_BATCHED_TOKENS")
        if _mbt:
            _set_vllm_field(
                ("vllm_max_num_batched_tokens", "max_num_batched_tokens"),
                int(_mbt),
                "vLLM max_num_batched_tokens",
            )
        #  - CUDAGRAPH MODE (default FULL_AND_PIECEWISE): verl explicitly sets this rollout
        #    cudagraph mode (full-graph decode + piecewise fallback) rather than vLLM's implicit
        #    default; faster decode than PIECEWISE-only. Only applied if THIS TRL exposes a vLLM
        #    compilation-config passthrough (most don't β€” then it's a silent no-op; vLLM auto-picks
        #    a mode). RL_VLLM_CUDAGRAPH_MODE overrides; ="" / "0" disables the override.
        _cg = os.environ.get("RL_VLLM_CUDAGRAPH_MODE", "FULL_AND_PIECEWISE")
        if _cg not in ("", "0", "false", "False"):
            for _f in ("vllm_compilation_config", "compilation_config"):
                if _f in _grpo_fields:
                    grpo_kwargs[_f] = {"cudagraph_mode": _cg}
                    print(f"[rl] vLLM {_f}={{'cudagraph_mode': {_cg!r}}} (verl rollout default)")
                    break
    # Adapter init: continue training the SFT adapter (peft_config=None, model is the
    # loaded PeftModel) when train.init_from_adapter is set, else a fresh LoRA on the
    # string model id (model_init_kwargs forces bf16 β€” TRL string-loading can fall back
    # to fp32 and double VRAM).
    init_model, init_peft = _init_adapter_model(model_id)
    if init_peft is not None:
        # Fresh LoRA: TRL loads the string model id with these kwargs, then attaches the
        # adapter. For the 4-bit-QLoRA tier load the base in NF4 β€” TRL detects the
        # bnb.Linear4bit modules and brings up its colocated vLLM rollout engine with
        # quantization="bitsandbytes" (so a 36B MoE fits an 80 GB GPU in 4-bit on both the
        # trainer and rollout sides). Otherwise force bf16 (TRL string-loading can fall
        # back to fp32 and double VRAM).
        _attn = optimal_attn_impl()  # arch-aware FlashAttention (Kernels Hub) / SDPA
        if quant == "4bit-qlora":
            _patch_peft_weight_converter_compat()  # MoE adapter (re)load compatibility
            grpo_kwargs["model_init_kwargs"] = qlora_model_init_kwargs(
                prequantized=weights_id != model_id
            )
            _vllm_note = "; vLLM rollout -> bitsandbytes" if use_vllm else ""
            print(f"[rl] loading {model_id} in 4-bit (QLoRA tier){_vllm_note}")
        else:
            grpo_kwargs["model_init_kwargs"] = {"dtype": "bfloat16"}
        if _attn:
            grpo_kwargs["model_init_kwargs"]["attn_implementation"] = _attn
    else:
        _attn = optimal_attn_impl()
    # stop_sequences: TRL forwards generation_kwargs to the (vLLM) sampler, whose
    # SamplingParams.stop truncates each rollout at the requested delimiter β€” so the reward
    # sees the same completion the config intends, instead of generating to max_completion.
    if _t and _t.stop_sequences:
        grpo_kwargs["generation_kwargs"] = {"stop": list(_t.stop_sequences)}
    # advantage_clip>0 is the datums centered-advantage clamp; TRL has no advantage-value
    # clip knob (it clips the importance ratio), so honor the default (clip off ==
    # centered) and surface a note when a config asks for an explicit clamp.
    if _adv_clip > 0:
        print(f"[rl] advantage_clip={_adv_clip} recorded; TRL centers advantages (no value clip)")
    # Research-backed throughput/stability knobs, feature-detected so an older TRL that lacks
    # the field is simply skipped (GRPOConfig would reject an unknown kwarg otherwise):
    #  - RL_NUM_ITERATIONS (ΞΌ): reuse each EXPENSIVE generation batch for ΞΌ optimizer steps.
    #    Generation dominates GRPO wall-clock on one GPU, so ΞΌ>1 is the single biggest speed
    #    lever (mu-x fewer rollouts per update); mu>1 activates TRL's PPO clipped surrogate, kept
    #    safe by the default importance-sampling correction. (arXiv 2402.03300 / TRL docs.)
    #  - RL_IMPORTANCE_SAMPLING_LEVEL=sequence -> GSPO: sequence-level IS ratio (lower variance,
    #    notably more stable for MoE RL; credited in Qwen3). (arXiv 2507.18071.)
    import dataclasses as _dc

    _grpo_fields = {f.name for f in _dc.fields(GRPOConfig)}
    # DEFAULT 2 (measured 1.38x faster; mu=4 -> 1.66x): generation dominates GRPO wall-clock, so
    # reusing each rollout batch for 2 optimizer steps is the cheapest large speedup. mu>=2 is the
    # standard GRPO config (TRL/DAPO/GRPO papers) and TRL's importance-sampling correction (on by
    # default) keeps the off-policy step stable. RL_NUM_ITERATIONS=1 restores strict on-policy.
    _num_iter = int(os.environ.get("RL_NUM_ITERATIONS", "2") or "2")
    if _num_iter > 1 and "num_iterations" in _grpo_fields:
        grpo_kwargs["num_iterations"] = _num_iter
        print(
            f"[rl] rollout amortization: num_iterations={_num_iter} (reuse each generation batch)"
        )
    _is_level = os.environ.get("RL_IMPORTANCE_SAMPLING_LEVEL")
    if _is_level in ("token", "sequence") and "importance_sampling_level" in _grpo_fields:
        grpo_kwargs["importance_sampling_level"] = _is_level
        print(
            f"[rl] importance_sampling_level={_is_level}"
            + (" (GSPO)" if _is_level == "sequence" else "")
        )
    # --- Transferable GRPO A/B levers (cross-framework scan: verl/DAPO/ROLL/Lite-PPO). All
    # feature-detected against the installed TRL GRPOConfig and env-gated (default off -> no
    # behavior change); documented at the framework-scan in gpu-bench/RESEARCH_FINDINGS.md.
    #  - RL_SCALE_REWARDS: ROLL/Lite-PPO advantage normalization. Our default is "none" (Dr.GRPO);
    #    "batch" = group-mean/batch-std (arXiv 2508.08221, more robust on small/homogeneous groups).
    _scale = os.environ.get("RL_SCALE_REWARDS")
    if _scale and "scale_rewards" in _grpo_fields:
        grpo_kwargs["scale_rewards"] = _scale
        print(f"[rl] scale_rewards={_scale}")
    #  - RL_EPSILON_HIGH: DAPO "clip-higher" β€” asymmetric PPO upper clip gives low-prob tokens room
    #    and prevents entropy collapse (distinct from advantage_clip). Typical 0.28.
    _eps_hi = _env_float("RL_EPSILON_HIGH")
    if _eps_hi is not None and "epsilon_high" in _grpo_fields:
        grpo_kwargs["epsilon_high"] = _eps_hi
        print(f"[rl] epsilon_high={_eps_hi} (DAPO clip-higher)")
    #  - RL_TOP_ENTROPY_QUANTILE: train only on the highest-entropy "forking" tokens (~20% carry
    #    most of the signal) -> less backward compute, sometimes faster convergence. <1.0 = on.
    _teq = _env_float("RL_TOP_ENTROPY_QUANTILE")
    if _teq is not None and "top_entropy_quantile" in _grpo_fields:
        grpo_kwargs["top_entropy_quantile"] = _teq
        print(f"[rl] top_entropy_quantile={_teq} (train high-entropy tokens only)")
    #  - RL_MASK_TRUNCATED: DAPO overlong-filtering β€” truncated completions inject biased gradient;
    #    mask them out. Worth it when completions/clipped_ratio is non-trivial.
    if (
        os.environ.get("RL_MASK_TRUNCATED") in ("1", "true", "True")
        and "mask_truncated_completions" in _grpo_fields
    ):
        grpo_kwargs["mask_truncated_completions"] = True
        print("[rl] mask_truncated_completions=True (DAPO overlong filtering)")
    cfg = GRPOConfig(**grpo_kwargs)
    setup_seconds = time.time() - t_start
    heartbeat("rl_train_start", setup_seconds=setup_seconds)

    # VL checkpoints (Qwen3.5/3.6) train text-only: make TRL's colocated rollout
    # engine skip the vision tower (VRAM + 5090 PTX-compat; see the patch docstring).
    # Only relevant when vLLM drives rollouts; transformers generation uses the trainer
    # model (already text-only via the LoRA target/exclude config).
    if use_vllm:
        patch_vllm_language_model_only(model_id)
    hb_cb = make_reward_heartbeat_callback()
    # Multi-turn / tool wiring (trl 1.6): tool envs hand TRL the tool callables so it runs the
    # tool-call loop natively; pure multi-turn envs hand TRL a rollout_func that drives the
    # env's own turn loop on the colocate engine (env_mask masks the non-model tokens).
    extra_trainer_kwargs: dict = {}
    tools = ACTIVE_ENV.tools() if is_tool_env else []
    # A tool env exposing NO tools would silently degrade to single-shot under tools=[]; drive
    # it through the rollout_func turn loop instead so it isn't mis-trained as single-turn.
    if is_tool_env and not tools:
        print("[rl][warn] tool env exposes no tools β€” using the multi-turn rollout_func path")
    use_rollout_func = is_multi_turn and not (is_tool_env and tools)
    require_vllm_for_rollout_func(use_rollout_func, use_vllm, model_id)
    if is_tool_env and tools:
        extra_trainer_kwargs["tools"] = tools
        print(f"[rl] tool env: handing {len(tools)} tool(s) to TRL's native tool loop")
    if use_rollout_func:
        from autoslm.engine.multiturn_rollout import (
            build_examples_index,
            build_rollout_func,
            index_collisions,
        )

        examples_by_key = build_examples_index(train, ACTIVE_ENV.prompt_messages)
        ncol = index_collisions(train, ACTIVE_ENV.prompt_messages)
        if ncol:
            print(
                f"[rl][warn] {ncol} duplicate prompt(s) collide in the reward index; the shared "
                "prompt scores against the last example's answer/info"
            )
        extra_trainer_kwargs["rollout_func"] = build_rollout_func(
            active_env=ACTIVE_ENV,
            tok=tok,
            examples_by_key=examples_by_key,
            max_completion=_max_completion,
            max_turns=getattr(ACTIVE_ENV, "max_turns", 10),
            temperature=_temperature,
            top_p=rl.sampling_top_p,
            stop=(list(_t.stop_sequences) if _t and _t.stop_sequences else None),
            thinking=THINKING,
            engine_max_len=vllm_max_len,
        )
        print("[rl] multi-turn env: driving the turn loop via rollout_func")
    # Lever 1 (opt-in, default OFF): GRPO remove-padding / varlen logprob forward. Only when
    # AUTOSLM_GRPO_RMPAD=1 AND the run is on FlashAttention (varlen needs FA2/FA3) β€” otherwise
    # _grpo_rmpad_enabled prints a warning and we keep the stock GRPOTrainer. Liger fuses the
    # logprob+lm_head itself, so don't layer rmpad on top of it (they patch the same forward).
    _Trainer = GRPOTrainer
    if _grpo_rmpad_enabled(_attn):
        if grpo_kwargs.get("use_liger_kernel"):
            print(
                "[rl][rmpad] AUTOSLM_GRPO_RMPAD ignored: Liger fused GRPO loss is enabled "
                "(set RL_LIGER=0 to use rmpad instead)"
            )
        else:
            try:
                _Trainer = make_rmpad_grpo_trainer(GRPOTrainer)
                print("[rl] rmpad varlen logprob forward enabled (AUTOSLM_GRPO_RMPAD, FA varlen)")
            except Exception as e:  # never block training on the rmpad wiring
                print("[rl][rmpad] subclass build failed, using stock GRPOTrainer:", e)
                _Trainer = GRPOTrainer
    trainer = _Trainer(
        model=init_model,
        args=cfg,
        train_dataset=ds,
        reward_funcs=reward_fn,
        peft_config=init_peft,
        processing_class=tok,
        callbacks=[hb_cb, make_checkpoint_upload_callback()],
        **extra_trainer_kwargs,
    )
    from autoslm.engine.triton_kernels import install_custom_rmsnorm

    install_custom_rmsnorm()  # opt-in fused Triton RMSNorm (GRPO too); self-tests, eager fallback
    maybe_regional_compile(
        trainer.model, "rl"
    )  # opt-in regional torch.compile (Lever 2; default off)
    t_train = time.time()
    with _sdpa_cudnn_ctx(_attn):  # force cuDNN SDPA on sm120 (no-op otherwise)
        trainer.train(resume_from_checkpoint=resume_ckpt)
    train_wall = time.time() - t_train
    reward_history = list(getattr(hb_cb, "reward_history", []))

    adapter_dir = f"{out_dir}/adapter"
    trainer.model.save_pretrained(adapter_dir)
    tok.save_pretrained(adapter_dir)
    hf_upload_folder(adapter_dir, "adapter", required=True)
    heartbeat("rl_trained", train_wall=train_wall)

    # Upper bound on generated tokens: completions actually optimized (the intended
    # prompts_per_step after the batch fix) x the max completion length. Over-counts (most
    # completions are shorter); reported as an upper bound, used only for a rough throughput.
    gen_tokens = steps * batching["unique_prompts_per_step"] * group_size * _max_completion
    write_train_meta(
        phase="rl",
        adapter_dir=adapter_dir,
        model_id=model_id,
        train_wall=train_wall,
        setup_seconds=setup_seconds,
        train_tokens=0,
        generated_tokens=gen_tokens,
        notes={
            "steps": steps,
            "resumed": bool(resume_ckpt),
            "download_seconds": download_seconds,
            "hf_transfer": os.environ.get("HF_HUB_ENABLE_HF_TRANSFER", ""),
            "reward_history": reward_history,
            "loss_curve": _metric_curve(trainer, "loss"),
            **wandb_run_info(),
            "gen_tokens_is_upper_bound": True,
            "thinking": THINKING,
            "max_completion_len": _max_completion,
            "prompts_per_step": batching["unique_prompts_per_step"],
            "generations_per_step": batching["generations_per_step"],
            "group_size": group_size,
            "per_device_train_batch_size": batching["per_device_train_batch_size"],
            "gradient_accumulation_steps": batching["gradient_accumulation_steps"],
            "grpo_recipe": {
                "lr_scheduler": "constant",
                "beta": _kl_beta,
                "scale_rewards": "none",
                "loss_type": "dr_grpo",
                "temperature": _temperature,
                "advantage_clip": _adv_clip,
                "thinking_length_penalty_coef": _think_penalty,
                "init_from_adapter": JOB_SPEC.train.init_from_adapter if JOB_SPEC else "",
            },
        },
    )
    free_gpu(trainer)


# ---------------------------------------------------------------------------
# Completion: train phase writes metrics.json + the DONE sentinel (see _finalize).
# ---------------------------------------------------------------------------
def gpu_diagnostics() -> dict:
    """Collect CUDA/driver diagnostics to pin down GPU init failures on rented nodes."""
    diag = {}
    try:
        import torch

        diag["torch"] = torch.__version__
        diag["torch_cuda"] = torch.version.cuda
        diag["cuda_available"] = torch.cuda.is_available()
        try:
            diag["device_count"] = torch.cuda.device_count()
            diag["device_name"] = torch.cuda.get_device_name(0)
        except Exception as e:
            diag["device_query_err"] = str(e)[:160]
    except Exception as e:
        diag["torch_import_err"] = str(e)[:160]
    try:
        import subprocess

        out = subprocess.run(
            ["nvidia-smi", "--query-gpu=driver_version,name,memory.total", "--format=csv,noheader"],
            capture_output=True,
            text=True,
            timeout=20,
        )
        diag["nvidia_smi"] = (out.stdout or out.stderr).strip()[:200]
    except Exception as e:
        diag["nvidia_smi_err"] = str(e)[:160]
    return diag


def wait_for_gpu(max_tries=12, sleep_s=10):
    """Rented nodes sometimes report 'CUDA device not ready' transiently at startup.
    Poll a trivial CUDA op until it succeeds before doing real work; raise if never ready."""
    import time as _t

    last = None
    for i in range(max_tries):
        try:
            import torch

            if torch.cuda.is_available():
                # Force an actual kernel launch (alloc + add) to confirm the GPU is live.
                _ = torch.zeros(8, device="cuda") + 1
                torch.cuda.synchronize()
                print(f"GPU ready after {i} retries: {torch.cuda.get_device_name(0)}")
                return True
            last = "cuda not available"
        except Exception as e:
            last = str(e)[:160]
        print(f"GPU not ready (try {i + 1}/{max_tries}): {last}; sleeping {sleep_s}s")
        _t.sleep(sleep_s)
    raise RuntimeError(f"GPU never became ready after {max_tries} tries: {last}")


def free_gpu(trainer=None):
    try:
        import gc

        import torch

        try:
            if trainer is not None and hasattr(trainer, "model"):
                trainer.model = None
        except Exception:
            # Best-effort VRAM release before gc; any failure here is non-fatal cleanup.
            pass
        gc.collect()
        if torch.cuda.is_available():
            torch.cuda.empty_cache()
    except Exception as e:
        print("free_gpu warn:", e)


def _metric_curve(trainer, key: str, cap: int = 400) -> list:
    """The logged values of `key` (e.g. 'loss' or 'reward') from the trainer's log history,
    rounded + capped. Lets metrics.json carry the convergence/reward curve for an A/B without
    relying on a checkpoint's trainer_state.json (only written on save_steps) or the console
    (only uploaded on failure). Never raises."""
    try:
        vals = [round(float(h[key]), 4) for h in trainer.state.log_history if key in h]
        return vals[:cap]
    except Exception:
        return []


def write_train_meta(
    phase, adapter_dir, model_id, train_wall, setup_seconds, train_tokens, generated_tokens, notes
):
    meta = {
        "phase": phase,
        "adapter_dir": adapter_dir,
        "model_id": model_id,
        "train_wall": train_wall,
        "setup_seconds": setup_seconds,
        "train_tokens": train_tokens,
        "generated_tokens": generated_tokens,
        "notes": notes or {},
    }
    with open("/tmp/train_meta.json", "w") as f:
        json.dump(meta, f)
    hf_upload_file("/tmp/train_meta.json", "train_meta.json")
    heartbeat(
        f"{phase}_train_done",
        **{k: meta[k] for k in ("train_wall", "train_tokens", "generated_tokens")},
    )
    # Finalize directly from the training phase: build the run-metrics record (training
    # metrics only β€” loss/reward are streamed by the trainer; reward_history is in notes)
    # and write the completion sentinel. There is no separate eval phase.
    m = RunMetrics(
        # Substrate the worker actually ran on. Each provider's launcher sets AUTOSLM_ARM
        # in the worker env (runpod -> "runpod", vast -> "vast"); default to "runpod" only
        # when unset so the persisted metrics correctly attribute the compute backend.
        arm=os.environ.get("AUTOSLM_ARM", "runpod"),
        phase=phase,
        seed=SEED,
        model_id=model_id,
        wall_seconds=train_wall,
        setup_seconds=setup_seconds,
        train_throughput_toks_per_s=(
            (generated_tokens or train_tokens) / train_wall if train_wall else 0.0
        ),
        train_tokens=train_tokens,
        generated_tokens=generated_tokens,
        notes={
            **(notes or {}),
            "renderer": "autoslm_env",
            "thinking": THINKING,
            "train_wall": train_wall,
            "model_id": model_id,
            "environment": ACTIVE_ENV.id,
            "job_spec": JOB_SPEC.to_dict() if JOB_SPEC else None,
        },
    )
    _finalize(m, adapter_dir)


def _download_adapter(adapter_prefix: str | None) -> str | None:
    if not (adapter_prefix and HF_REPO):
        return None
    from huggingface_hub import snapshot_download

    snapshot_download(
        repo_id=HF_REPO,
        repo_type="dataset",
        allow_patterns=[f"{adapter_prefix}/adapter/*"],
        local_dir="/tmp/evdl",
        token=os.environ.get("HUGGINGFACE_TOKEN"),
    )
    adir = os.path.join("/tmp/evdl", adapter_prefix, "adapter")
    return adir if os.path.isdir(adir) else None


def _finalize(metrics: RunMetrics, adapter_dir: str):
    metrics.save("/tmp/metrics.json")
    # Required: a swallowed upload would make the control plane fail/retry a finished run.
    hf_upload_file("/tmp/metrics.json", "metrics.json", required=True)
    # DONE sentinel so the controller knows it's safe to tear down
    with open("/tmp/DONE", "w") as f:
        f.write(str(time.time()))
    hf_upload_file("/tmp/DONE", "DONE", required=True)
    heartbeat("done")
    print("NODE DONE:", metrics.to_json())


def _drop_fla_on_hopper() -> None:
    """Remove flash-linear-attention when running on a Hopper GPU (sm90, H100/H200).

    fla's gated chunk_bwd Triton kernel is miscomputed on Hopper with Triton>=3.4 and
    HARD-RAISES (fla #640), so every gated-delta (Qwen3.5/3.6 family) GRPO backward crashes.
    The worker base image BAKES fla in, and per-run installs (extra_pip / `prime env install`)
    can pull it back, so the only reliable place to drop it is HERE: in the worker process,
    after all installs and BEFORE any model import. transformers then uses the correct
    pure-PyTorch delta rule (2-3x slower but it RUNS). Runs on BOTH substrates (RunPod and
    Vast both exec this module). importlib caches are invalidated so the later
    is_fla_available() probe sees it gone. Ampere/Ada/Blackwell keep fla for the speedup.
    """
    import importlib
    import importlib.util
    import shutil
    import subprocess

    try:
        import torch

        if not (torch.cuda.is_available() and torch.cuda.get_device_capability()[0] == 9):
            return  # not Hopper: fla's Triton kernel is correct here, keep it.
    except Exception:
        return

    # Opt-in tilelang strategy: keep fla and let it use the tilelang backend (the fix fla
    # prescribes on Hopper #640), which stays memory-efficient so long-context 35B GRPO fits.
    # tilelang ships a manylinux wheel, so install it HERE at worker runtime (Flash caches its
    # per-GPU dep env and won't pick up a newly-added dep, so resolve_worker_deps isn't enough).
    if os.environ.get("AUTOSLM_HOPPER_TILELANG", "0") not in ("0", "false", "False", ""):
        if importlib.util.find_spec("tilelang") is None:
            subprocess.run([sys.executable, "-m", "pip", "install", "tilelang"], check=False)
            # Pin apache-tvm-ffi==0.1.11: a bare tilelang install pulls 0.1.12, which
            # double-registers an FFI type vs tilelang's bundled v0.1.11 and aborts
            # `import tilelang` (tilelang #2367). Pin last so it wins the resolve.
            subprocess.run(
                [sys.executable, "-m", "pip", "install", "apache-tvm-ffi==0.1.11"], check=False
            )
            importlib.invalidate_caches()
        if importlib.util.find_spec("tilelang") is not None:
            print(
                "[hopper] tilelang present -> keeping fla (memory-efficient delta rule)", flush=True
            )
            return
        print("[hopper] tilelang install failed -> falling back to dropping fla", flush=True)

    if importlib.util.find_spec("fla") is None:
        return
    # pip first (clears metadata) β€” but `pip uninstall` can report success yet LEAVE the package
    # directory (incomplete RECORD / non-pip base-image install) AND there can be >1 copy on
    # sys.path, so the import still resolves. So ALSO delete every `fla` package dir from disk,
    # looping until find_spec is clean (each removal can expose another copy further down path).
    subprocess.run(
        [sys.executable, "-m", "pip", "uninstall", "-y", "flash-linear-attention"], check=False
    )
    for _ in range(6):
        importlib.invalidate_caches()
        spec = importlib.util.find_spec("fla")
        if spec is None:
            break
        locs = list(spec.submodule_search_locations or [])
        if spec.origin and os.path.isfile(spec.origin):
            locs.append(os.path.dirname(spec.origin))
        removed = False
        for loc in locs:
            if loc and os.path.basename(loc.rstrip("/")) == "fla":
                shutil.rmtree(loc, ignore_errors=True)
                removed = True
        if not removed:
            break
    importlib.invalidate_caches()
    still = importlib.util.find_spec("fla") is not None
    print(
        f"[hopper] fla removed (still_importable={still}) -> "
        f"{'WARNING fla remains' if still else 'pure-PyTorch delta rule'} (fla #640)",
        flush=True,
    )


def _ensure_quant_loader_deps() -> None:
    """Install the loader a pre-quantized AWQ/GPTQ export needs, at worker runtime.

    transformers' AWQ path requires ``gptqmodel`` (its unified GPTQ/AWQ loader); without it
    ``from_pretrained`` raises ImportError (SFT) or silently fails to 4-bit the weights so the
    base loads near-bf16 and leaves no room for the vLLM rollout (GRPO). Flash caches its
    per-GPU dep env, so adding it via resolve_worker_deps won't land β€” install it here, before
    the model loads. Only when a quant_repo is configured (AUTOSLM_QUANT_REPO or catalog)."""
    repo = os.environ.get("AUTOSLM_QUANT_REPO") or ""
    if not repo:
        try:
            repo = quant_weights_repo(JOB_SPEC.model) if JOB_SPEC else ""
        except Exception:
            repo = ""
    if not repo:
        return
    import importlib
    import importlib.metadata
    import importlib.util
    import subprocess

    if importlib.util.find_spec("gptqmodel") is None:
        # gptqmodel's install AGGRESSIVELY downgrades core deps, breaking the worker's working
        # stack: protobuf -> trl GRPO import fails; huggingface_hub -> transformers fails
        # ("cannot import name KernelInfo"). Snapshot the core stack BEFORE and restore it after
        # so gptqmodel only adds its kernels and can't perturb the rest.
        import contextlib

        # Restore ONLY the packages gptqmodel's install is known to downgrade-and-break:
        # protobuf (trl GRPO import) and huggingface_hub (transformers KernelInfo). Restoring
        # the wider stack (transformers/tokenizers/accelerate) via --no-deps left them
        # inconsistent ("Either a revision or a version must be specified" at trl import).
        pin = {}
        for p in ("protobuf", "huggingface_hub"):
            with contextlib.suppress(Exception):
                pin[p] = importlib.metadata.version(p)
        # gptqmodel: transformers' AWQ/GPTQ loader. optimum>=1.24: PEFT's dispatch path calls
        # is_gptqmodel_available() which requires it. Pin gptqmodel==5.8.0: PEFT's released
        # lora/awq.py imports `AwqGEMMQuantLinear`, which gptqmodel RENAMED to `AwqGEMMLinear`
        # in v6.0.0 -> latest gptqmodel breaks the import. 5.8.0 is the last 5.x with the old
        # name (verified), matching the worker's PEFT.
        subprocess.run(
            [sys.executable, "-m", "pip", "install", "gptqmodel==5.8.0", "optimum>=1.24.0"],
            check=False,
        )
        # gptqmodel pulls the HF `kernels` Hub package, which BREAKS `import transformers` on the
        # 5.6-5.12 stack ("Either a revision or a version must be specified" -> trl GRPO import
        # fails -> the run dies before training; measured on the AWQ A100 run). The worker stack is
        # designed to run WITHOUT `kernels` (see WORKER_DEPS), so remove it after the install β€” same
        # as docker/Dockerfile.quant does for the baked quant image.
        subprocess.run(
            [sys.executable, "-m", "pip", "uninstall", "-y", "kernels"],
            check=False,
        )
        if pin:
            # one install call so pip resolves the restored set together (no-deps: don't let the
            # restore re-trigger downgrades of each other).
            subprocess.run(
                [
                    sys.executable,
                    "-m",
                    "pip",
                    "install",
                    "--no-deps",
                    *[f"{p}=={v}" for p, v in pin.items()],
                ],
                check=False,
            )
        importlib.invalidate_caches()
    print(
        f"[quant] gptqmodel present={importlib.util.find_spec('gptqmodel') is not None} "
        f"for pre-quantized base {repo}",
        flush=True,
    )


def main():
    # Idempotency: if DONE was already uploaded, a re-delivered job re-fetches the final
    # metrics from HF and returns them immediately. (The previous behavior β€” sleeping in
    # an infinite loop β€” kept a billable GPU worker alive until the execution timeout.)
    try:
        # Idempotency FIRST β€” before any env-mutating pip install / package removal: a re-delivered
        # job whose DONE already exists must return the persisted metrics and exit WITHOUT running
        # _drop_fla_on_hopper() (pip-uninstalls fla) or _ensure_quant_loader_deps() (pip-installs
        # gptqmodel) β€” those wasted a worker mutating its env on an already-complete run.
        if HF_REPO:
            from huggingface_hub import hf_hub_download

            try:
                hf_hub_download(
                    repo_id=HF_REPO,
                    repo_type="dataset",
                    filename=f"{hf_prefix()}/DONE",
                    token=os.environ.get("HUGGINGFACE_TOKEN"),
                )
                done = True
            except Exception:
                done = False
            if done:
                print("Run already complete (DONE present); returning persisted metrics.")
                heartbeat("already_done")
                try:
                    got = hf_hub_download(
                        repo_id=HF_REPO,
                        repo_type="dataset",
                        filename=f"{hf_prefix()}/metrics.json",
                        token=os.environ.get("HUGGINGFACE_TOKEN"),
                    )
                    import shutil

                    shutil.copy(got, "/tmp/metrics.json")
                    sys.stdout.flush()
                    os._exit(0)
                except Exception as e:
                    raise SystemExit(f"DONE present but metrics.json unavailable: {e}") from e
        # Not a DONE re-delivery -> this worker will train. These must run before any model import:
        _drop_fla_on_hopper()  # Hopper fla guard (see _drop_fla_on_hopper)
        _ensure_quant_loader_deps()  # AWQ/GPTQ pre-quantized base needs its loader before from_pretrained
        heartbeat("boot")
        finalize_alloc_conf_for_sleep()  # sync CUDA alloc conf to resolved sleep (before first CUDA alloc)
        disable_fla_if_requested()  # Hopper Gated-DeltaNet escape hatch (before any transformers import / kernel probe)
        probe_hopper_kernels()  # log the Hopper GDN kernel stack (tilelang import result) to console
        # Dispatch table β€” register new algorithms (e.g. ppo) here as they land.
        modes = {
            "sft": run_sft,  # SFT (TRL SFTTrainer)
            "rl": run_rl,  # GRPO (TRL GRPOTrainer + colocated vLLM)
        }
        handler = modes.get(RUN_MODE)
        if handler is None:
            raise SystemExit(f"unknown RUN_MODE {RUN_MODE}; known: {sorted(modes)}")
        handler()
        # All artifacts (adapter, train_meta, metrics, DONE) are uploaded to HF *inside* the
        # handler. The RL trainer's colocated vLLM can DEADLOCK at interpreter shutdown
        # during NCCL/IPC/CUDA teardown β€” not segfault-and-exit (which `check=False` on the
        # train subprocess already tolerates), but hang forever. That would block the Flash
        # handler's *blocking* `subprocess.run` (heartbeat frozen at "rl_train_done") and the
        # whole run stalls until the wall-clock cap. Hard-exit to bypass the hanging teardown now that
        # every output is safely persisted.
        sys.stdout.flush()
        sys.stderr.flush()
        os._exit(0)
    except Exception as e:
        tb = traceback.format_exc()
        traceback.print_exc()
        # Upload the FULL traceback under a phase-specific name (error_<phase>.txt) so the
        # train (sft/rl) root-cause error survives for debugging. heartbeat.json is
        # single-file/overwritten, so the per-phase error file is the persistent signal.
        try:
            err_name = error_artifact_name(RUN_MODE)
            err_path = f"/tmp/{err_name}"
            with open(err_path, "w") as f:
                f.write(tb)
            hf_upload_file(err_path, err_name)
        except Exception as up_err:
            print("error-upload warn:", up_err)
        try:
            heartbeat(f"error_{RUN_MODE}", error=str(e)[:500], diag=gpu_diagnostics())
        except Exception:
            heartbeat(f"error_{RUN_MODE}", error=str(e)[:500])
        # keep container alive briefly so logs flush, then exit non-zero -> restart
        time.sleep(10)
        raise


if __name__ == "__main__":
    main()