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
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
//! Decoder-only transformer assembly: configuration, builder, and the model.
use crate::attention::{KvCache, causal_by_default};
use crate::batch::TokenBatch;
use crate::causal_lm_loss::{TotalLoss, add_z_loss, causal_lm_loss_batch};
use crate::embedding::Embedding;
use crate::matrix::Matrix;
use crate::moe::{DEFAULT_AUX_LOSS_WEIGHT, DEFAULT_ROUTER_Z_LOSS_WEIGHT, MoeConfig};
use crate::network::NetworkError;
use crate::norm::RmsNorm;
use crate::optimizers::Optimizer;
use crate::param::{Linear, Param};
use crate::rope::{Rope, RopeScaling};
use crate::transformer_block::{FeedForward, TransformerBlock, TransformerBlockCache};
use rand::{SeedableRng, rngs::StdRng};
use serde::{Deserialize, Serialize};
use std::io::{Read, Write};
use std::path::Path;
/// Everything needed to lay out a decoder-only model.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct TransformerConfig {
pub vocab_size: usize,
pub d_model: usize,
pub n_layers: usize,
pub n_heads: usize,
/// `n_heads` for plain multi-head attention, fewer for grouped-query.
pub n_kv_heads: usize,
pub head_dim: usize,
/// Hidden width of the dense feed-forward layers.
pub d_ff: usize,
/// Hidden width of one expert, normally a fraction of `d_ff`.
pub moe_d_ff: usize,
pub num_experts: usize,
pub experts_per_token: usize,
/// Layer indices that use a MoE feed-forward. Everything else is dense,
/// which is how real MoE models keep their first layers.
pub moe_layers: Vec<usize>,
pub shared_expert: bool,
pub max_seq_len: usize,
pub rope_base: f32,
/// Stretches the rotary angles past the length the weights were trained
/// at. Absent in checkpoints written before it existed.
#[serde(default)]
pub rope_scaling: Option<RopeScaling>,
pub rmsnorm_eps: f32,
/// Reuses the embedding matrix as the output projection.
pub tie_embeddings: bool,
/// Whether attention is causal. False is the encoder shape: every position
/// reads the whole sequence, which is what a masked-language-model or a
/// vision transformer wants and what generation cannot use.
///
/// Defaults to true on load, so a checkpoint written before this existed
/// restores as the decoder it was.
#[serde(default = "causal_by_default")]
pub causal: bool,
pub aux_loss_weight: f32,
pub router_z_loss_weight: f32,
/// Set by [`TransformerLm::add_lora`]. Recorded here because it is what
/// tells [`TransformerLm::load_bin`] to rebuild the adapters and re-freeze
/// the base weights before it reads a file that holds both.
#[serde(default)]
pub lora: Option<LoraConfig>,
}
/// The shape of the low-rank adapters [`TransformerLm::add_lora`] attaches.
///
/// `rank` is the bottleneck width; 8 to 32 is the usual range, and the cost of
/// the adapters is `rank * (in + out)` per projection against the `in * out`
/// the projection itself costs. `alpha / rank` scales the adapter's output, so
/// raising the rank does not by itself raise how much the adapter moves the
/// model; the convention is `alpha == rank` or `alpha == 2 * rank`.
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq)]
pub struct LoraConfig {
pub rank: usize,
pub alpha: f32,
/// Seeds the initialization of the down-projections, so two runs that
/// adapt the same base model the same way start from the same adapters.
pub seed: u64,
}
impl LoraConfig {
/// `alpha` defaults to `rank`, which is scale one.
pub fn new(rank: usize) -> Self {
Self {
rank,
alpha: rank as f32,
seed: 0,
}
}
pub fn alpha(mut self, alpha: f32) -> Self {
self.alpha = alpha;
self
}
pub fn seed(mut self, seed: u64) -> Self {
self.seed = seed;
self
}
}
impl Default for TransformerConfig {
/// A roughly 55M-total / 36M-active model: small enough to train on a CPU
/// for experiments, large enough that the sparsity is visible.
fn default() -> Self {
Self {
vocab_size: 32_000,
d_model: 512,
n_layers: 8,
n_heads: 8,
n_kv_heads: 2,
head_dim: 64,
d_ff: 1408,
moe_d_ff: 352,
num_experts: 8,
experts_per_token: 2,
moe_layers: (2..8).collect(),
shared_expert: true,
max_seq_len: 2048,
rope_base: 10_000.0,
rope_scaling: None,
rmsnorm_eps: 1e-6,
tie_embeddings: true,
causal: true,
aux_loss_weight: DEFAULT_AUX_LOSS_WEIGHT,
router_z_loss_weight: DEFAULT_ROUTER_Z_LOSS_WEIGHT,
lora: None,
}
}
}
impl TransformerConfig {
pub fn validate(&self) -> Result<(), NetworkError> {
for (name, value) in [
("vocab_size", self.vocab_size),
("d_model", self.d_model),
("n_layers", self.n_layers),
("n_heads", self.n_heads),
("n_kv_heads", self.n_kv_heads),
("head_dim", self.head_dim),
("d_ff", self.d_ff),
("max_seq_len", self.max_seq_len),
] {
if value == 0 {
return Err(NetworkError::InvalidConfig(format!(
"{name} must be non-zero"
)));
}
}
if !self.n_heads.is_multiple_of(self.n_kv_heads) || self.n_kv_heads > self.n_heads {
return Err(NetworkError::InvalidConfig(format!(
"n_heads ({}) must be a multiple of n_kv_heads ({})",
self.n_heads, self.n_kv_heads
)));
}
if !self.head_dim.is_multiple_of(2) {
return Err(NetworkError::InvalidConfig(format!(
"head_dim must be even for rotary embeddings, got {}",
self.head_dim
)));
}
if let Some(&layer) = self.moe_layers.iter().find(|&&l| l >= self.n_layers) {
return Err(NetworkError::InvalidConfig(format!(
"moe_layers names layer {layer}, but the model has {} layers",
self.n_layers
)));
}
if !self.moe_layers.is_empty() {
self.moe_config().validate()?;
}
if self.lora.is_some_and(|lora| lora.rank == 0) {
return Err(NetworkError::InvalidConfig(
"lora rank must be non-zero".into(),
));
}
Ok(())
}
pub fn moe_config(&self) -> MoeConfig {
MoeConfig {
num_experts: self.num_experts,
experts_per_token: self.experts_per_token,
d_ff: self.moe_d_ff,
shared_expert: self.shared_expert,
aux_loss_weight: self.aux_loss_weight,
router_z_loss_weight: self.router_z_loss_weight,
}
}
pub fn is_moe_layer(&self, layer: usize) -> bool {
self.moe_layers.contains(&layer)
}
/// Parameter counts derived from the configuration alone, so a caller can
/// size a model before paying to build one.
pub fn parameter_counts(&self) -> ParameterCounts {
let query = self.d_model * self.n_heads * self.head_dim;
let key_value = 2 * self.d_model * self.n_kv_heads * self.head_dim;
let attention = 2 * query + key_value;
let norms = 2 * self.d_model;
let dense_ffn = 3 * self.d_model * self.d_ff;
let expert = 3 * self.d_model * self.moe_d_ff;
let shared = if self.shared_expert { expert } else { 0 };
let router = self.num_experts * self.d_model;
let moe_total = router + self.num_experts * expert + shared;
let moe_active = router + self.experts_per_token * expert + shared;
let mut total = self.vocab_size * self.d_model + self.d_model;
if !self.tie_embeddings {
total += self.vocab_size * self.d_model;
}
let mut active = total;
for layer in 0..self.n_layers {
total += attention + norms;
active += attention + norms;
if self.is_moe_layer(layer) {
total += moe_total;
active += moe_active;
} else {
total += dense_ffn;
active += dense_ffn;
}
}
ParameterCounts { total, active }
}
}
/// Total and per-token-active weight counts.
///
/// For a MoE model these differ by a lot, and both matter: total sets the
/// memory the model occupies, active sets what one forward pass costs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ParameterCounts {
pub total: usize,
pub active: usize,
}
impl ParameterCounts {
/// Total divided by active. One for a dense model, higher the sparser the
/// routing.
pub fn sparsity_ratio(&self) -> f32 {
if self.active == 0 {
return 0.0;
}
self.total as f32 / self.active as f32
}
}
impl std::fmt::Display for ParameterCounts {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
formatter,
"{:.1}M total / {:.1}M active ({:.2}x)",
self.total as f64 / 1e6,
self.active as f64 / 1e6,
self.sparsity_ratio()
)
}
}
/// Fluent configuration for [`TransformerLm`], in the style of
/// [`NetworkBuilder`](crate::network::NetworkBuilder).
///
/// It is a separate builder rather than an extension of `NetworkBuilder`
/// because the two describe different things: one is a list of dense layer
/// widths, the other a fixed block structure parameterized by head and expert
/// counts.
#[derive(Clone, Debug)]
pub struct TransformerBuilder {
config: TransformerConfig,
optimizer: Optimizer,
seed: Option<u64>,
mixed_precision: bool,
z_loss: f32,
checkpoint: Vec<bool>,
}
impl TransformerBuilder {
pub fn new() -> Self {
Self {
config: TransformerConfig::default(),
optimizer: Optimizer::adam(3e-4),
seed: None,
mixed_precision: true,
z_loss: 0.0,
checkpoint: Vec::new(),
}
}
pub fn config(mut self, config: TransformerConfig) -> Self {
self.config = config;
self
}
pub fn vocab_size(mut self, vocab_size: usize) -> Self {
self.config.vocab_size = vocab_size;
self
}
pub fn d_model(mut self, d_model: usize) -> Self {
self.config.d_model = d_model;
self
}
pub fn n_layers(mut self, n_layers: usize) -> Self {
self.config.n_layers = n_layers;
self
}
pub fn heads(mut self, n_heads: usize, n_kv_heads: usize, head_dim: usize) -> Self {
self.config.n_heads = n_heads;
self.config.n_kv_heads = n_kv_heads;
self.config.head_dim = head_dim;
self
}
pub fn d_ff(mut self, d_ff: usize) -> Self {
self.config.d_ff = d_ff;
self
}
pub fn moe_d_ff(mut self, moe_d_ff: usize) -> Self {
self.config.moe_d_ff = moe_d_ff;
self
}
pub fn experts(mut self, num_experts: usize, experts_per_token: usize) -> Self {
self.config.num_experts = num_experts;
self.config.experts_per_token = experts_per_token;
self
}
/// Layer indices that use a MoE feed-forward.
pub fn moe_layers(mut self, layers: impl IntoIterator<Item = usize>) -> Self {
self.config.moe_layers = layers.into_iter().collect();
self
}
pub fn shared_expert(mut self, shared_expert: bool) -> Self {
self.config.shared_expert = shared_expert;
self
}
pub fn max_seq_len(mut self, max_seq_len: usize) -> Self {
self.config.max_seq_len = max_seq_len;
self
}
pub fn rope_base(mut self, rope_base: f32) -> Self {
self.config.rope_base = rope_base;
self
}
pub fn rope_scaling(mut self, rope_scaling: Option<RopeScaling>) -> Self {
self.config.rope_scaling = rope_scaling;
self
}
pub fn rmsnorm_eps(mut self, rmsnorm_eps: f32) -> Self {
self.config.rmsnorm_eps = rmsnorm_eps;
self
}
/// Drops the causal mask, so every position reads the whole sequence.
///
/// This is the encoder shape — BERT-style masked language modelling, or a
/// vision transformer over patches. A bidirectional model cannot generate:
/// appending a token changes the tokens before it, so the KV cache has
/// nothing to cache and [`TransformerLm::generate`] reports that. Training
/// it on the next-token loss would also be meaningless, because every
/// position can see the token it is asked to predict.
///
/// CUDA is decoder-only: the flash-attention kernel is causal, so
/// [`TransformerLm::to_cuda`] reports that rather than training the wrong
/// mask on a device.
pub fn bidirectional(mut self, bidirectional: bool) -> Self {
self.config.causal = !bidirectional;
self
}
pub fn tie_embeddings(mut self, tie_embeddings: bool) -> Self {
self.config.tie_embeddings = tie_embeddings;
self
}
pub fn aux_loss_weight(mut self, weight: f32) -> Self {
self.config.aux_loss_weight = weight;
self
}
pub fn router_z_loss_weight(mut self, weight: f32) -> Self {
self.config.router_z_loss_weight = weight;
self
}
pub fn optimizer(mut self, optimizer: Optimizer) -> Self {
self.optimizer = optimizer;
self
}
pub fn seed(mut self, seed: u64) -> Self {
self.seed = Some(seed);
self
}
/// Lets the device path compute in reduced precision. **On by default**,
/// and ignored by the CPU path, which is always FP32. Pass `false` to get
/// a bit-comparable FP32 device run.
///
/// Two things turn on together, and neither touches the parameters, the
/// optimizer state or the gradients the optimizer consumes, all of which
/// stay FP32:
///
/// * Every cuBLAS GEMM runs on the tensor cores in TF32: storage stays
/// FP32 and the products still accumulate in FP32, but the two
/// multiplier inputs are rounded to a 10-bit mantissa first.
/// * The language-model head — its input, its weight, its logits and both
/// of its gradient products — is computed in BF16, with the cross-entropy
/// reading and writing BF16 in place. The gradient that leaves the head
/// for the rest of the network is widened back to FP32, and the weight
/// gradient is accumulated into the FP32 gradient after every chunk
/// rather than summed in BF16.
///
/// No loss scaling, and none is needed: both formats keep FP32's exponent
/// range, so nothing underflows here that FP32 would have kept. That is
/// the reason for BF16 over FP16.
///
/// The cost is accuracy. A TF32 dot product carries roughly `2^-11`
/// relative error per term against FP32's `2^-24`, and BF16 storage
/// carries `2^-8`, so agreement with the FP32 path is around `1e-2`
/// relative on a loss rather than `1e-4`. Over twenty steps of the 5.2M
/// dense configuration at a 32k vocabulary the two loss curves still track
/// each other to four decimal places, because the head's error is
/// stochastic across 32000 logits rather than a systematic bias.
///
/// The head is worth the casts because it is the only part of the step
/// whose GEMMs are `vocab`-wide; it is about three quarters of all GEMM
/// time. Measured on an RTX 3060 at batch 128, sequence 128, the flag is
/// worth about 1.7x end to end (61k vs 104k tokens/s), which is why it is
/// the default.
pub fn mixed_precision(mut self, mixed_precision: bool) -> Self {
self.mixed_precision = mixed_precision;
self
}
/// Adds `weight * logsumexp(logits)^2` per predicted position to the
/// training loss, which keeps the LM head's logits from drifting large
/// and the softmax from saturating. PaLM used `1e-4`. The default of `0`
/// leaves the loss untouched.
///
/// The term is reported in [`TotalLoss::auxiliary_loss`] by
/// [`TransformerLm::train_step`] and [`TransformerLm::accumulate_step`];
/// [`TransformerLm::evaluate`] and the masked-language-model step leave
/// it out. Like the precision, it is not saved with the model.
pub fn z_loss(mut self, weight: f32) -> Self {
self.z_loss = weight;
self
}
/// Recomputes the listed blocks' forward pass during the backward pass
/// instead of keeping their activations, so each of them holds only its
/// input between the two. That costs about one more forward pass of those
/// blocks per step and frees most of their activation memory, which is
/// what lets a longer sequence or a bigger batch fit on the card.
///
/// Indexes past the last block are ignored. It applies to training on the
/// device; the host path and decoding keep everything. Like the precision,
/// it is not saved with the model.
pub fn checkpoint(mut self, blocks: impl IntoIterator<Item = usize>) -> Self {
self.checkpoint = checkpoint_flags(blocks);
self
}
/// Parameter counts for what this builder would produce.
pub fn parameter_counts(&self) -> ParameterCounts {
self.config.parameter_counts()
}
pub fn build(self) -> Result<TransformerLm, NetworkError> {
TransformerLm::from_builder(self)
}
}
/// One flag per block index up to the largest listed.
fn checkpoint_flags(blocks: impl IntoIterator<Item = usize>) -> Vec<bool> {
let mut flags = Vec::new();
for index in blocks {
if flags.len() <= index {
flags.resize(index + 1, false);
}
flags[index] = true;
}
flags
}
impl Default for TransformerBuilder {
fn default() -> Self {
Self::new()
}
}
/// What [`TransformerLm::backward`] needs, and the auxiliary losses the forward
/// pass produced.
#[derive(Clone, Debug)]
pub struct TransformerCache {
batch: TokenBatch,
blocks: Vec<TransformerBlockCache>,
final_input: Matrix,
final_output: Matrix,
auxiliary_loss: f32,
/// Set when the forward pass ran device-side, in which case the host fields
/// above are empty and every activation lives in this cache instead. Shared
/// rather than owned so that a `TransformerCache` stays `Clone`: device
/// buffers cannot be duplicated by a derive.
#[cfg(feature = "cuda")]
device: Option<std::sync::Arc<crate::gpu_model::GpuCache>>,
}
impl TransformerCache {
/// Summed load-balancing and z-losses from every MoE layer, already
/// weighted.
pub fn auxiliary_loss(&self) -> f32 {
self.auxiliary_loss
}
/// The share of routed token slots each expert received, one vector per
/// MoE layer in block order; each sums to one. Empty for a dense model.
///
/// The benchmark's random tokens route almost evenly, real text need not:
/// an expert well above `1 / num_experts` is the one every MoE cost
/// estimate is waiting on.
pub fn expert_loads(&self) -> Vec<Vec<f32>> {
#[cfg(feature = "cuda")]
if let Some(device) = &self.device {
return device.expert_loads();
}
self.blocks
.iter()
.filter_map(TransformerBlockCache::expert_loads)
.collect()
}
/// The batch this cache was produced from, which the loss needs in order
/// to find the sequence boundaries.
pub fn batch(&self) -> &TokenBatch {
&self.batch
}
}
/// Magic and version for the optimizer-state sidecar, so an unrelated or
/// outdated file is rejected instead of being read as moments.
const OPTIMIZER_STATE_MAGIC: &[u8; 8] = b"RBOPT001";
const WEIGHTS_MAGIC: &[u8; 8] = b"RBWTS001";
const LORA_MAGIC: &[u8; 8] = b"RBLOR001";
/// How [`TransformerLm::save_bin`] stores each weight.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Precision {
/// Raw `f32`, 4 bytes per weight. Lossless, and the only choice that a
/// training run can resume from without a visible jump in loss.
F32,
/// Symmetric int8 with one `f32` scale per row: 1 byte per weight plus 4
/// bytes per row. Lossy, for inference and for shipping a model.
Q8,
/// FP8 E4M3 with one `f32` scale per row, for the block linears of the
/// FLUX-family transformer (`mmdit::Dit`) only: its modulations stay int8,
/// its embeddings `f32`, and [`crate::pipeline::ImagePipeline`] loads the
/// prompt encoder at [`Precision::Q8`]. Other loaders read it as `F32`
/// and [`TransformerLm::save_bin`] refuses it. On a device without FP8
/// tensor cores the bytes are widened to BF16 before each GEMM.
Fp8,
}
/// The JSON preamble of a binary snapshot. Small: it holds no weights.
#[derive(Serialize, Deserialize)]
struct BinHeader {
config: TransformerConfig,
optimizer: Optimizer,
optimizer_step: u64,
precision: Precision,
}
/// Writes `data` as little-endian bytes through a 16 KiB scratch buffer, so a
/// checkpoint never holds a second full copy of its largest tensor.
fn write_f32s(writer: &mut impl Write, data: &[f32]) -> std::io::Result<()> {
let mut bytes = Vec::with_capacity(4 * 4096);
for chunk in data.chunks(4096) {
bytes.clear();
bytes.extend(chunk.iter().flat_map(|v| v.to_le_bytes()));
writer.write_all(&bytes)?;
}
Ok(())
}
/// Rounds to the 255 levels int8 has, leaving -128 unused so the range stays
/// symmetric around zero.
fn quantize(value: f32, scale: f32) -> i8 {
if scale == 0.0 {
return 0;
}
(value / scale).round().clamp(-127.0, 127.0) as i8
}
/// A decoder-only language model.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TransformerLm {
pub config: TransformerConfig,
pub embedding: Embedding,
pub blocks: Vec<TransformerBlock>,
pub final_norm: RmsNorm,
/// `None` when embeddings are tied, in which case the embedding matrix is
/// the output projection.
pub lm_head: Option<Linear>,
pub optimizer: Optimizer,
optimizer_step: usize,
/// Set by [`TransformerLm::to_cuda`]. Never serialized: a snapshot is host
/// data, and a restored model starts on the CPU.
#[cfg(feature = "cuda")]
#[serde(skip)]
device: Option<std::sync::Arc<crate::gpu_transformer::GpuContext>>,
/// Set by [`TransformerBuilder::mixed_precision`] and read by
/// [`TransformerLm::to_cuda`]. Not serialized: it describes how to run a
/// model, not what the model is, and a restored model starts on the CPU.
#[serde(skip)]
#[cfg_attr(not(feature = "cuda"), allow(dead_code))]
mixed_precision: bool,
/// Set by [`TransformerBuilder::z_loss`]. Not serialized, for the same
/// reason as `mixed_precision`.
#[serde(skip)]
pub(crate) z_loss: f32,
/// Set by [`TransformerBuilder::checkpoint`]: which blocks recompute
/// their forward pass in the backward pass. Not serialized either.
#[serde(skip)]
#[cfg_attr(not(feature = "cuda"), allow(dead_code))]
pub(crate) checkpoint: Vec<bool>,
/// Set by [`TransformerLm::set_int8_decode`]. Not serialized either.
#[serde(skip)]
#[cfg_attr(not(feature = "cuda"), allow(dead_code))]
pub(crate) int8_decode: bool,
}
/// Weights and configuration, not transient training or device state: two
/// models that predict identically are equal, wherever their buffers live.
impl PartialEq for TransformerLm {
fn eq(&self, other: &Self) -> bool {
self.config == other.config
&& self.embedding == other.embedding
&& self.blocks == other.blocks
&& self.final_norm == other.final_norm
&& self.lm_head == other.lm_head
&& self.optimizer == other.optimizer
}
}
impl TransformerLm {
pub fn builder() -> TransformerBuilder {
TransformerBuilder::new()
}
fn from_builder(builder: TransformerBuilder) -> Result<Self, NetworkError> {
let config = builder.config;
config.validate()?;
let mut rng = builder
.seed
.map_or_else(StdRng::from_entropy, StdRng::seed_from_u64);
let rope = Rope::scaled(
config.head_dim,
config.max_seq_len,
config.rope_base,
config.rope_scaling,
)?;
let embedding = Embedding::new(config.vocab_size, config.d_model, &mut rng);
let mut blocks = Vec::with_capacity(config.n_layers);
for layer in 0..config.n_layers {
let feed_forward = if config.is_moe_layer(layer) {
FeedForward::moe(config.d_model, config.moe_config(), &mut rng)?
} else {
FeedForward::swiglu(config.d_model, config.d_ff, &mut rng)
};
blocks.push(TransformerBlock::new(
config.d_model,
config.n_heads,
config.n_kv_heads,
config.head_dim,
rope.clone(),
feed_forward,
config.rmsnorm_eps,
&mut rng,
)?);
if !config.causal {
// Set after construction rather than threaded through a
// ninth argument: the block owns the attention and nothing
// else in it changes.
blocks
.last_mut()
.expect("a block was just pushed")
.attention
.set_causal(false);
}
}
let lm_head = (!config.tie_embeddings)
.then(|| Linear::new(config.d_model, config.vocab_size, &mut rng));
let mut model = Self {
final_norm: RmsNorm::new(config.d_model, config.rmsnorm_eps),
config,
embedding,
blocks,
lm_head,
optimizer: builder.optimizer,
optimizer_step: 0,
#[cfg(feature = "cuda")]
device: None,
mixed_precision: builder.mixed_precision,
z_loss: builder.z_loss,
checkpoint: builder.checkpoint,
int8_decode: false,
};
if let Some(lora) = model.config.lora {
model.attach_lora(lora);
}
Ok(model)
}
/// Counts taken from the built modules. Agrees with
/// [`TransformerConfig::parameter_counts`].
pub fn parameter_counts(&self) -> ParameterCounts {
let head = self.lm_head.as_ref().map_or(0, |head| head.weight.len());
let base = self.embedding.weight.len() + self.final_norm.weight.len() + head;
ParameterCounts {
total: base
+ self
.blocks
.iter()
.map(TransformerBlock::num_parameters)
.sum::<usize>(),
active: base
+ self
.blocks
.iter()
.map(TransformerBlock::active_parameters)
.sum::<usize>(),
}
}
/// One empty key/value cache per layer, sized for `max_seq_len`.
pub fn new_kv_caches(&self) -> Vec<KvCache> {
(0..self.config.n_layers)
.map(|_| {
KvCache::with_capacity(
self.config.n_kv_heads,
self.config.head_dim,
self.config.max_seq_len,
)
})
.collect()
}
/// Forward pass over a batch of sequences, returning
/// `[batch * seq_len, vocab_size]` logits.
///
/// Sequences are packed into one matrix, so every matmul in the model is
/// `batch` times taller than it would be for a single sequence. Short
/// sequences are right-padded; their rows produce logits that the loss
/// ignores.
pub fn forward_train<S: AsRef<[u32]>>(
&self,
sequences: &[S],
) -> Result<(Matrix, TransformerCache), NetworkError> {
self.forward_batch(&TokenBatch::new(sequences)?)
}
/// [`TransformerLm::forward_train`] over an already-packed batch.
pub fn forward_batch(
&self,
batch: &TokenBatch,
) -> Result<(Matrix, TransformerCache), NetworkError> {
self.check_length(batch.seq_len(), 0)?;
#[cfg(feature = "cuda")]
if let Some(context) = &self.device {
let (logits, cache) = crate::gpu_model::forward(self, context, batch)?;
self.check_device()?;
return Ok((
logits,
TransformerCache {
batch: batch.clone(),
blocks: Vec::new(),
final_input: Matrix::new(0, 0),
final_output: Matrix::new(0, 0),
auxiliary_loss: cache.auxiliary_loss(),
device: Some(std::sync::Arc::new(cache)),
},
));
}
let layout = batch.layout();
let mut hidden = self.embedding.forward(batch.ids())?;
let mut blocks = Vec::with_capacity(self.blocks.len());
let mut auxiliary_loss = 0.0;
for block in &self.blocks {
let (output, cache) = block.forward_train(&hidden, layout)?;
auxiliary_loss += cache.auxiliary_loss();
blocks.push(cache);
hidden = output;
}
let final_output = self.final_norm.forward(&hidden);
let logits = match &self.lm_head {
Some(head) => head.forward(&final_output),
None => self.embedding.unembed(&final_output),
};
self.check_device()?;
Ok((
logits,
TransformerCache {
batch: batch.clone(),
blocks,
final_input: hidden,
final_output,
auxiliary_loss,
#[cfg(feature = "cuda")]
device: None,
},
))
}
/// Inference-only forward pass, appending to the caches.
///
/// Pass the whole prompt with empty caches to prefill, then one token at a
/// time; the caches carry the position, so the caller does not track it.
pub fn forward_cached(
&self,
ids: &[u32],
caches: &mut [KvCache],
) -> Result<Matrix, NetworkError> {
if caches.len() != self.blocks.len() {
return Err(NetworkError::InvalidConfig(format!(
"expected one kv cache per layer ({}), got {}",
self.blocks.len(),
caches.len()
)));
}
self.check_length(ids.len(), caches.first().map_or(0, KvCache::len))?;
let mut hidden = self.embedding.forward(ids)?;
for (block, cache) in self.blocks.iter().zip(caches.iter_mut()) {
hidden = block.forward_cached(&hidden, cache)?;
}
let hidden = self.final_norm.forward(&hidden);
let logits = match &self.lm_head {
Some(head) => head.forward(&hidden),
None => self.embedding.unembed(&hidden),
};
self.check_device()?;
Ok(logits)
}
/// Continues `prompt` by `max_new_tokens` ids, returning only the new ones.
///
/// The prompt is prefilled into a fresh set of caches in one pass and each
/// token after it costs one row of attention. A caller that wants the
/// tokens as they arrive, or wants to stop on one, uses
/// [`generate_with`](TransformerLm::generate_with); a caller that wants to
/// keep the caches for a second turn runs the loop itself.
///
/// ```no_run
/// # use rusting_brain::{Sampler, TransformerLm};
/// # let mut model = TransformerLm::load_bin("model.rbw")?;
/// let mut sampler = Sampler::temperature(0.8, None).top_k(40);
/// let continuation = model.generate(&[1, 2, 3], 128, &mut sampler)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn generate(
&self,
prompt: &[u32],
max_new_tokens: usize,
sampler: &mut crate::sampling::Sampler,
) -> Result<Vec<u32>, NetworkError> {
self.generate_with(prompt, max_new_tokens, sampler, |_| true)
}
/// [`generate`](TransformerLm::generate), calling `on_token` with each id
/// as it is decoded and stopping early when it returns `false`.
///
/// Decoding a hundred tokens takes as long as a hundred forward passes, so
/// a caller that prints the result at the end prints nothing for several
/// seconds. This hands over each token at the point it exists, which is
/// also where an end-of-text id or a stop sequence is noticed:
///
/// ```no_run
/// # use rusting_brain::{Sampler, TransformerLm};
/// # let mut model = TransformerLm::load_bin("model.rbw")?;
/// # let mut sampler = Sampler::greedy();
/// # let end_of_text = 0;
/// let continuation = model.generate_with(&[1, 2, 3], 128, &mut sampler, |id| {
/// print!("{id} ");
/// id != end_of_text
/// })?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// The id that stopped the generation is in the returned continuation: it
/// was sampled, and hiding it would make the two functions disagree about
/// what the model produced.
pub fn generate_with(
&self,
prompt: &[u32],
max_new_tokens: usize,
sampler: &mut crate::sampling::Sampler,
mut on_token: impl FnMut(u32) -> bool,
) -> Result<Vec<u32>, NetworkError> {
if prompt.is_empty() {
return Err(NetworkError::InvalidConfig(
"generation needs at least one prompt token".into(),
));
}
let mut decoder = self.decoder();
decoder.feed(prompt)?;
let mut generated = Vec::with_capacity(max_new_tokens);
for _ in 0..max_new_tokens {
// `next` defers the forward pass for the token it returns, so the
// last one costs none, and a generation that ends exactly on
// `max_seq_len` does not overflow the caches.
let next = decoder.next(sampler)?;
generated.push(next);
if !on_token(next) {
break;
}
}
Ok(generated)
}
/// Beam search: keeps the `beams` most probable continuations of
/// `prompt` at each step and returns the best one found.
///
/// A continuation that samples `end` stops there, `end` included, and
/// gives up its beam, so the search narrows as continuations finish. The
/// best is the one with the highest mean log-probability per token, so a
/// short finished continuation does not win only for summing fewer
/// terms. With `beams` at 1 this is greedy decoding.
///
/// ```no_run
/// # use rusting_brain::TransformerLm;
/// # let model = TransformerLm::load_bin("model.rbw")?;
/// # let end_of_text = 0;
/// let continuation = model.generate_beam(&[1, 2, 3], 64, 4, Some(end_of_text))?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn generate_beam(
&self,
prompt: &[u32],
max_new_tokens: usize,
beams: usize,
end: Option<u32>,
) -> Result<Vec<u32>, NetworkError> {
if prompt.is_empty() || beams == 0 {
return Err(NetworkError::InvalidConfig(
"beam search needs a prompt token and at least one beam".into(),
));
}
let mut root = self.decoder();
root.feed(prompt)?;
// Each live beam: its session, its continuation, and the summed
// log-probability of that continuation.
let mut live = vec![(root, Vec::new(), 0.0f32)];
let mut finished: Vec<(Vec<u32>, f32)> = Vec::new();
for _ in 0..max_new_tokens {
let mut candidates = Vec::new();
for (parent, (decoder, _, score)) in live.iter_mut().enumerate() {
let logits = decoder.logits()?;
let max = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max);
let log_sum = max + logits.iter().map(|l| (l - max).exp()).sum::<f32>().ln();
candidates.extend(
logits
.iter()
.enumerate()
.map(|(id, l)| (parent, id as u32, *score + l - log_sum)),
);
}
candidates.sort_by(|a, b| b.2.total_cmp(&a.2));
let mut next = Vec::with_capacity(beams);
for &(parent, id, score) in candidates.iter().take(beams) {
let mut continuation = live[parent].1.clone();
continuation.push(id);
if Some(id) == end {
finished.push((continuation, score));
continue;
}
// NOTE: a fork copies the whole cache every step; reuse
// the parent for its last child if beam search gets hot.
let mut decoder = live[parent].0.fork()?;
decoder.push(id)?;
next.push((decoder, continuation, score));
}
live = next;
if live.is_empty() {
break;
}
}
finished.extend(
live.into_iter()
.map(|(_, continuation, score)| (continuation, score)),
);
let mean =
|(continuation, score): &(Vec<u32>, f32)| score / continuation.len().max(1) as f32;
Ok(finished
.into_iter()
.max_by(|a, b| mean(a).total_cmp(&mean(b)))
.map(|(continuation, _)| continuation)
.unwrap_or_default())
}
/// [`generate`](TransformerLm::generate) with a greedy sampler, drafted
/// by a smaller model `draft` that shares this model's vocabulary.
///
/// The draft proposes up to `lookahead` ids one at a time, and this model
/// scores all of them in one forward pass, keeping the proposals that
/// match its own greedy choice plus one id of its own. Each round costs one
/// pass of this model instead of one per id, and the continuation is the
/// one greedy decoding gives, up to near-ties in the logits that the
/// multi-row pass can round the other way.
///
/// ```no_run
/// # use rusting_brain::TransformerLm;
/// # let model = TransformerLm::load_bin("model.rbw")?;
/// # let draft = TransformerLm::load_bin("draft.rbw")?;
/// let continuation = model.generate_speculative(&draft, &[1, 2, 3], 128, 4)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn generate_speculative(
&self,
draft: &TransformerLm,
prompt: &[u32],
max_new_tokens: usize,
lookahead: usize,
) -> Result<Vec<u32>, NetworkError> {
let mut greedy = crate::sampling::Sampler::greedy();
self.generate_speculative_with(draft, prompt, max_new_tokens, lookahead, &mut greedy)
}
/// [`generate_speculative`](TransformerLm::generate_speculative) with any
/// sampler: the continuation is distributed as `generate` with `sampler`
/// would draw it from this model, whatever the draft proposes.
///
/// Both models are sampled with the same settings. A proposal `x` that the
/// draft gave probability `q(x)` is kept with probability
/// `min(1, p(x) / q(x))` under this model's `p`; the first one refused is
/// replaced by a draw from what is left of `p` once `q` is taken out,
/// `max(0, p - q)`, which is exactly the mass the acceptance test
/// under-counts. A greedy sampler reduces this to the greedy scheme.
///
/// ```no_run
/// # use rusting_brain::{Sampler, TransformerLm};
/// # let model = TransformerLm::load_bin("model.rbw")?;
/// # let draft = TransformerLm::load_bin("draft.rbw")?;
/// let mut sampler = Sampler::temperature(0.8, Some(7)).top_k(40);
/// let continuation = model.generate_speculative_with(&draft, &[1, 2, 3], 128, 4, &mut sampler)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn generate_speculative_with(
&self,
draft: &TransformerLm,
prompt: &[u32],
max_new_tokens: usize,
lookahead: usize,
sampler: &mut crate::sampling::Sampler,
) -> Result<Vec<u32>, NetworkError> {
if prompt.is_empty() {
return Err(NetworkError::InvalidConfig(
"generation needs at least one prompt token".into(),
));
}
if draft.embedding.vocab_size() != self.embedding.vocab_size() {
return Err(NetworkError::InvalidConfig(format!(
"the draft model has {} tokens, this model {}",
draft.embedding.vocab_size(),
self.embedding.vocab_size()
)));
}
let mut target = self.decoder();
let mut proposer = draft.decoder();
target.rewrite(0, prompt)?;
proposer.rewrite(0, prompt)?;
let capacity = self.config.max_seq_len.min(draft.config.max_seq_len);
let mut generated = Vec::with_capacity(max_new_tokens);
while generated.len() < max_new_tokens {
let base = target.history.len();
let proposals = lookahead
.min(max_new_tokens - generated.len() - 1)
.min(capacity.saturating_sub(base));
let (proposal, drafted): (Vec<u32>, Vec<Vec<f32>>) = (0..proposals)
.map(|_| proposer.propose(sampler))
.collect::<Result<Vec<_>, _>>()?
.into_iter()
.unzip();
let logits = target.score(&proposal)?;
let mut accepted = 0;
let own = loop {
let p =
sampler.probabilities(logits.row(accepted), &target.history[..base + accepted]);
if accepted == proposals {
break sampler.draw(&p);
}
let (x, q) = (proposal[accepted] as usize, &drafted[accepted]);
if sampler.uniform() * q[x] < p[x] {
accepted += 1;
continue;
}
let rest: Vec<f32> = p.iter().zip(q).map(|(p, q)| (p - q).max(0.0)).collect();
// All of `p` under `q` leaves nothing; only rounding gets here.
break match rest.iter().sum::<f32>() > 0.0 {
true => sampler.draw(&rest),
false => sampler.draw(&p),
};
};
generated.extend_from_slice(&proposal[..accepted]);
generated.push(own);
target.rewrite(base + accepted, &[own])?;
proposer.rewrite(base + accepted, &[own])?;
}
Ok(generated)
}
/// A decoding session that keeps its caches between turns.
///
/// [`generate`](TransformerLm::generate) throws the caches away when it
/// returns, so a chat loop re-reads the whole conversation on every turn —
/// quadratic work in the number of turns, and the second turn of a long
/// conversation is the expensive one. A [`Decoder`] holds them:
///
/// ```no_run
/// # use rusting_brain::{Sampler, TransformerLm};
/// # let model = TransformerLm::load_bin("model.rbw")?;
/// # let mut sampler = Sampler::greedy();
/// let mut decoder = model.decoder();
/// decoder.feed(&[1, 2, 3])?; // prompt
/// let reply: Vec<u32> = (0..20).map(|_| decoder.next(&mut sampler)).collect::<Result<_, _>>()?;
/// decoder.feed(&[4, 5])?; // the user's next turn
/// let second = decoder.next(&mut sampler)?; // no re-read of anything above
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn decoder(&self) -> Decoder<'_> {
Decoder {
caches: self.new_kv_caches(),
model: self,
history: Vec::new(),
logits: None,
pending: None,
#[cfg(feature = "cuda")]
device: None,
}
}
/// A [`Decoder`] over `sequences` independent sequences decoded in step.
///
/// One token per sequence is one forward pass over `sequences` rows, so
/// on a device the weights are read once for all of them instead of once
/// each, which is where a single sequence's decode spends its time.
/// Prompts may differ in length:
///
/// ```no_run
/// # use rusting_brain::{Sampler, TransformerLm};
/// # let model = TransformerLm::load_bin("model.rbw")?;
/// # let mut sampler = Sampler::greedy();
/// let mut decoder = model.batch_decoder(2)?;
/// decoder.feed(&[&[1, 2, 3], &[4, 5]])?;
/// let step: Vec<u32> = decoder.next(&mut sampler)?; // one id per sequence
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn batch_decoder(&self, sequences: usize) -> Result<BatchDecoder<'_>, NetworkError> {
if sequences == 0 {
return Err(NetworkError::InvalidConfig(
"a batch decoder needs at least one sequence".into(),
));
}
Ok(BatchDecoder {
model: self,
caches: (0..sequences).map(|_| self.new_kv_caches()).collect(),
histories: vec![Vec::new(); sequences],
logits: None,
pending: None,
#[cfg(feature = "cuda")]
device: None,
})
}
/// Replaces every projection weight with one `i8` per value and a scale per
/// row, and drops the gradients and Adam moments. Returns the bytes the
/// weights now occupy.
///
/// A CPU decode step reads every active weight once, so it is bound by
/// memory bandwidth: a quarter of the bytes is most of the way to a quarter
/// of the time. Rounding to 255 levels per row costs about 0.4% relative
/// error per weight, which generation absorbs.
///
/// One-way. The `f32` weights are gone afterwards, so
/// [`train_step`](TransformerLm::train_step),
/// [`backward`](TransformerLm::backward), `save_bin` and `to_cuda` all
/// refuse rather than write out or train on rounded weights.
///
/// ```no_run
/// # use rusting_brain::{Sampler, TransformerLm};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut model = TransformerLm::load_bin("model.rbw")?;
/// let bytes = model.quantize();
/// println!("{} MiB of weights", bytes / (1024 * 1024));
/// let continuation = model.generate(&[1, 2, 3], 128, &mut Sampler::greedy())?;
/// # Ok(())
/// # }
/// ```
pub fn quantize(&mut self) -> usize {
let mut bytes = self.embedding.weight.quantize();
for block in &mut self.blocks {
for linear in block.linears_mut() {
bytes += linear.weight.quantize();
}
}
if let Some(head) = &mut self.lm_head {
bytes += head.weight.quantize();
}
bytes
}
/// [`quantize`](TransformerLm::quantize) with every projection inside the
/// blocks at 4 bits a weight, on `codebook`, with one scale per 64
/// weights of a row. The embedding table and an untied output head stay
/// int8: they are a small share of the weights and the most sensitive to
/// rounding. Returns the bytes the quantized weights now occupy.
///
/// Host only for now: a 4-bit model refuses `to_cuda`. The same one-way
/// rules as `quantize` apply.
///
/// ```no_run
/// # use rusting_brain::TransformerLm;
/// # use rusting_brain::quantized::Codebook;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut model = TransformerLm::load_bin("model.rbw")?;
/// let bytes = model.quantize_4bit(Codebook::Nf4);
/// println!("{} MiB of weights", bytes / (1024 * 1024));
/// # Ok(())
/// # }
/// ```
pub fn quantize_4bit(&mut self, codebook: crate::quantized::Codebook) -> usize {
let mut bytes = self.embedding.weight.quantize();
for block in &mut self.blocks {
for linear in block.linears_mut() {
bytes += linear.weight.quantize_4bit(codebook);
}
}
if let Some(head) = &mut self.lm_head {
bytes += head.weight.quantize();
}
bytes
}
/// Rounds every weight [`quantize`](TransformerLm::quantize) would round
/// through the int8 grid in the forward pass, while the stored weights and
/// the optimizer stay in full precision.
///
/// This is quantization-aware training: what backpropagates is the loss of
/// the rounded model, so the weights settle where rounding costs least and
/// the accuracy `quantize` gives up afterwards shrinks. The backward pass
/// is a straight-through estimator: it differentiates as though the
/// rounding were the identity, rounding having a derivative of zero almost
/// everywhere.
///
/// It covers the embedding table, every projection in every block and an
/// untied output head, which is the set `quantize` replaces. A forward pass
/// costs one rounding pass over each of those weights, so this is usually
/// worth turning on for the last part of a run rather than all of it.
///
/// CPU only: device training never reads these weights, so a model on a
/// device reports that rather than training as though the flag had taken.
///
/// ```no_run
/// # use rusting_brain::{Precision, TransformerLm};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let mut model = TransformerLm::load_bin("model.rbw")?;
/// # let sequences: Vec<Vec<u32>> = Vec::new();
/// // The last part of a run, once the loss has mostly settled.
/// model.quantization_aware(true)?;
/// for batch in &sequences {
/// model.train_step(&[batch])?;
/// }
/// model.quantization_aware(false)?;
/// model.save_bin("model.q8.rbw", Precision::Q8)?;
/// # Ok(())
/// # }
/// ```
pub fn quantization_aware(&mut self, enabled: bool) -> Result<(), NetworkError> {
self.check_full_precision("train quantization-aware")?;
self.check_not_on_device("train quantization-aware")?;
self.embedding.weight.set_fake_quantize(enabled);
for block in &mut self.blocks {
for linear in block.linears_mut() {
linear.weight.set_fake_quantize(enabled);
}
}
if let Some(head) = &mut self.lm_head {
head.weight.set_fake_quantize(enabled);
}
Ok(())
}
/// Whether [`quantization_aware`](TransformerLm::quantization_aware) is on.
pub fn is_quantization_aware(&self) -> bool {
self.embedding.weight.is_fake_quantized()
}
/// Whether [`quantize`](TransformerLm::quantize) has been called.
pub fn is_quantized(&self) -> bool {
self.embedding.weight.quantized.is_some()
}
fn check_not_quantized(&self, action: &str) -> Result<(), NetworkError> {
if self.is_quantized() {
return Err(NetworkError::InvalidConfig(format!(
"this model was quantized for inference, so it cannot {action}"
)));
}
Ok(())
}
/// [`TransformerLm::check_not_quantized`], and also no quantized LoRA base:
/// what needs the base weights in full precision.
fn check_full_precision(&self, action: &str) -> Result<(), NetworkError> {
self.check_not_quantized(action)?;
if self.has_quantized_base() {
return Err(NetworkError::InvalidConfig(format!(
"this model's LoRA base is quantized, so it cannot {action}; save the adapter \
with save_lora instead"
)));
}
Ok(())
}
/// Attaches a low-rank adapter to every attention and feed-forward
/// projection and freezes everything else.
///
/// This is the fine-tuning shape: the base weights keep their values but
/// lose their gradient and Adam moments, so a model that needed four
/// weight-sized buffers to train now needs one plus the adapters. The
/// adapters start at zero, so the first forward pass after this call
/// returns exactly what the base model returned.
///
/// The MoE router is left alone. Everything else the training loop already
/// does — [`train_step_batch`](TransformerLm::train_step_batch),
/// [`step`](TransformerLm::step), [`save_bin`](TransformerLm::save_bin),
/// [`to_cuda`](TransformerLm::to_cuda) — keeps working unchanged; the
/// frozen parameters simply ignore the step.
///
/// Call this while the model is on the host. A device-resident model has
/// already allocated the gradients and moments freezing would release, so
/// attaching there would cost the memory the adapter exists to save.
///
/// ```no_run
/// # use rusting_brain::{LoraConfig, TransformerLm};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut model = TransformerLm::load_bin("base.rbw")?;
/// model.add_lora(LoraConfig::new(16).alpha(32.0))?;
/// // ... train ...
/// model.save_lora("adapter.rbl")?;
/// # Ok(())
/// # }
/// ```
pub fn add_lora(&mut self, lora: LoraConfig) -> Result<(), NetworkError> {
self.check_not_quantized("take a LoRA adapter")?;
if lora.rank == 0 {
return Err(NetworkError::InvalidConfig(
"lora rank must be non-zero".into(),
));
}
if self.config.lora.is_some() {
return Err(NetworkError::InvalidConfig(
"this model already has a LoRA adapter; merge it first".into(),
));
}
self.check_not_on_device("take a LoRA adapter")?;
self.config.lora = Some(lora);
self.attach_lora(lora);
Ok(())
}
/// Puts the frozen flags back after a snapshot that carried the adapters
/// but not the flags. Freezing everything and then thawing the adapters
/// avoids a second traversal that could disagree with `params_mut`.
fn refreeze_for_lora(&mut self) {
for param in self.params_mut() {
param.freeze();
}
for block in &mut self.blocks {
for linear in block.lora_linears_mut() {
if let Some(lora) = &mut linear.lora {
for param in lora.params_mut() {
param.unfreeze();
}
}
}
}
}
fn attach_lora(&mut self, lora: LoraConfig) {
for param in self.params_mut() {
param.freeze();
}
let mut rng = StdRng::seed_from_u64(lora.seed);
for block in &mut self.blocks {
for linear in block.lora_linears_mut() {
linear.attach_lora(lora.rank, lora.alpha, &mut rng);
}
}
}
/// Folds every adapter into the weight it adapts and unfreezes the model.
///
/// What comes out is an ordinary model that predicts what the adapted one
/// predicted, with no adapters left to carry and no inference cost over the
/// base. It is the only way to get a trained adapter through
/// [`quantize`](TransformerLm::quantize), and, like
/// [`add_lora`](TransformerLm::add_lora), it runs on the host: call
/// [`to_cpu`](TransformerLm::to_cpu) first.
pub fn merge_lora(&mut self) -> Result<(), NetworkError> {
self.check_full_precision("merge a LoRA adapter")?;
self.check_not_on_device("merge a LoRA adapter")?;
for block in &mut self.blocks {
for linear in block.lora_linears_mut() {
linear.merge_lora();
}
}
for param in self.params_mut() {
param.unfreeze();
}
self.config.lora = None;
Ok(())
}
/// Stores every adapted projection's frozen base weight as int8 with one
/// scale per row, the [`Precision::Q8`] scheme, so fine-tuning holds the
/// base in a quarter of the memory: the QLoRA recipe, at int8.
///
/// The adapters stay FP32 and train as before, against the rounded base.
/// On a device the base is uploaded as int8 and widened into each weight
/// pack as it is built. The embedding, the norms, the output head and a
/// MoE router keep full precision.
///
/// One-way, like [`quantize`](TransformerLm::quantize): the model can then
/// train, generate and [`save_lora`](TransformerLm::save_lora), but not
/// `merge_lora` or `save_bin`. Load a full-precision base and the saved
/// adapter to merge. Call it on the host, after
/// [`add_lora`](TransformerLm::add_lora); returns the bytes the int8 bases
/// take.
///
/// ```no_run
/// # use rusting_brain::{LoraConfig, TransformerLm};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut model = TransformerLm::load_hf("TinyLlama-1.1B", 2048)?;
/// model.add_lora(LoraConfig::new(16))?;
/// model.quantize_lora_base()?;
/// // `to_cuda` here, train_step as usual, then:
/// model.save_lora("adapter.rbl")?;
/// # Ok(())
/// # }
/// ```
pub fn quantize_lora_base(&mut self) -> Result<usize, NetworkError> {
self.quantize_lora_base_with(crate::param::Param::quantize)
}
/// [`quantize_lora_base`](TransformerLm::quantize_lora_base) at 4 bits a
/// weight on `codebook`, with a scale per block of 64: the QLoRA recipe
/// proper with [`Codebook::Nf4`](crate::quantized::Codebook::Nf4), an
/// eighth of the FP32 base's memory against a quarter at int8.
///
/// ```no_run
/// # use rusting_brain::{LoraConfig, TransformerLm, quantized::Codebook};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut model = TransformerLm::load_hf("TinyLlama-1.1B", 2048)?;
/// model.add_lora(LoraConfig::new(16))?;
/// model.quantize_lora_base_4bit(Codebook::Nf4)?;
/// # Ok(())
/// # }
/// ```
pub fn quantize_lora_base_4bit(
&mut self,
codebook: crate::quantized::Codebook,
) -> Result<usize, NetworkError> {
self.quantize_lora_base_with(|weight| weight.quantize_4bit(codebook))
}
fn quantize_lora_base_with(
&mut self,
quantize: impl Fn(&mut crate::param::Param) -> usize,
) -> Result<usize, NetworkError> {
self.check_not_quantized("quantize its LoRA base")?;
self.check_not_on_device("quantize its LoRA base")?;
if !self.has_lora() {
return Err(NetworkError::InvalidConfig(
"quantize_lora_base needs a LoRA adapter; call add_lora first".into(),
));
}
let mut bytes = 0;
for block in &mut self.blocks {
for linear in block.lora_linears_mut() {
bytes += quantize(&mut linear.weight);
}
}
Ok(bytes)
}
/// Whether [`quantize_lora_base`](TransformerLm::quantize_lora_base) or
/// [`quantize_lora_base_4bit`](TransformerLm::quantize_lora_base_4bit) has
/// run.
pub fn has_quantized_base(&self) -> bool {
// `quantize_lora_base` converts every adapted projection at once, and
// every block's query projection is one.
self.blocks
.iter()
.any(|block| block.attention.query.weight.quantized.is_some())
}
/// Whether [`add_lora`](TransformerLm::add_lora) is in effect.
pub fn has_lora(&self) -> bool {
self.config.lora.is_some()
}
/// Every parameter the optimizer will actually move: the adapters alone
/// once [`add_lora`](TransformerLm::add_lora) has run, and the whole model
/// otherwise.
pub fn trainable_params_mut(&mut self) -> Vec<&mut Param> {
self.params_mut()
.into_iter()
.filter(|param| !param.is_frozen())
.collect()
}
/// How many weights a training step updates.
pub fn trainable_parameters(&mut self) -> usize {
self.trainable_params_mut()
.iter()
.map(|param| param.len())
.sum()
}
/// Writes the adapter weights alone, which is the point of training one:
/// a rank-16 adapter over a 50M-parameter model is a few megabytes, and
/// several of them share one base checkpoint.
///
/// Read back by [`load_lora`](TransformerLm::load_lora) onto a base model
/// that [`add_lora`](TransformerLm::add_lora) has prepared the same way.
pub fn save_lora<P: AsRef<Path>>(&mut self, path: P) -> Result<(), NetworkError> {
let lora = self.config.lora.ok_or_else(|| {
NetworkError::InvalidConfig("this model has no LoRA adapter to save".into())
})?;
#[cfg(feature = "cuda")]
self.sync_from_device()?;
let header = serde_json::to_vec(&lora)?;
let file = std::fs::File::create(path)?;
let mut writer = std::io::BufWriter::new(file);
writer.write_all(LORA_MAGIC)?;
writer.write_all(&(header.len() as u64).to_le_bytes())?;
writer.write_all(&header)?;
let params = self.trainable_params_mut();
writer.write_all(&(params.len() as u64).to_le_bytes())?;
for param in params {
writer.write_all(&(param.value.rows as u64).to_le_bytes())?;
writer.write_all(&(param.value.cols as u64).to_le_bytes())?;
let bytes: Vec<u8> = param
.value
.data
.iter()
.flat_map(|value| value.to_le_bytes())
.collect();
writer.write_all(&bytes)?;
}
writer.flush()?;
Ok(())
}
/// Restores adapter weights written by [`save_lora`](TransformerLm::save_lora).
///
/// The model must already carry adapters of the same shape, so the usual
/// sequence is `load_bin` the base, `add_lora` with the same
/// [`LoraConfig`], then this. Fails closed on any mismatch rather than
/// loading part of an adapter.
pub fn load_lora<P: AsRef<Path>>(&mut self, path: P) -> Result<(), NetworkError> {
let file = std::fs::File::open(path)?;
let file_length = file.metadata()?.len();
let mut reader = std::io::BufReader::new(file);
let mut magic = [0u8; 8];
reader.read_exact(&mut magic)?;
if &magic != LORA_MAGIC {
return Err(NetworkError::InvalidSnapshot(
"not a RustingBrain LoRA file".into(),
));
}
let mut word = [0u8; 8];
reader.read_exact(&mut word)?;
let header_length = u64::from_le_bytes(word);
if header_length > file_length {
return Err(NetworkError::InvalidSnapshot(format!(
"adapter file header claims {header_length} bytes, the file has {file_length}"
)));
}
let mut header = vec![0u8; header_length as usize];
reader.read_exact(&mut header)?;
let header: LoraConfig = serde_json::from_slice(&header)?;
match self.config.lora {
Some(lora) if lora == header => {}
Some(lora) => {
return Err(NetworkError::InvalidSnapshot(format!(
"adapter file holds rank {} alpha {}, this model has rank {} alpha {}",
header.rank, header.alpha, lora.rank, lora.alpha
)));
}
None => {
return Err(NetworkError::InvalidSnapshot(
"this model has no LoRA adapter to load into; call add_lora first".into(),
));
}
}
reader.read_exact(&mut word)?;
let count = u64::from_le_bytes(word) as usize;
let params = self.trainable_params_mut();
if count != params.len() {
return Err(NetworkError::InvalidSnapshot(format!(
"adapter file holds {count} parameters, this model has {}",
params.len()
)));
}
for param in params {
reader.read_exact(&mut word)?;
let rows = u64::from_le_bytes(word) as usize;
reader.read_exact(&mut word)?;
let cols = u64::from_le_bytes(word) as usize;
if rows != param.value.rows || cols != param.value.cols {
return Err(NetworkError::InvalidSnapshot(format!(
"adapter file has a {rows}x{cols} parameter where the model has {}x{}",
param.value.rows, param.value.cols
)));
}
let mut bytes = vec![0u8; rows * cols * 4];
reader.read_exact(&mut bytes)?;
for (slot, chunk) in param.value.data.iter_mut().zip(bytes.as_chunks::<4>().0) {
*slot = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
}
}
Ok(())
}
fn check_not_on_device(&self, action: &str) -> Result<(), NetworkError> {
if self.on_device() {
return Err(NetworkError::InvalidConfig(format!(
"a device-resident model cannot {action}; call to_cpu first"
)));
}
Ok(())
}
/// Accumulates gradients for every parameter from `dL/dlogits`.
pub fn backward(
&mut self,
cache: &TransformerCache,
grad_logits: &Matrix,
) -> Result<(), NetworkError> {
self.check_not_quantized("be trained")?;
#[cfg(feature = "cuda")]
if let Some(device) = &cache.device {
let context = self
.device
.clone()
.ok_or_else(|| NetworkError::Cuda("the model left the device mid-step".into()))?;
crate::gpu_model::backward(self, &context, device, grad_logits)?;
return self.check_device();
}
let mut grad_hidden = match &mut self.lm_head {
Some(head) => head.backward(&cache.final_output, grad_logits),
// Tied weights: this accumulates into the same gradient buffer the
// embedding gather writes to, which is the point of tying.
None => self
.embedding
.unembed_backward(&cache.final_output, grad_logits),
};
grad_hidden = self.final_norm.backward(&cache.final_input, &grad_hidden);
for (block, block_cache) in self.blocks.iter_mut().zip(&cache.blocks).rev() {
grad_hidden = block.backward(block_cache, &grad_hidden)?;
}
self.embedding.backward(cache.batch.ids(), &grad_hidden)?;
self.check_device()
}
/// Moves every matmul-bound parameter onto a CUDA device and keeps it
/// there until [`TransformerLm::to_cpu`].
///
/// Training then runs entirely on the device:
/// [`forward_batch`](TransformerLm::forward_batch) and
/// [`backward`](TransformerLm::backward) dispatch to
/// `gpu_model`, which keeps activations in device buffers across
/// a whole layer and rounds trip to the host only for the token ids, the
/// logits, `dL/dlogits`, the RMSNorm scales and one routing table per MoE
/// layer. The norm weights stay host-resident, so they keep using the CPU
/// optimizer step and cached decode keeps working. Fails closed: no device
/// means an error, never a silent CPU fallback. A caller who wants a fallback asks
/// [`accelerator_doctor`](crate::accelerator::accelerator_doctor) first.
#[cfg(feature = "cuda")]
pub fn to_cuda(&mut self, device: usize, memory_budget_mib: usize) -> Result<(), NetworkError> {
self.check_not_quantized("move to a device")?;
let counts = self.config.parameter_counts();
// Value, gradient and the two Adam moments, all FP32 - except under a
// LoRA adapter, where the frozen base carries its value alone and the
// adapters, which the counts above do not include, are the only things
// holding the other three.
let buffers_per_weight = if self.has_lora() { 1 } else { 4 };
let estimated_mib = (counts.total * 4 * buffers_per_weight).div_ceil(1024 * 1024);
if memory_budget_mib > 0 && estimated_mib > memory_budget_mib {
return Err(NetworkError::CudaMemoryBudget {
estimated_mib,
budget_mib: memory_budget_mib,
});
}
let context =
crate::gpu_transformer::GpuContext::with_precision(device, self.mixed_precision)?;
self.embedding.weight.move_to_cuda(&context)?;
for block in &mut self.blocks {
for linear in block.linears_mut() {
// `params_mut` rather than `weight`, so a LoRA adapter rides
// onto the device with the projection it adapts.
for param in linear.params_mut() {
param.move_to_cuda(&context)?;
}
}
}
if let Some(head) = &mut self.lm_head {
head.weight.move_to_cuda(&context)?;
}
self.device = Some(context);
Ok(())
}
/// Copies every device parameter back and releases the device buffers.
#[cfg(feature = "cuda")]
pub fn to_cpu(&mut self) -> Result<(), NetworkError> {
for param in self.params_mut() {
param.move_to_cpu()?;
}
if let Some(context) = self.device.take() {
context.check()?;
}
Ok(())
}
/// Refreshes the host copies of the device parameters, keeping residency.
///
/// Call this before [`TransformerLm::save_json`] or before reading weights
/// while training on a device: the host values go stale at the first device
/// optimizer step.
#[cfg(feature = "cuda")]
pub fn sync_from_device(&mut self) -> Result<(), NetworkError> {
for param in self.params_mut() {
param.sync_from_device()?;
}
self.check_device()
}
/// Waits for every queued device operation to finish.
///
/// A no-op on the host path. Timing code needs it because the optimizer
/// step only enqueues launches, so without a barrier its cost lands in
/// whatever phase is measured next.
pub fn synchronize(&self) -> Result<(), NetworkError> {
#[cfg(feature = "cuda")]
if let Some(context) = &self.device {
return context.synchronize();
}
Ok(())
}
/// Whether the matmul-bound parameters currently live on a device.
pub fn on_device(&self) -> bool {
#[cfg(feature = "cuda")]
{
self.device.is_some()
}
#[cfg(not(feature = "cuda"))]
{
false
}
}
/// Reports the first device failure since the last check.
///
/// Device operations sit inside infallible signatures (`Linear::forward`
/// returns a `Matrix`), so a failure is recorded and surfaced here, at the
/// next fallible boundary.
fn check_device(&self) -> Result<(), NetworkError> {
#[cfg(feature = "cuda")]
if let Some(context) = &self.device {
context.check()?;
}
Ok(())
}
/// The natural-log probability the model gives each token of `ids` after
/// the ones before it: `ids.len() - 1` values, the first for `ids[1]`.
///
/// Their sum scores a whole continuation, for ranking candidates or
/// classifying by the most probable label; minus their mean is the loss
/// [`evaluate`](TransformerLm::evaluate) reports for this one sequence.
///
/// ```no_run
/// # use rusting_brain::TransformerLm;
/// # let model = TransformerLm::load_bin("model.rbw")?;
/// let score: f32 = model.log_probabilities(&[1, 2, 3, 4])?.iter().sum();
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn log_probabilities(&self, ids: &[u32]) -> Result<Vec<f32>, NetworkError> {
let (logits, _) = self.forward_train(&[ids])?;
Ok(ids
.windows(2)
.enumerate()
.map(|(row, pair)| {
let logits = logits.row(row);
let max = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max);
let log_sum = max + logits.iter().map(|l| (l - max).exp()).sum::<f32>().ln();
logits[pair[1] as usize] - log_sum
})
.collect())
}
/// The loss over a batch, without gradients and without a step.
///
/// This is what a held-out split is for: training loss falls whether or not
/// the model is learning anything general, and the gap between the two is
/// the only thing that says which.
///
/// NOTE: on a device this materializes the full `[rows, vocab]` logits
/// on the host, where `train_step_batch` fuses the loss into the head and
/// never does. Evaluate in batches the size of a training batch, or add a
/// device loss-only path if that stops being enough.
pub fn evaluate(&self, batch: &TokenBatch) -> Result<TotalLoss, NetworkError> {
let (logits, cache) = self.forward_batch(batch)?;
Ok(TotalLoss {
lm_loss: causal_lm_loss_batch(&logits, batch)?.loss,
auxiliary_loss: cache.auxiliary_loss(),
})
}
/// Forward, loss, backward and one optimizer update over a batch of
/// sequences.
///
/// The loss is the mean over every predicted position in the batch, so the
/// gradient is already a batch mean and the optimizer step needs no extra
/// scaling.
pub fn train_step<S: AsRef<[u32]>>(
&mut self,
sequences: &[S],
) -> Result<TotalLoss, NetworkError> {
self.train_step_batch(&TokenBatch::new(sequences)?)
}
/// [`TransformerLm::train_step`] over an already-packed batch, which a
/// training loop that reuses one batch shape can build once.
pub fn train_step_batch(&mut self, batch: &TokenBatch) -> Result<TotalLoss, NetworkError> {
// On a device the loss is fused into the step, so the `[rows, vocab]`
// logits stay in device memory and are never materialized in full.
// See `gpu_model::train_step`.
#[cfg(feature = "cuda")]
if let Some(context) = self.device.clone() {
self.check_length(batch.seq_len(), 0)?;
self.zero_grad();
let (lm_loss, auxiliary_loss) = crate::gpu_model::train_step(self, &context, batch)?;
self.step(1.0);
self.check_device()?;
return Ok(TotalLoss {
lm_loss,
auxiliary_loss,
});
}
let (logits, cache) = self.forward_batch(batch)?;
let mut loss = causal_lm_loss_batch(&logits, batch)?;
let z_loss = add_z_loss(&logits, batch, self.z_loss, &mut loss.grad_logits);
self.zero_grad();
self.backward(&cache, &loss.grad_logits)?;
self.step(1.0);
self.check_device()?;
Ok(TotalLoss {
lm_loss: loss.loss,
auxiliary_loss: cache.auxiliary_loss() + z_loss,
})
}
/// Forward, masked-language-model loss, backward and one optimizer update.
///
/// This is the encoder objective: the batch carries corrupted ids, and the
/// loss scores the model on the tokens that were corrupted, each from both
/// sides at once. Build the batch with
/// [`MaskedBatch::corrupt`](crate::masked_lm::MaskedBatch::corrupt).
///
/// The model must be bidirectional, which is what
/// [`TransformerBuilder::bidirectional`] makes it: with a causal mask a
/// masked position reads nothing after itself, so most of the objective's
/// signal is not there to learn from.
///
/// ```no_run
/// # use rusting_brain::{MaskedBatch, TransformerLm};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut model = TransformerLm::builder()
/// .vocab_size(32_000)
/// .bidirectional(true)
/// .build()?;
/// let batch = MaskedBatch::corrupt(&[vec![5u32, 6, 7, 8]], 32_000, 4, 0.15, None)?;
/// let loss = model.train_step_masked(&batch)?;
/// println!("{}", loss.lm_loss);
/// # Ok(())
/// # }
/// ```
pub fn train_step_masked(
&mut self,
batch: &crate::masked_lm::MaskedBatch,
) -> Result<TotalLoss, NetworkError> {
self.check_bidirectional()?;
let (logits, cache) = self.forward_batch(batch.inputs())?;
let loss = crate::masked_lm::masked_lm_loss(&logits, batch)?;
self.zero_grad();
self.backward(&cache, &loss.grad_logits)?;
self.step(1.0);
Ok(TotalLoss {
lm_loss: loss.loss,
auxiliary_loss: cache.auxiliary_loss(),
})
}
/// The masked loss over a batch, without gradients and without a step.
pub fn evaluate_masked(
&self,
batch: &crate::masked_lm::MaskedBatch,
) -> Result<TotalLoss, NetworkError> {
self.check_bidirectional()?;
let (logits, cache) = self.forward_batch(batch.inputs())?;
Ok(TotalLoss {
lm_loss: crate::masked_lm::masked_lm_loss(&logits, batch)?.loss,
auxiliary_loss: cache.auxiliary_loss(),
})
}
fn check_bidirectional(&self) -> Result<(), NetworkError> {
if self.config.causal {
return Err(NetworkError::InvalidConfig(
"a masked language-modelling loss needs a bidirectional model: under a causal \
mask a masked position reads only the tokens before it, which is the next-token \
objective with holes in it. Build the model with `bidirectional(true)`"
.into(),
));
}
Ok(())
}
/// Forward and backward over one batch, adding into whatever gradients are
/// already there.
///
/// Unlike [`TransformerLm::train_step_batch`] this neither zeroes the
/// gradients first nor steps the optimizer after, which is what lets a
/// caller build an effective batch larger than the device holds:
///
/// ```ignore
/// model.zero_grad();
/// for part in parts {
/// model.accumulate_step(part)?;
/// }
/// model.step(1.0 / parts.len() as f32);
/// ```
///
/// The averaging belongs on the step rather than on each backward pass:
/// Adam normalizes by the gradient's own second moment, so scaling every
/// accumulation identically would cancel out and change nothing.
///
/// For a dense model this reproduces the gradient of the whole batch
/// exactly. A mixture-of-experts model's load-balancing loss does not: it
/// is computed from routing fractions over whatever batch it sees, so four
/// sequences in two accumulations balance the experts against two
/// different halves rather than against the whole. The language-modelling
/// gradient is unaffected; only the auxiliary term shifts.
pub fn accumulate_step(&mut self, batch: &TokenBatch) -> Result<TotalLoss, NetworkError> {
self.check_not_quantized("be trained")?;
#[cfg(feature = "cuda")]
if let Some(context) = self.device.clone() {
self.check_length(batch.seq_len(), 0)?;
let (lm_loss, auxiliary_loss) = crate::gpu_model::train_step(self, &context, batch)?;
self.check_device()?;
return Ok(TotalLoss {
lm_loss,
auxiliary_loss,
});
}
let (logits, cache) = self.forward_batch(batch)?;
let mut loss = causal_lm_loss_batch(&logits, batch)?;
let z_loss = add_z_loss(&logits, batch, self.z_loss, &mut loss.grad_logits);
self.backward(&cache, &loss.grad_logits)?;
Ok(TotalLoss {
lm_loss: loss.loss,
auxiliary_loss: cache.auxiliary_loss() + z_loss,
})
}
/// [`TransformerLm::accumulate_step`] with a per-token loss mask.
///
/// `mask` holds one flag per token position of `batch`, in the same order
/// and of the same length as [`TokenBatch::ids`] - `batch.rows()` flags,
/// padding included. A flag marks its token as a *target*: `false` makes
/// the position that predicts that token contribute exactly zero to the
/// loss and zero to the gradient, and the mean is taken over the flagged
/// positions alone, so no scaling is needed on the caller's side. `None`
/// is [`TransformerLm::accumulate_step`] exactly.
///
/// Masked tokens still run the forward pass and still condition the
/// positions that count, which is what supervised fine-tuning needs: for
/// `<|user|>{instruction}<|assistant|>{response}<|end|>`, flag the
/// `{response}<|end|>` span and leave the instruction span unflagged, and
/// the instruction is read as context without being learned.
///
/// A sequence's first token is never a target - nothing precedes it - so
/// its flag is ignored.
pub fn accumulate_step_masked(
&mut self,
batch: &TokenBatch,
mask: Option<&[bool]>,
) -> Result<TotalLoss, NetworkError> {
match mask {
None => self.accumulate_step(batch),
Some(mask) => self.accumulate_step(&batch.clone().with_loss_mask(mask)?),
}
}
/// Applies the optimizer to every parameter and clears the gradients.
///
/// `scale` divides the accumulated gradient, so a caller that ran several
/// sequences before stepping passes `1.0 / sequences`.
pub fn step(&mut self, scale: f32) {
self.optimizer_step += 1;
let step = self.optimizer_step;
let optimizer = self.optimizer.clone();
crate::optimizers::apply_step(&mut self.params_mut(), &optimizer, step, scale);
}
/// [`TransformerLm::step`], returning how far it moved each parameter
/// relative to its size, `|w_after - w_before| / |w_before|`, in the order
/// [`TransformerLm::params_mut`] yields them. A frozen or all-zero
/// parameter reads 0.
///
/// Around `1e-3` is the usual healthy value under Adam. Well above `1e-2`
/// the step is too large for that layer; far below `1e-4` the layer has
/// stopped learning.
///
/// NOTE: copies every weight to the host twice and holds a second
/// copy there, so call it every few hundred steps, not every step. Add a
/// device-side reduction if it has to run often.
pub fn step_with_update_ratios(&mut self, scale: f32) -> Result<Vec<f32>, NetworkError> {
#[cfg(feature = "cuda")]
self.sync_from_device()?;
let before: Vec<Matrix> = self
.params_mut()
.into_iter()
.map(|param| param.value.clone())
.collect();
self.step(scale);
#[cfg(feature = "cuda")]
self.sync_from_device()?;
Ok(self
.params_mut()
.into_iter()
.zip(&before)
.map(|(param, before)| {
let (moved, size) = param.value.data.iter().zip(&before.data).fold(
(0.0f64, 0.0f64),
|(moved, size), (&after, &before)| {
let delta = f64::from(after - before);
(
moved + delta * delta,
size + f64::from(before) * f64::from(before),
)
},
);
if size == 0.0 {
0.0
} else {
(moved / size).sqrt() as f32
}
})
.collect())
}
/// The L2 norm of the accumulated gradients, over every parameter at once.
///
/// Worth logging on its own: a run that is about to diverge shows it in
/// this number one or two steps before the loss moves.
pub fn grad_norm(&mut self) -> Result<f32, NetworkError> {
crate::optimizers::grad_norm(&mut self.params_mut())
}
/// [`TransformerLm::step`] with the gradients clipped to a global norm of
/// `max_norm` first, and the pre-clip norm returned for logging.
///
/// Clipping is a uniform rescale of every gradient, and `scale` already
/// multiplies every gradient uniformly, so this folds the clip into that
/// factor rather than rewriting the gradient buffers.
///
/// A NaN or infinite norm skips the step and clears the gradients, and
/// the returned norm says so: check `norm.is_finite()` to count skips.
pub fn step_clipped(&mut self, scale: f32, max_norm: f32) -> Result<f32, NetworkError> {
let step = self.optimizer_step + 1;
let optimizer = self.optimizer.clone();
let norm = crate::optimizers::step_clipped(
&mut self.params_mut(),
&optimizer,
step,
scale,
max_norm,
)?;
// A skipped step does not count, so Adam's bias correction stays in
// line with the moments it has.
if norm.is_finite() {
self.optimizer_step = step;
}
Ok(norm)
}
pub fn zero_grad(&mut self) {
crate::optimizers::zero_grad(&mut self.params_mut());
}
pub fn optimizer_step(&self) -> usize {
self.optimizer_step
}
/// Sets the Adam step counter, for a resume that has weights but no saved
/// moments: bias correction only matches moments that were accumulated
/// over the same number of steps, and correcting zero moments as if they
/// were warmed up makes the first updates several times too large.
pub fn set_optimizer_step(&mut self, step: usize) {
self.optimizer_step = step;
}
pub fn params_mut(&mut self) -> Vec<&mut Param> {
let mut params = self.embedding.params_mut();
for block in &mut self.blocks {
params.extend(block.params_mut());
}
params.extend(self.final_norm.params_mut());
if let Some(head) = &mut self.lm_head {
params.extend(head.params_mut());
}
params
}
pub fn save_json<P: AsRef<Path>>(&self, path: P) -> Result<(), NetworkError> {
let file = std::fs::File::create(path)?;
let mut writer = std::io::BufWriter::new(file);
serde_json::to_writer(&mut writer, self)?;
std::io::Write::flush(&mut writer)?;
Ok(())
}
pub fn load_json<P: AsRef<Path>>(path: P) -> Result<Self, NetworkError> {
let file = std::fs::File::open(path)?;
let mut model: Self = serde_json::from_reader(std::io::BufReader::new(file))?;
model.config.validate()?;
// What is frozen is not in the snapshot; the adapters are, and the
// configuration says they are there, which is enough to put the base
// weights back the way `add_lora` left them.
if model.has_lora() {
model.refreeze_for_lora();
}
Ok(model)
}
/// Overrides the precision chosen at build time.
///
/// A snapshot records what a model is, not how to run it, so a model
/// restored by [`TransformerLm::load_json`] always comes back in full
/// precision. A resumed training run that wants reduced precision has to
/// say so again, before [`TransformerLm::to_cuda`].
pub fn set_mixed_precision(&mut self, mixed_precision: bool) {
self.mixed_precision = mixed_precision;
}
/// Overrides the z-loss weight chosen at build time. See
/// [`TransformerBuilder::z_loss`]; a restored model comes back with none.
pub fn set_z_loss(&mut self, weight: f32) {
self.z_loss = weight;
}
/// Holds the Adam moments of every trainable weight on the device at one
/// byte each instead of four, or puts them back in FP32. The moments
/// carry over either way.
///
/// Each block of 256 values keeps its largest magnitude and every value as
/// one of 256 logarithmically spaced levels of it, the scheme of
/// bitsandbytes' block-wise 8-bit Adam. A weight then costs 10 bytes on
/// the device to train instead of 16. Only Adam reads 8-bit state: a Lion
/// step on it fails.
///
/// Device only, and it lasts while the model stays there: call it after
/// [`TransformerLm::to_cuda`]. A model on the host ignores it, and
/// [`TransformerLm::to_cpu`] brings the moments back as FP32.
pub fn set_8bit_optimizer_state(&mut self, enabled: bool) -> Result<(), NetworkError> {
#[cfg(feature = "cuda")]
for param in self.params_mut() {
param.set_8bit_moments(enabled)?;
}
#[cfg(not(feature = "cuda"))]
let _ = enabled;
Ok(())
}
/// Overrides the checkpointed blocks chosen at build time. See
/// [`TransformerBuilder::checkpoint`]; a restored model comes back with
/// none.
pub fn set_checkpoint(&mut self, blocks: impl IntoIterator<Item = usize>) {
self.checkpoint = checkpoint_flags(blocks);
}
/// Makes decoders of a model on a device read every block projection
/// (attention, feed-forwards, routers and experts) and the output head as
/// int8, one byte per weight and a scale per row (the scheme of
/// [`TransformerLm::quantize`]), instead of FP32 or, under mixed
/// precision, BF16. Takes effect for decoders made afterwards.
///
/// A device decode step reads every weight once, so it is bound by memory
/// bandwidth. The stored weights are untouched: training, saving and
/// decoders made with this off still see full precision. The int8 copies
/// live as long as a decoder and come on top of the model's own weights.
/// Host decoders ignore it; [`TransformerLm::quantize`] is the host route.
///
/// On the default model this is about 19% more tokens per second for one
/// sequence and about 12% fewer for a batch of 16, where the int8 kernel
/// does not yet beat cuBLAS on BF16 weights.
pub fn set_int8_decode(&mut self, int8: bool) {
self.int8_decode = int8;
}
/// Writes the Adam moments to `path`, in the order
/// [`TransformerLm::params_mut`] yields them.
///
/// The JSON snapshot holds weights alone: the moments triple its size and
/// nothing that only runs the model ever reads them. A run that stops and
/// resumes does need them. Without them Adam restarts from zero while the
/// step counter carries on, so bias correction no longer compensates and
/// the first updates after the resume are several times larger than the
/// ones the run was taking before it stopped.
///
/// Call this after [`TransformerLm::to_cuda`] on a device-resident model:
/// the device owns the moments, and they are read back here.
pub fn save_optimizer_state<P: AsRef<Path>>(&mut self, path: P) -> Result<(), NetworkError> {
let file = std::fs::File::create(path)?;
let mut writer = std::io::BufWriter::new(file);
let step = self.optimizer_step as u64;
let params = self.params_mut();
writer.write_all(OPTIMIZER_STATE_MAGIC)?;
writer.write_all(&(params.len() as u64).to_le_bytes())?;
writer.write_all(&step.to_le_bytes())?;
for param in params {
let (first, second) = param.moments()?;
writer.write_all(&(first.rows as u64).to_le_bytes())?;
writer.write_all(&(first.cols as u64).to_le_bytes())?;
for matrix in [first, second] {
write_f32s(&mut writer, &matrix.data)?;
}
}
writer.flush()?;
Ok(())
}
/// Restores the moments and step counter written by
/// [`TransformerLm::save_optimizer_state`].
///
/// Order matters on a device-resident model: uploading a parameter zeroes
/// its moments, so call this after [`TransformerLm::to_cuda`], not before.
pub fn load_optimizer_state<P: AsRef<Path>>(&mut self, path: P) -> Result<(), NetworkError> {
let file = std::fs::File::open(path)?;
let mut reader = std::io::BufReader::new(file);
let mut magic = [0u8; 8];
reader.read_exact(&mut magic)?;
if &magic != OPTIMIZER_STATE_MAGIC {
return Err(NetworkError::InvalidSnapshot(
"not a RustingBrain optimizer state file".into(),
));
}
let mut word = [0u8; 8];
reader.read_exact(&mut word)?;
let count = u64::from_le_bytes(word) as usize;
reader.read_exact(&mut word)?;
let step = u64::from_le_bytes(word) as usize;
let params = self.params_mut();
if count != params.len() {
return Err(NetworkError::InvalidSnapshot(format!(
"optimizer state holds {count} parameters, this model has {}",
params.len()
)));
}
for param in params {
reader.read_exact(&mut word)?;
let rows = u64::from_le_bytes(word) as usize;
reader.read_exact(&mut word)?;
let cols = u64::from_le_bytes(word) as usize;
// A frozen parameter released its moments, so it wrote a 0x0
// placeholder and expects one back.
let (expected_rows, expected_cols) = if param.is_frozen() {
(0, 0)
} else {
(param.value.rows, param.value.cols)
};
if rows != expected_rows || cols != expected_cols {
return Err(NetworkError::InvalidSnapshot(format!(
"optimizer state has a {rows}x{cols} parameter where the model has {expected_rows}x{expected_cols}"
)));
}
let mut bytes = vec![0u8; rows * cols * 4];
let mut moments = [Matrix::new(rows, cols), Matrix::new(rows, cols)];
for matrix in &mut moments {
reader.read_exact(&mut bytes)?;
for (slot, chunk) in matrix.data.iter_mut().zip(bytes.as_chunks::<4>().0) {
*slot = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
}
}
let [first, second] = moments;
param.set_moments(first, second)?;
}
self.optimizer_step = step;
Ok(())
}
/// Writes weights in a binary snapshot: raw f32, or int8 with a per-row
/// scale.
///
/// JSON spends about 13 bytes on every weight, because a shortest
/// round-trip `f32` prints as roughly a dozen characters plus a comma, so a
/// 50M-parameter model lands near 670 MB. The same weights are 4 bytes each
/// as raw `f32` and 1 byte each as [`Precision::Q8`], which is 200 MB and
/// 50 MB for that model.
///
/// The header holds the configuration and optimizer as JSON, so
/// [`TransformerLm::load_bin`] rebuilds the module tree before it reads any
/// weights and does not need a matching model to load into.
/// Writes the model out as an ONNX graph for another runtime to serve.
///
/// The graph takes `seq_len` token ids as `int64` under the name `ids` and
/// returns `[seq_len, vocab_size]` logits. Both the rotary tables and the
/// causal mask are baked in at that length, so a model that has to serve
/// several lengths is exported once per length. Weights are written as
/// `f32` whatever [`Precision`] a checkpoint would use.
///
/// What it does not cover:
///
/// - Mixture-of-experts layers. Routing is data-dependent control flow
/// rather than a graph of tensor ops, and exporting one silently as a
/// dense layer would be a different model.
/// - An attached LoRA adapter. Call
/// [`merge_lora`](TransformerLm::merge_lora) first, which folds it into
/// the weights the export writes.
/// - A quantized or device-resident model, as everywhere else.
///
/// There is no KV cache in the graph: it is a prefill, so a runtime
/// generating from it re-reads the whole prefix per token. Export is a
/// serving seam for scoring and short prompts, not a fast decode loop.
///
/// ```no_run
/// # use rusting_brain::TransformerLm;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let model = TransformerLm::load_bin("model.rbw")?;
/// model.save_onnx("model.onnx", 128)?;
/// # Ok(())
/// # }
/// ```
pub fn save_onnx<P: AsRef<Path>>(&self, path: P, seq_len: usize) -> Result<(), NetworkError> {
self.check_full_precision("be exported to ONNX")?;
self.check_not_on_device("be exported to ONNX")?;
if self.has_lora() {
return Err(NetworkError::InvalidConfig(
"an adapted model cannot be exported to ONNX; call merge_lora first".into(),
));
}
self.check_length(seq_len, 0)?;
crate::onnx_export::export_transformer(self, seq_len, path)
}
pub fn save_bin<P: AsRef<Path>>(
&mut self,
path: P,
precision: Precision,
) -> Result<(), NetworkError> {
self.check_full_precision("be saved")?;
if precision == Precision::Fp8 {
return Err(NetworkError::InvalidConfig(
"a language model saves as F32 or Q8, not FP8".into(),
));
}
#[cfg(feature = "cuda")]
self.sync_from_device()?;
let header = serde_json::to_vec(&BinHeader {
config: self.config.clone(),
optimizer: self.optimizer.clone(),
optimizer_step: self.optimizer_step as u64,
precision,
})?;
let file = std::fs::File::create(path)?;
let mut writer = std::io::BufWriter::new(file);
writer.write_all(WEIGHTS_MAGIC)?;
writer.write_all(&(header.len() as u64).to_le_bytes())?;
writer.write_all(&header)?;
let params = self.params_mut();
writer.write_all(&(params.len() as u64).to_le_bytes())?;
for param in params {
let value = ¶m.value;
writer.write_all(&(value.rows as u64).to_le_bytes())?;
writer.write_all(&(value.cols as u64).to_le_bytes())?;
match precision {
Precision::F32 => write_f32s(&mut writer, &value.data)?,
Precision::Q8 => {
for row in value.data.chunks(value.cols.max(1)) {
let absmax = row.iter().fold(0.0f32, |acc, v| acc.max(v.abs()));
let scale = absmax / 127.0;
writer.write_all(&scale.to_le_bytes())?;
let quantized: Vec<u8> =
row.iter().map(|v| quantize(*v, scale) as u8).collect();
writer.write_all(&quantized)?;
}
}
Precision::Fp8 => unreachable!("refused above"),
}
}
writer.flush()?;
Ok(())
}
/// Rebuilds the model written by [`TransformerLm::save_bin`].
///
/// A [`Precision::Q8`] file restores dequantized `f32` weights: the model
/// runs in full precision, it is only the file that is small. Rounding to
/// 255 levels per row costs about 0.4% relative error on each weight, which
/// inference absorbs and a resumed training run does not, so keep
/// [`Precision::F32`] for checkpoints you intend to train from.
pub fn load_bin<P: AsRef<Path>>(path: P) -> Result<Self, NetworkError> {
let file = std::fs::File::open(path)?;
let file_length = file.metadata()?.len();
let mut reader = std::io::BufReader::new(file);
let mut magic = [0u8; 8];
reader.read_exact(&mut magic)?;
if &magic != WEIGHTS_MAGIC {
return Err(NetworkError::InvalidSnapshot(
"not a RustingBrain weight file".into(),
));
}
let mut word = [0u8; 8];
reader.read_exact(&mut word)?;
let header_length = u64::from_le_bytes(word);
if header_length > file_length {
return Err(NetworkError::InvalidSnapshot(format!(
"weight file header claims {header_length} bytes, the file has {file_length}"
)));
}
let mut header = vec![0u8; header_length as usize];
reader.read_exact(&mut header)?;
let header: BinHeader = serde_json::from_slice(&header)?;
header.config.validate()?;
// Building the model allocates what the header asks for, so check the
// file can hold it first: every weight takes at least one byte.
let needed = weights_needed(&header.config);
let rope_table = (header.config.max_seq_len as u128) * (header.config.head_dim as u128);
// An adapter of rank r on an m x n weight holds r * (m + n) values,
// at most twice the weight when r <= min(m, n), which the file bounds.
let config = &header.config;
let smallest = [
config.d_model,
config.n_heads.saturating_mul(config.head_dim),
config.n_kv_heads.saturating_mul(config.head_dim),
if config.moe_layers.is_empty() {
config.d_ff
} else {
config.d_ff.min(config.moe_d_ff)
},
]
.into_iter()
.min()
.unwrap_or(0);
let lora_too_big = config.lora.is_some_and(|lora| lora.rank > smallest);
if needed > file_length as u128 || rope_table > 1 << 28 || lora_too_big {
return Err(NetworkError::InvalidSnapshot(format!(
"weight file header describes a model that does not fit in its {file_length} bytes"
)));
}
let mut model = Self::from_builder(TransformerBuilder {
config: header.config,
optimizer: header.optimizer,
seed: Some(0),
..TransformerBuilder::new()
})?;
model.optimizer_step = header.optimizer_step as usize;
reader.read_exact(&mut word)?;
let count = u64::from_le_bytes(word) as usize;
let params = model.params_mut();
if count != params.len() {
return Err(NetworkError::InvalidSnapshot(format!(
"weight file holds {count} parameters, this configuration builds {}",
params.len()
)));
}
for param in params {
reader.read_exact(&mut word)?;
let rows = u64::from_le_bytes(word) as usize;
reader.read_exact(&mut word)?;
let cols = u64::from_le_bytes(word) as usize;
if rows != param.value.rows || cols != param.value.cols {
return Err(NetworkError::InvalidSnapshot(format!(
"weight file has a {rows}x{cols} parameter where the model has {}x{}",
param.value.rows, param.value.cols
)));
}
match header.precision {
Precision::F32 => {
let mut bytes = vec![0u8; rows * cols * 4];
reader.read_exact(&mut bytes)?;
for (slot, chunk) in param.value.data.iter_mut().zip(bytes.as_chunks::<4>().0) {
*slot = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
}
}
Precision::Q8 => {
let mut scale_bytes = [0u8; 4];
let mut row_bytes = vec![0u8; cols];
for row in param.value.data.chunks_mut(cols.max(1)) {
reader.read_exact(&mut scale_bytes)?;
let scale = f32::from_le_bytes(scale_bytes);
reader.read_exact(&mut row_bytes)?;
for (slot, byte) in row.iter_mut().zip(&row_bytes) {
*slot = *byte as i8 as f32 * scale;
}
}
}
Precision::Fp8 => {
return Err(NetworkError::InvalidConfig(
"this file says FP8, which save_bin never writes".into(),
));
}
}
}
Ok(model)
}
fn check_length(&self, new_tokens: usize, already_cached: usize) -> Result<(), NetworkError> {
let length = new_tokens + already_cached;
if length > self.config.max_seq_len {
return Err(NetworkError::SequenceTooLong {
length,
max_seq_len: self.config.max_seq_len,
});
}
if new_tokens == 0 {
return Err(NetworkError::EmptyDataset);
}
Ok(())
}
}
/// [`TransformerConfig::parameter_counts`]'s total, in arithmetic a corrupt
/// configuration cannot overflow and without a loop over its layers.
fn weights_needed(config: &TransformerConfig) -> u128 {
let [
vocab,
d_model,
n_layers,
n_heads,
n_kv_heads,
head_dim,
d_ff,
moe_d_ff,
num_experts,
] = [
config.vocab_size,
config.d_model,
config.n_layers,
config.n_heads,
config.n_kv_heads,
config.head_dim,
config.d_ff,
config.moe_d_ff,
config.num_experts,
]
.map(|value| value as u128);
let mut moe_layers = config.moe_layers.clone();
moe_layers.sort_unstable();
moe_layers.dedup();
let moe_count = moe_layers.len() as u128;
let product = |values: &[u128]| values.iter().fold(1u128, |acc, v| acc.saturating_mul(*v));
let attention = product(&[2, d_model, n_heads, head_dim])
.saturating_add(product(&[2, d_model, n_kv_heads, head_dim]))
.saturating_add(2 * d_model);
let expert = product(&[3, d_model, moe_d_ff]);
let moe = product(&[num_experts, expert])
.saturating_add(product(&[num_experts, d_model]))
.saturating_add(if config.shared_expert { expert } else { 0 });
let dense = product(&[3, d_model, d_ff]);
product(&[vocab, d_model])
.saturating_add(product(&[n_layers, attention]))
.saturating_add(product(&[moe_count, moe]))
.saturating_add(product(&[n_layers.saturating_sub(moe_count), dense]))
}
/// A decoding session: the KV caches, the ids that filled them, and the logits
/// for whatever comes next. Built by [`TransformerLm::decoder`].
pub struct Decoder<'a> {
model: &'a TransformerLm,
caches: Vec<KvCache>,
history: Vec<u32>,
logits: Option<Matrix>,
/// Sampled but not yet run through the model. The forward pass for a token
/// is only needed to produce the token after it, so deferring it means a
/// session that stops decoding never pays for one, and a session that fills
/// `max_seq_len` exactly does not overflow its caches on the way out.
pending: Option<u32>,
/// The caches on the device, for a model that lives there; `caches` then
/// stays empty.
#[cfg(feature = "cuda")]
device: Option<crate::gpu_model::DeviceKv>,
}
impl<'a> Decoder<'a> {
/// An independent copy of the session, history and caches included. A
/// prefix every request shares, such as a system prompt or a few-shot
/// preamble, is prefilled once and each request continues a fork:
///
/// ```no_run
/// # use rusting_brain::{Sampler, TransformerLm};
/// # let model = TransformerLm::load_bin("model.rbw")?;
/// # let mut sampler = Sampler::greedy();
/// let mut preamble = model.decoder();
/// preamble.feed(&[1, 2, 3, 4])?;
/// let mut request = preamble.fork()?;
/// request.feed(&[5, 6])?;
/// let id = request.next(&mut sampler)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// On a device the copy takes as much memory as the original's caches
/// and shares its packed weights.
pub fn fork(&self) -> Result<Decoder<'a>, NetworkError> {
Ok(Decoder {
model: self.model,
caches: self.caches.clone(),
history: self.history.clone(),
logits: self.logits.clone(),
pending: self.pending,
#[cfg(feature = "cuda")]
device: self.device.as_ref().map(|kv| kv.fork()).transpose()?,
})
}
/// Appends `ids` to the session: a prompt, or the next turn of a
/// conversation. Only these tokens are read, not the ones before them.
pub fn feed(&mut self, ids: &[u32]) -> Result<(), NetworkError> {
self.catch_up()?;
if ids.is_empty() {
return Ok(());
}
self.logits = Some(self.run(ids, 1)?);
self.history.extend_from_slice(ids);
Ok(())
}
/// Samples the next token and appends it to the session.
pub fn next(&mut self, sampler: &mut crate::sampling::Sampler) -> Result<u32, NetworkError> {
self.catch_up()?;
let logits = self.logits.as_ref().ok_or_else(|| {
NetworkError::InvalidConfig("decoding needs a prompt fed in first".into())
})?;
let next = sampler.pick(logits.row(logits.rows - 1), &self.history);
self.history.push(next);
self.pending = Some(next);
Ok(next)
}
/// The next token's logits, for choices [`Sampler`] does not make:
/// constrained output, a logit bias, log-probabilities. Append the chosen
/// id with [`push`](Decoder::push):
///
/// ```no_run
/// # use rusting_brain::TransformerLm;
/// # let model = TransformerLm::load_bin("model.rbw")?;
/// # let allowed = [7u32, 9, 12];
/// let mut decoder = model.decoder();
/// decoder.feed(&[1, 2, 3])?;
/// let logits = decoder.logits()?;
/// let id = *allowed.iter().max_by(|a, b| {
/// logits[**a as usize].total_cmp(&logits[**b as usize])
/// }).unwrap();
/// decoder.push(id)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// [`Sampler`]: crate::Sampler
pub fn logits(&mut self) -> Result<&[f32], NetworkError> {
self.catch_up()?;
let logits = self.logits.as_ref().ok_or_else(|| {
NetworkError::InvalidConfig("decoding needs a prompt fed in first".into())
})?;
Ok(logits.row(logits.rows - 1))
}
/// Appends `id` as if [`next`](Decoder::next) had sampled it, deferring
/// its forward pass the same way.
pub fn push(&mut self, id: u32) -> Result<(), NetworkError> {
self.catch_up()?;
self.history.push(id);
self.pending = Some(id);
Ok(())
}
/// [`next`](Decoder::next), also returning the distribution it drew from.
fn propose(
&mut self,
sampler: &mut crate::sampling::Sampler,
) -> Result<(u32, Vec<f32>), NetworkError> {
self.catch_up()?;
let logits = self.logits.as_ref().ok_or_else(|| {
NetworkError::InvalidConfig("decoding needs a prompt fed in first".into())
})?;
let q = sampler.probabilities(logits.row(logits.rows - 1), &self.history);
let next = sampler.draw(&q);
self.history.push(next);
self.pending = Some(next);
Ok((next, q))
}
/// Every id the session has seen, prompts and generated tokens alike.
pub fn history(&self) -> &[u32] {
&self.history
}
fn catch_up(&mut self) -> Result<(), NetworkError> {
if let Some(id) = self.pending.take() {
self.logits = Some(self.run(&[id], 1)?);
}
Ok(())
}
/// Positions the caches hold, which trail the history by any pending id.
fn cached(&self) -> usize {
#[cfg(feature = "cuda")]
if self.model.device.is_some() {
return self
.device
.as_ref()
.map_or(0, crate::gpu_model::DeviceKv::len);
}
self.caches.first().map_or(0, KvCache::len)
}
/// Keeps the first `keep` ids of the history, appends `ids` and leaves the
/// last of them pending, as [`next`](Decoder::next) would. Ids the caches
/// already hold are not run again.
fn rewrite(&mut self, keep: usize, ids: &[u32]) -> Result<(), NetworkError> {
self.pending = None;
let cached = self.cached().min(keep);
for cache in &mut self.caches {
cache.truncate(cached);
}
#[cfg(feature = "cuda")]
if let Some(kv) = &mut self.device {
kv.truncate(cached);
}
let mut tail = self.history[cached..keep].to_vec();
tail.extend_from_slice(ids);
self.history.truncate(cached);
if let Some((&last, rest)) = tail.split_last() {
self.feed(rest)?;
self.history.push(last);
self.pending = Some(last);
}
Ok(())
}
/// Runs the pending id and then `ids`, returning the logits of every row:
/// row `i` predicts the id after the `i`-th one run.
fn score(&mut self, ids: &[u32]) -> Result<Matrix, NetworkError> {
let mut run: Vec<u32> = self.pending.take().into_iter().collect();
run.extend_from_slice(ids);
let logits = self.run(&run, run.len())?;
self.history.extend_from_slice(ids);
Ok(logits)
}
/// The host returns every row's logits; a device only the last
/// `positions`.
#[cfg_attr(not(feature = "cuda"), allow(unused_variables))]
fn run(&mut self, ids: &[u32], positions: usize) -> Result<Matrix, NetworkError> {
#[cfg(feature = "cuda")]
if let Some(context) = &self.model.device {
if self.device.is_none() {
self.device = Some(crate::gpu_model::DeviceKv::new(self.model, context, 1)?);
}
let kv = self.device.as_mut().expect("allocated above");
self.model.check_length(ids.len(), kv.len())?;
let valid = vec![1; ids.len()];
let logits = crate::gpu_model::decode(self.model, context, ids, kv, positions, &valid)?;
self.model.check_device()?;
return Ok(logits);
}
self.model.forward_cached(ids, &mut self.caches)
}
}
/// A [`Decoder`] for several sequences at once. Built by
/// [`TransformerLm::batch_decoder`].
pub struct BatchDecoder<'a> {
model: &'a TransformerLm,
/// One set of caches per sequence on the host; empty sets on a device.
caches: Vec<Vec<KvCache>>,
histories: Vec<Vec<u32>>,
/// `[sequences, vocab_size]`: each sequence's next-token logits.
logits: Option<Matrix>,
/// Sampled but not yet run, as [`Decoder`] defers it.
pending: Option<Vec<u32>>,
#[cfg(feature = "cuda")]
device: Option<crate::gpu_model::DeviceKv>,
}
impl BatchDecoder<'_> {
/// Appends `ids[s]` to sequence `s`. The prompts, the first tokens fed,
/// may differ in length; after them every call feeds every sequence the
/// same number of tokens.
///
/// On a device, a shorter prompt is padded on the left to the longest,
/// with the padding masked out of attention. Rotary positions are
/// relative, so its logits are what it would get decoded alone, up to
/// rounding; but the padding still takes cache positions, so every
/// sequence's `max_seq_len` budget is spent at the longest one's rate.
/// Padding later in the history would change the distance from earlier
/// tokens, which is why only the prompts may be uneven.
pub fn feed(&mut self, ids: &[&[u32]]) -> Result<(), NetworkError> {
if ids.len() != self.histories.len() {
return Err(NetworkError::InvalidConfig(format!(
"expected tokens for {} sequences, got {}",
self.histories.len(),
ids.len()
)));
}
let length = ids.iter().map(|sequence| sequence.len()).max().unwrap_or(0);
if length > 0 && ids.iter().any(|sequence| sequence.is_empty()) {
return Err(NetworkError::InvalidConfig(
"a batch decoder feeds every sequence at least one token, or none".into(),
));
}
let prompted = self.histories.iter().any(|history| !history.is_empty());
if prompted && ids.iter().any(|sequence| sequence.len() != length) {
return Err(NetworkError::InvalidConfig(
"only the prompts of a batch decoder may differ in length".into(),
));
}
self.catch_up()?;
if length == 0 {
return Ok(());
}
self.logits = Some(self.run(ids)?);
for (history, sequence) in self.histories.iter_mut().zip(ids) {
history.extend_from_slice(sequence);
}
Ok(())
}
/// Samples the next token of every sequence and appends it.
pub fn next(
&mut self,
sampler: &mut crate::sampling::Sampler,
) -> Result<Vec<u32>, NetworkError> {
self.catch_up()?;
let logits = self.logits.as_ref().ok_or_else(|| {
NetworkError::InvalidConfig("decoding needs a prompt fed in first".into())
})?;
let next: Vec<u32> = self
.histories
.iter_mut()
.enumerate()
.map(|(sequence, history)| {
let id = sampler.pick(logits.row(sequence), history);
history.push(id);
id
})
.collect();
self.pending = Some(next.clone());
Ok(next)
}
/// Sequence `sequence`'s next-token logits, as [`Decoder::logits`] gives
/// them. Panics past the last sequence.
pub fn logits(&mut self, sequence: usize) -> Result<&[f32], NetworkError> {
self.catch_up()?;
let logits = self.logits.as_ref().ok_or_else(|| {
NetworkError::InvalidConfig("decoding needs a prompt fed in first".into())
})?;
Ok(logits.row(sequence))
}
/// Appends `ids[s]` to sequence `s` as if [`next`](BatchDecoder::next)
/// had sampled them.
pub fn push(&mut self, ids: &[u32]) -> Result<(), NetworkError> {
if ids.len() != self.histories.len() {
return Err(NetworkError::InvalidConfig(format!(
"expected one id for each of {} sequences, got {}",
self.histories.len(),
ids.len()
)));
}
self.catch_up()?;
for (history, &id) in self.histories.iter_mut().zip(ids) {
history.push(id);
}
self.pending = Some(ids.to_vec());
Ok(())
}
/// Every id sequence `sequence` has seen. Panics past the last sequence.
pub fn history(&self, sequence: usize) -> &[u32] {
&self.histories[sequence]
}
fn catch_up(&mut self) -> Result<(), NetworkError> {
if let Some(ids) = self.pending.take() {
let ids: Vec<[u32; 1]> = ids.into_iter().map(|id| [id]).collect();
let ids: Vec<&[u32]> = ids.iter().map(|id| &id[..]).collect();
self.logits = Some(self.run(&ids)?);
}
Ok(())
}
fn run(&mut self, ids: &[&[u32]]) -> Result<Matrix, NetworkError> {
#[cfg(feature = "cuda")]
if let Some(context) = &self.model.device {
if self.device.is_none() {
self.device = Some(crate::gpu_model::DeviceKv::new(
self.model,
context,
ids.len(),
)?);
}
let kv = self.device.as_mut().expect("allocated above");
let length = ids.iter().map(|sequence| sequence.len()).max().unwrap_or(0);
self.model.check_length(length, kv.len())?;
// Position-major, the order the device cache keeps its rows in,
// with the shorter sequences padded on the left.
let (interleaved, valid): (Vec<u32>, Vec<i32>) = (0..length)
.flat_map(|position| {
ids.iter().map(move |sequence| {
match position.checked_sub(length - sequence.len()) {
Some(index) => (sequence[index], 1),
None => (0, 0),
}
})
})
.unzip();
let logits =
crate::gpu_model::decode(self.model, context, &interleaved, kv, 1, &valid)?;
self.model.check_device()?;
return Ok(logits);
}
// NOTE: the host runs the sequences one after another; batch the
// rows through `forward_cached` if host throughput ever matters.
let mut data = Vec::new();
for (sequence, caches) in ids.iter().zip(&mut self.caches) {
let logits = self.model.forward_cached(sequence, caches)?;
data.extend_from_slice(logits.row(logits.rows - 1));
}
Ok(Matrix::from_vec(ids.len(), data.len() / ids.len(), data))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::causal_lm_loss::causal_lm_loss;
use crate::sampling::Sampler;
#[test]
fn accumulating_two_half_batches_sums_the_half_gradients() {
let ids: [&[u32]; 4] = [
&[1, 2, 3, 4],
&[5, 6, 7, 8],
&[9, 10, 11, 12],
&[13, 14, 15, 16],
];
// Dense: a mixture-of-experts model's load-balancing loss is computed
// from routing fractions over whatever batch it sees, so it is not
// linear in the batch and splitting one changes it. See
// `accumulate_step`'s note.
let dense = || tiny().moe_layers(0..0).seed(3);
// One backward over all four sequences: a mean over four.
let mut whole = dense().build().unwrap();
whole.zero_grad();
whole
.accumulate_step(&TokenBatch::new(&ids).unwrap())
.unwrap();
let whole_grads: Vec<Vec<f32>> = whole
.params_mut()
.iter()
.map(|param| param.grad.data.clone())
.collect();
// Two backwards over two sequences each, nothing cleared between them.
// Each contributes a mean over two, so the sum is twice the mean over
// four -- which is exactly what `step(1.0 / parts)` divides back out.
let mut split = dense().build().unwrap();
split.zero_grad();
split
.accumulate_step(&TokenBatch::new(&ids[..2]).unwrap())
.unwrap();
split
.accumulate_step(&TokenBatch::new(&ids[2..]).unwrap())
.unwrap();
let split_grads: Vec<Vec<f32>> = split
.params_mut()
.iter()
.map(|param| param.grad.data.clone())
.collect();
assert_eq!(whole_grads.len(), split_grads.len());
let mut compared = 0usize;
for (whole_param, split_param) in whole_grads.iter().zip(&split_grads) {
for (whole_grad, split_grad) in whole_param.iter().zip(split_param) {
let tolerance = 1e-5 + 1e-3 * whole_grad.abs();
assert!(
(split_grad - 2.0 * whole_grad).abs() < tolerance,
"accumulated {split_grad} against twice the whole-batch {whole_grad}"
);
compared += 1;
}
}
assert!(compared > 1000, "only {compared} gradients compared");
}
#[test]
fn a_loss_mask_zeroes_the_masked_positions_gradient() {
let ids: [&[u32]; 2] = [&[1, 2, 3, 4], &[5, 6, 7, 8]];
let batch = TokenBatch::new(&ids).unwrap();
let grads = |model: &mut TransformerLm| -> Vec<Vec<f32>> {
model
.params_mut()
.iter()
.map(|param| param.grad.data.clone())
.collect()
};
// A mask that flags every token is the unmasked step exactly.
let mut plain = tiny().seed(3).build().unwrap();
plain.zero_grad();
plain.accumulate_step(&batch).unwrap();
let mut flagged = tiny().seed(3).build().unwrap();
flagged.zero_grad();
flagged
.accumulate_step_masked(&batch, Some(&[true; 8]))
.unwrap();
assert_eq!(grads(&mut plain), grads(&mut flagged));
// Masking the first half of every sequence leaves a different
// gradient, but one that is still finite and non-zero: the masked
// tokens went through the forward pass as context.
let mut masked = tiny().seed(3).build().unwrap();
masked.zero_grad();
let mask = [false, false, true, true, false, false, true, true];
masked.accumulate_step_masked(&batch, Some(&mask)).unwrap();
let masked_grads = grads(&mut masked);
let plain_grads = grads(&mut plain);
assert_ne!(masked_grads, plain_grads);
let total: f32 = masked_grads.iter().flatten().map(|g| g.abs()).sum();
assert!(total.is_finite() && total > 0.0, "gradient was {total}");
}
#[test]
fn a_loss_mask_that_covers_the_wrong_number_of_tokens_is_rejected() {
let batch = TokenBatch::new(&[[1u32, 2, 3, 4]]).unwrap();
let mut model = tiny().seed(3).build().unwrap();
assert!(
model
.accumulate_step_masked(&batch, Some(&[true; 3]))
.is_err()
);
}
#[test]
fn accumulating_without_zeroing_keeps_adding() {
let ids: [&[u32]; 2] = [&[1, 2, 3, 4], &[5, 6, 7, 8]];
let batch = TokenBatch::new(&ids).unwrap();
let mut model = tiny().seed(3).build().unwrap();
model.zero_grad();
model.accumulate_step(&batch).unwrap();
let once = model.params_mut()[0].grad.data.clone();
model.accumulate_step(&batch).unwrap();
let twice = model.params_mut()[0].grad.data.clone();
for (single, double) in once.iter().zip(&twice) {
assert!(
(double - 2.0 * single).abs() < 1e-5 + 1e-3 * single.abs(),
"second accumulation gave {double}, not twice {single}"
);
}
}
#[test]
fn grad_norm_matches_the_flattened_gradient() {
let mut model = tiny().build().unwrap();
model.zero_grad();
model
.accumulate_step(&TokenBatch::new(&[[1u32, 2, 3, 4]]).unwrap())
.unwrap();
let expected: f64 = model
.params_mut()
.iter()
.flat_map(|param| param.grad.data.iter())
.map(|&g| f64::from(g) * f64::from(g))
.sum();
let norm = model.grad_norm().unwrap();
assert!(norm > 0.0);
assert!((norm - expected.sqrt() as f32).abs() < 1e-5, "{norm}");
}
/// A poisoned gradient must not reach the weights or the step counter.
#[test]
fn a_non_finite_gradient_skips_the_step() {
let mut model = tiny().build().unwrap();
model.zero_grad();
model
.accumulate_step(&TokenBatch::new(&[[1u32, 2, 3, 4]]).unwrap())
.unwrap();
let before = model.blocks[0].attention.query.weight.value.clone();
model.blocks[0].attention.query.weight.grad.data[0] = f32::NAN;
assert!(model.step_clipped(1.0, 1.0).unwrap().is_nan());
assert_eq!(model.blocks[0].attention.query.weight.value, before);
assert_eq!(model.optimizer_step(), 0);
assert_eq!(model.grad_norm().unwrap(), 0.0);
}
/// Under SGD a step moves each weight by `rate * grad`, so the ratio is
/// `rate * |grad| / |w|` exactly, and the step itself is an ordinary one.
#[test]
fn update_ratios_measure_the_step_taken() {
let batch = TokenBatch::new(&[[1u32, 2, 3, 4]]).unwrap();
let mut model = tiny().optimizer(Optimizer::sgd(0.1)).build().unwrap();
model.zero_grad();
model.accumulate_step(&batch).unwrap();
let mut plain = model.clone();
let expected: Vec<f32> = model
.params_mut()
.into_iter()
.map(|param| {
let norm = |data: &[f32]| data.iter().map(|v| v * v).sum::<f32>().sqrt();
0.1 * norm(¶m.grad.data) / norm(¶m.value.data)
})
.collect();
let ratios = model.step_with_update_ratios(1.0).unwrap();
plain.step(1.0);
assert_eq!(model, plain);
assert_eq!(ratios.len(), expected.len());
for (ratio, expected) in ratios.iter().zip(&expected) {
assert!(
(ratio - expected).abs() <= 1e-4 * expected.max(1e-3),
"{ratio} vs {expected}"
);
}
assert!(ratios.iter().any(|&ratio| ratio > 0.0));
}
/// Clipping to a norm the gradients already sit under must leave the step
/// byte for byte identical to an unclipped one, and clipping to half the
/// norm must move the weights exactly half as far as clipping to the full
/// norm does.
#[test]
fn clipping_rescales_the_step_it_takes() {
let batch = TokenBatch::new(&[[1u32, 2, 3, 4]]).unwrap();
let stepped = |max_norm: Option<f32>| {
let mut model = tiny().optimizer(Optimizer::sgd(0.1)).build().unwrap();
let before = model.blocks[0].attention.query.weight.value.clone();
model.zero_grad();
model.accumulate_step(&batch).unwrap();
let norm = match max_norm {
Some(max_norm) => model.step_clipped(1.0, max_norm).unwrap(),
None => {
let norm = model.grad_norm().unwrap();
model.step(1.0);
norm
}
};
let after = &model.blocks[0].attention.query.weight.value;
let delta: Vec<f32> = after
.data
.iter()
.zip(&before.data)
.map(|(after, before)| after - before)
.collect();
(norm, delta)
};
let (norm, unclipped) = stepped(None);
assert!(norm > 0.0);
assert_eq!(stepped(Some(norm * 2.0)).1, unclipped);
let (_, half) = stepped(Some(norm / 2.0));
for (half, unclipped) in half.iter().zip(&unclipped) {
assert!((half - unclipped / 2.0).abs() < 1e-6, "{half} {unclipped}");
}
}
/// Fake quantization has to be the *same* rounding `quantize` performs,
/// or a run trained under it optimizes for arithmetic the checkpoint will
/// never do. Both models see the same batch, so the two losses agree to
/// within summation order.
#[test]
fn a_fake_quantized_forward_matches_the_quantized_model() {
let batch = TokenBatch::new(&[[1u32, 2, 3, 4, 5, 6]]).unwrap();
let mut aware = tiny().build().unwrap();
let mut rounded = aware.clone();
aware.quantization_aware(true).unwrap();
assert!(aware.is_quantization_aware());
rounded.quantize();
let aware_loss = aware.evaluate(&batch).unwrap().total();
let rounded_loss = rounded.evaluate(&batch).unwrap().total();
assert!(
(aware_loss - rounded_loss).abs() < 1e-4,
"{aware_loss} against {rounded_loss}"
);
// And it is reversible, unlike `quantize`.
aware.quantization_aware(false).unwrap();
assert!(!aware.is_quantization_aware());
assert!((aware.evaluate(&batch).unwrap().total() - aware_loss).abs() > 1e-6);
}
/// Rounding has a derivative of zero almost everywhere, so a backward
/// pass that differentiated it would learn nothing. The straight-through
/// estimator is what keeps the gradients flowing, and the weights that
/// move are the full precision ones, not the grid.
#[test]
fn a_fake_quantized_weight_still_trains_in_full_precision() {
let batch = TokenBatch::new(&[[1u32, 2, 3, 4, 5, 6]]).unwrap();
let mut model = tiny().optimizer(Optimizer::sgd(0.05)).build().unwrap();
model.quantization_aware(true).unwrap();
let before = model.blocks[0].attention.query.weight.value.clone();
model.zero_grad();
model.accumulate_step(&batch).unwrap();
assert!(model.grad_norm().unwrap() > 0.0);
model.step(1.0);
let after = &model.blocks[0].attention.query.weight.value;
assert_ne!(after.data, before.data);
// A step smaller than the grid it is rounded onto still lands
// somewhere new: the stored weight never touches the grid.
let step = after.data.iter().fold(0.0f32, |acc, v| acc.max(v.abs())) / 127.0;
let moved = after
.data
.iter()
.zip(&before.data)
.map(|(after, before)| (after - before).abs())
.fold(0.0f32, f32::max);
assert!(
moved > 0.0 && moved < step,
"moved {moved}, grid step {step}"
);
}
#[test]
fn a_quantized_model_still_generates_and_refuses_to_train() {
let mut model = tiny().build().unwrap();
let before = model
.generate(&[1, 2, 3], 4, &mut Sampler::greedy())
.unwrap();
assert!(model.quantize() > 0);
assert!(model.is_quantized());
// Rounded weights are close enough that a three-layer toy model picks
// the same greedy tokens; what matters here is that it runs at all.
let after = model
.generate(&[1, 2, 3], 4, &mut Sampler::greedy())
.unwrap();
assert_eq!(before.len(), after.len());
// One-way: the `f32` weights are gone, so anything that would write
// them out or update them has to say so rather than produce rounded
// nonsense.
assert!(model.train_step(&[[1u32, 2, 3]]).is_err());
assert!(model.save_bin("/dev/null", Precision::F32).is_err());
}
/// A 4-bit model against a float model holding the same rounded weights:
/// the block projections on the 4-bit grid, the embedding and the
/// untied head on the int8 one. Only the storage differs, so the logits
/// agree to rounding.
#[test]
fn a_4bit_model_matches_a_float_model_on_the_same_grid_and_refuses_to_train() {
use crate::quantized::{Codebook, Quantized};
let base = tiny().tie_embeddings(false).build().unwrap();
let mut reference = base.clone();
let mut quantized = base;
assert!(quantized.quantize_4bit(Codebook::Nf4) > 0);
for block in &mut reference.blocks {
for linear in block.linears_mut() {
let value = &mut linear.weight.value;
*value = Quantized::from_matrix_4bit(value, Codebook::Nf4).dequantize();
}
}
for weight in [
&mut reference.embedding.weight,
&mut reference.lm_head.as_mut().unwrap().weight,
] {
weight.value = Quantized::from_matrix(&weight.value).dequantize();
}
let ids: Vec<u32> = (0..12).map(|i| (i * 5 % 24) as u32).collect();
let mut expected = reference.decoder();
let mut actual = quantized.decoder();
expected.feed(&ids).unwrap();
actual.feed(&ids).unwrap();
let (expected, actual) = (expected.logits.unwrap(), actual.logits.unwrap());
for (got, want) in actual.data.iter().zip(&expected.data) {
assert!((got - want).abs() < 1e-4, "{got} vs {want}");
}
assert!(quantized.train_step(&[[1u32, 2, 3]]).is_err());
assert!(quantized.save_bin("/dev/null", Precision::Q8).is_err());
}
fn tiny() -> TransformerBuilder {
TransformerLm::builder()
.vocab_size(24)
.d_model(16)
.n_layers(3)
.heads(4, 2, 4)
.d_ff(32)
.moe_d_ff(12)
.experts(4, 2)
.moe_layers([1, 2])
.shared_expert(true)
.max_seq_len(32)
.seed(1234)
}
/// A device decoder against the host one, logits after every call: a
/// prompt, single tokens, then a second multi-token turn, which is the
/// case where the causal mask has to start past the cached positions.
#[cfg(feature = "cuda")]
#[test]
fn a_device_decoder_matches_the_host_decoder_or_skips_without_device() {
match crate::cuda_training::cuda_doctor(0, 8192) {
Ok(_) => {}
Err(NetworkError::Cuda(message))
if message.contains("NO_DEVICE") || message.contains("no CUDA-capable device") =>
{
crate::cuda_training::skip_without_cuda();
return;
}
Err(error) => panic!("CUDA is present but the CUDA doctor failed: {error}"),
}
// BF16 decode lands within about 1.3e-3 of the host here; an attention
// output off by half shows up near 4e-2.
for (mixed, tolerance) in [(false, 1e-3), (true, 5e-3)] {
let cpu = tiny().mixed_precision(mixed).build().unwrap();
let mut gpu = cpu.clone();
gpu.to_cuda(0, 8192).unwrap();
let mut host = cpu.decoder();
let mut device = gpu.decoder();
let turns: [&[u32]; 5] = [&[3, 8, 1, 5], &[7], &[2], &[9, 4, 11], &[6]];
for (turn, ids) in turns.iter().enumerate() {
host.feed(ids).unwrap();
device.feed(ids).unwrap();
let host_logits = host.logits.as_ref().unwrap();
let host_last = host_logits.row(host_logits.rows - 1);
let device_logits = device.logits.as_ref().unwrap();
for (index, (d, h)) in device_logits.data.iter().zip(host_last).enumerate() {
assert!(
(d - h).abs() <= tolerance,
"mixed {mixed}, turn {turn}, logit {index}: {d} on the device vs {h}"
);
}
}
}
}
/// An int8 device decoder against a host model whose projections and head
/// went through [`Param::quantize`], the same rounding. The 20-token prompt
/// takes the dequantize-and-cuBLAS route, single tokens the int8 GEMV and
/// the six-token turn its multi-pass loop over input rows.
#[cfg(feature = "cuda")]
#[test]
fn an_int8_device_decoder_matches_a_quantized_host_or_skips_without_device() {
match crate::cuda_training::cuda_doctor(0, 8192) {
Ok(_) => {}
Err(NetworkError::Cuda(message))
if message.contains("NO_DEVICE") || message.contains("no CUDA-capable device") =>
{
crate::cuda_training::skip_without_cuda();
return;
}
Err(error) => panic!("CUDA is present but the CUDA doctor failed: {error}"),
}
// BF16 decode of this model, int8 or not, lands within about 1.3e-2.
// An expert width of 16 takes the routed int8 GEMV, 12 the per-expert
// GEMMs its 16-byte loads need.
for (moe_d_ff, mixed, tolerance) in [
(12, false, 1e-3),
(12, true, 3e-2),
(16, false, 1e-3),
(16, true, 3e-2),
] {
let base = tiny()
.moe_d_ff(moe_d_ff)
.tie_embeddings(false)
.mixed_precision(mixed)
.build()
.unwrap();
let mut gpu = base.clone();
gpu.set_int8_decode(true);
gpu.to_cuda(0, 8192).unwrap();
let mut cpu = base.clone();
for block in &mut cpu.blocks {
for linear in block.linears_mut() {
linear.weight.quantize();
}
}
cpu.lm_head.as_mut().unwrap().weight.quantize();
let mut host = cpu.decoder();
let mut device = gpu.decoder();
let prompt: Vec<u32> = (0..20).map(|i| (i * 5 % 13) as u32).collect();
let turns: [&[u32]; 5] = [&prompt, &[7], &[2], &[3, 1, 4, 1, 5, 9], &[9]];
for (turn, ids) in turns.iter().enumerate() {
host.feed(ids).unwrap();
device.feed(ids).unwrap();
let host_logits = host.logits.as_ref().unwrap();
let host_last = host_logits.row(host_logits.rows - 1);
let device_logits = device.logits.as_ref().unwrap();
for (index, (d, h)) in device_logits.data.iter().zip(host_last).enumerate() {
assert!(
(d - h).abs() <= tolerance,
"width {moe_d_ff}, mixed {mixed}, turn {turn}, logit {index}: {d} on the device vs {h}"
);
}
}
}
}
/// Long enough for the device's fused single-row attention to split its
/// history over several chunks and merge them, for one and two sequences.
#[cfg(feature = "cuda")]
#[test]
fn a_long_device_decode_matches_the_host_or_skips_without_device() {
match crate::cuda_training::cuda_doctor(0, 8192) {
Ok(_) => {}
Err(NetworkError::Cuda(message))
if message.contains("NO_DEVICE") || message.contains("no CUDA-capable device") =>
{
crate::cuda_training::skip_without_cuda();
return;
}
Err(error) => panic!("CUDA is present but the CUDA doctor failed: {error}"),
}
let cpu = tiny()
.max_seq_len(200)
.mixed_precision(false)
.build()
.unwrap();
let mut gpu = cpu.clone();
gpu.to_cuda(0, 8192).unwrap();
let prompt: Vec<u32> = (0..130).map(|i| (i * 7 % 13) as u32).collect();
// The second sequence is padded by 90 positions, so whole chunks of
// its history are padding.
let prompts = [&prompt[..], &prompt[90..]];
let mut hosts = prompts.map(|_| cpu.decoder());
let mut device = gpu.batch_decoder(2).unwrap();
for (host, prompt) in hosts.iter_mut().zip(prompts) {
host.feed(prompt).unwrap();
}
device.feed(&prompts).unwrap();
for step in 0..20u32 {
let id = step % 13;
device.feed(&[&[id], &[id]]).unwrap();
let device_logits = device.logits.as_ref().unwrap();
for (sequence, host) in hosts.iter_mut().enumerate() {
host.feed(&[id]).unwrap();
let host_logits = host.logits.as_ref().unwrap();
let expected = host_logits.row(host_logits.rows - 1);
for (d, h) in device_logits.row(sequence).iter().zip(expected) {
assert!(
(d - h).abs() <= 1e-3,
"step {step}: {d} on the device vs {h}"
);
}
}
}
}
/// Feeds `batched` and one single-sequence host decoder per sequence the
/// same turns, and checks every sequence's logits agree after each. The
/// prompts differ in length, so a device pads them.
fn assert_batch_matches_single(host: &TransformerLm, batched: &TransformerLm, tolerance: f32) {
let turns: [[&[u32]; 3]; 4] = [
[&[3, 8, 1, 5], &[9, 4], &[6, 6, 0, 13, 7, 2]],
[&[7], &[2], &[10]],
[&[2, 12], &[5, 1], &[8, 3]],
[&[6], &[11], &[4]],
];
let mut batch = batched.batch_decoder(3).unwrap();
let mut singles: Vec<_> = (0..3).map(|_| host.decoder()).collect();
for (turn, ids) in turns.iter().enumerate() {
batch.feed(ids).unwrap();
let batch_logits = batch.logits.as_ref().unwrap();
for (sequence, single) in singles.iter_mut().enumerate() {
single.feed(ids[sequence]).unwrap();
let single_logits = single.logits.as_ref().unwrap();
let expected = single_logits.row(single_logits.rows - 1);
for (index, (b, h)) in batch_logits.row(sequence).iter().zip(expected).enumerate() {
assert!(
(b - h).abs() <= tolerance,
"turn {turn}, sequence {sequence}, logit {index}: {b} batched vs {h}"
);
}
}
}
assert!(batch.feed(&[&[1], &[2]]).is_err());
assert!(batch.feed(&[&[1], &[], &[4]]).is_err());
assert!(batch.feed(&[&[1], &[2, 3], &[4]]).is_err());
}
#[test]
fn a_batch_decoder_matches_one_decoder_per_sequence() {
let model = tiny().build().unwrap();
assert_batch_matches_single(&model, &model, 1e-5);
assert!(model.batch_decoder(0).is_err());
}
/// Checks per-token log-probabilities against the loss `evaluate` takes
/// over the same sequence, and each one against a decoder's logits.
fn assert_log_probabilities_match_the_loss(model: &TransformerLm, tolerance: f32) {
let ids = [3, 8, 1, 5, 9, 4, 11];
let scores = model.log_probabilities(&ids).unwrap();
assert_eq!(scores.len(), ids.len() - 1);
let loss = model
.evaluate(&TokenBatch::new(&[ids]).unwrap())
.unwrap()
.lm_loss;
let mean = -scores.iter().sum::<f32>() / scores.len() as f32;
assert!(
(mean - loss).abs() <= tolerance,
"{mean} against loss {loss}"
);
let mut decoder = model.decoder();
decoder.feed(&ids[..3]).unwrap();
let logits = decoder.logits().unwrap();
let log_sum = logits.iter().map(|l| l.exp()).sum::<f32>().ln();
let expected = logits[ids[3] as usize] - log_sum;
assert!(
(scores[2] - expected).abs() <= tolerance,
"{} against {expected}",
scores[2]
);
}
#[test]
fn log_probabilities_match_the_loss_and_the_decoder() {
assert_log_probabilities_match_the_loss(&tiny().build().unwrap(), 1e-5);
}
#[cfg(feature = "cuda")]
#[test]
fn device_log_probabilities_match_the_loss_or_skip_without_device() {
match crate::cuda_training::cuda_doctor(0, 8192) {
Ok(_) => {}
Err(err) => {
eprintln!("skipping: {err}");
return;
}
}
let mut model = tiny().build().unwrap();
model.to_cuda(0, 8192).unwrap();
assert_log_probabilities_match_the_loss(&model, 1e-3);
}
#[test]
fn beam_search_finds_the_most_probable_continuation() {
let model = tiny().build().unwrap();
let prompt = [3, 8, 1];
let greedy = model.generate(&prompt, 5, &mut Sampler::greedy()).unwrap();
assert_eq!(model.generate_beam(&prompt, 5, 1, None).unwrap(), greedy);
assert_eq!(
model.generate_beam(&prompt, 5, 1, Some(greedy[1])).unwrap(),
greedy[..2]
);
// With a beam per vocabulary id, two steps search every pair.
let log_probabilities = |history: &[u32]| {
let mut decoder = model.decoder();
decoder.feed(history).unwrap();
let logits = decoder.logits().unwrap().to_vec();
let max = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max);
let log_sum = max + logits.iter().map(|l| (l - max).exp()).sum::<f32>().ln();
logits.into_iter().map(|l| l - log_sum).collect::<Vec<_>>()
};
let first = log_probabilities(&prompt);
let mut best = (f32::NEG_INFINITY, vec![]);
for a in 0..24u32 {
let second = log_probabilities(&[3, 8, 1, a]);
for b in 0..24u32 {
let score = first[a as usize] + second[b as usize];
if score > best.0 {
best = (score, vec![a, b]);
}
}
}
assert_eq!(model.generate_beam(&prompt, 2, 24, None).unwrap(), best.1);
assert!(model.generate_beam(&prompt, 2, 0, None).is_err());
}
/// Forks a session mid-generation, continues the original and the fork
/// differently, and checks each against a fresh session fed the same ids.
fn assert_forks_continue_independently(model: &TransformerLm, tolerance: f32) {
let mut sampler = Sampler::greedy();
let mut original = model.decoder();
original.feed(&[3, 8, 1, 5]).unwrap();
original.next(&mut sampler).unwrap();
let mut fork = original.fork().unwrap();
original.feed(&[2, 9]).unwrap();
fork.feed(&[7]).unwrap();
for session in [&mut original, &mut fork] {
session.next(&mut sampler).unwrap();
let mut fresh = model.decoder();
let history = session.history().to_vec();
fresh.feed(&history).unwrap();
for (a, b) in session
.logits()
.unwrap()
.iter()
.zip(fresh.logits().unwrap())
{
assert!((a - b).abs() <= tolerance, "{a} forked vs {b} fresh");
}
}
assert_ne!(original.history(), fork.history());
}
#[test]
fn a_forked_decoder_continues_independently() {
assert_forks_continue_independently(&tiny().build().unwrap(), 1e-5);
}
#[cfg(feature = "cuda")]
#[test]
fn a_forked_device_decoder_continues_independently_or_skips_without_device() {
match crate::cuda_training::cuda_doctor(0, 8192) {
Ok(_) => {}
Err(err) => {
eprintln!("skipping: {err}");
return;
}
}
let mut model = tiny().build().unwrap();
model.to_cuda(0, 8192).unwrap();
assert_forks_continue_independently(&model, 1e-3);
}
#[test]
fn pushing_the_argmax_of_the_logits_decodes_greedily() {
let model = tiny().build().unwrap();
let argmax = |logits: &[f32]| {
(0..logits.len())
.max_by(|&a, &b| logits[a].total_cmp(&logits[b]))
.unwrap() as u32
};
let mut sampler = Sampler::greedy();
let (mut sampled, mut pushed) = (model.decoder(), model.decoder());
assert!(pushed.logits().is_err());
sampled.feed(&[3, 8, 1]).unwrap();
pushed.feed(&[3, 8, 1]).unwrap();
let mut batch = model.batch_decoder(2).unwrap();
batch.feed(&[&[3, 8, 1], &[5]]).unwrap();
for _ in 0..6 {
let id = argmax(pushed.logits().unwrap());
assert_eq!(batch.logits(0).unwrap(), pushed.logits().unwrap());
let other = argmax(batch.logits(1).unwrap());
assert_eq!(sampled.next(&mut sampler).unwrap(), id);
pushed.push(id).unwrap();
batch.push(&[id, other]).unwrap();
}
assert_eq!(pushed.history(), sampled.history());
assert_eq!(batch.history(0), sampled.history());
assert!(batch.push(&[1]).is_err());
}
#[cfg(feature = "cuda")]
#[test]
fn a_device_batch_decoder_matches_host_decoders_or_skips_without_device() {
match crate::cuda_training::cuda_doctor(0, 8192) {
Ok(_) => {}
Err(NetworkError::Cuda(message))
if message.contains("NO_DEVICE") || message.contains("no CUDA-capable device") =>
{
crate::cuda_training::skip_without_cuda();
return;
}
Err(error) => panic!("CUDA is present but the CUDA doctor failed: {error}"),
}
for (mixed, tolerance) in [(false, 1e-3), (true, 5e-2)] {
let cpu = tiny().mixed_precision(mixed).build().unwrap();
let mut gpu = cpu.clone();
gpu.to_cuda(0, 8192).unwrap();
assert_batch_matches_single(&cpu, &gpu, tolerance);
}
}
/// A prompt wide enough for the fused flash kernel (heads of 64 under
/// mixed precision, more than one 64-row tile, two sequences), even and
/// with one sequence padded by more than a tile, then single steps and a
/// 130-row turn that read the cache it filled. Measured error is under
/// 4e-3; masking only each query tile's last key tile reaches 1.4e-2.
#[cfg(feature = "cuda")]
#[test]
fn a_device_prompt_at_head_width_64_matches_the_host_or_skips_without_device() {
match crate::cuda_training::cuda_doctor(0, 8192) {
Ok(_) => {}
Err(NetworkError::Cuda(message))
if message.contains("NO_DEVICE") || message.contains("no CUDA-capable device") =>
{
crate::cuda_training::skip_without_cuda();
return;
}
Err(error) => panic!("CUDA is present but the CUDA doctor failed: {error}"),
}
let cpu = tiny()
.d_model(128)
.heads(4, 2, 64)
.max_seq_len(300)
.build()
.unwrap();
let mut gpu = cpu.clone();
gpu.to_cuda(0, 8192).unwrap();
let first: Vec<u32> = (0..130).map(|i| (i * 7 % 13) as u32).collect();
let second: Vec<u32> = (0..130).map(|i| (i * 5 % 17) as u32).collect();
for prompts in [[&first[..], &second[..]], [&first[..], &second[..40]]] {
let mut hosts = prompts.map(|_| cpu.decoder());
let mut device = gpu.batch_decoder(2).unwrap();
device.feed(&prompts).unwrap();
for (host, prompt) in hosts.iter_mut().zip(prompts) {
host.feed(prompt).unwrap();
}
for step in 0..5u32 {
// Step 2 is a second turn of several rows after the cache.
let ids: Vec<u32> = match step {
2 => (0..130).map(|i| (i * 3 % 11) as u32).collect(),
_ => vec![step],
};
let device_logits = device.logits.as_ref().unwrap();
for (sequence, host) in hosts.iter_mut().enumerate() {
let host_logits = host.logits.as_ref().unwrap();
let expected = host_logits.row(host_logits.rows - 1);
for (d, h) in device_logits.row(sequence).iter().zip(expected) {
assert!(
(d - h).abs() <= 1e-2,
"{}-token prompt, step {step}: {d} on the device vs {h}",
prompts[sequence].len()
);
}
host.feed(&ids).unwrap();
}
device.feed(&[&ids, &ids]).unwrap();
}
}
}
/// Speculative decoding against plain greedy decoding, with the target as
/// its own draft (every proposal kept) and with an unrelated draft (most
/// rejected), each run to `max_seq_len`.
fn assert_speculative_matches_greedy(target: &TransformerLm, draft: &TransformerLm) {
let prompt = [3, 1, 4];
let expected = target
.generate(&prompt, 29, &mut Sampler::greedy())
.unwrap();
for draft in [target, draft] {
for lookahead in [1, 3, 8] {
let got = target
.generate_speculative(draft, &prompt, 29, lookahead)
.unwrap();
assert_eq!(got, expected, "lookahead {lookahead}");
}
}
assert_eq!(
target.generate_speculative(draft, &prompt, 5, 0).unwrap(),
expected[..5]
);
}
/// The next-token distribution `sampler` gives `model` after `history`.
fn next_distribution(model: &TransformerLm, sampler: &Sampler, history: &[u32]) -> Vec<f32> {
let mut decoder = model.decoder();
decoder.feed(history).unwrap();
let logits = decoder.logits.unwrap();
sampler.probabilities(logits.row(logits.rows - 1), history)
}
#[test]
fn sampled_speculative_decoding_draws_from_the_target() {
let target = tiny().build().unwrap();
let draft = tiny().n_layers(1).moe_layers([]).seed(99).build().unwrap();
let mut sampler = Sampler::temperature(0.02, Some(5)).top_k(12);
let prompt = [3u32, 1, 4];
let vocab = 24;
// The first two ids' marginals under plain sampling from the target.
let first = next_distribution(&target, &sampler, &prompt);
let mut second = vec![0.0; vocab];
for (id, &weight) in first.iter().enumerate().filter(|(_, w)| **w > 0.0) {
let after = next_distribution(&target, &sampler, &[3, 1, 4, id as u32]);
for (total, p) in second.iter_mut().zip(after) {
*total += weight * p;
}
}
let distance = |a: &[f32], b: &[f32]| -> f32 {
a.iter().zip(b).map(|(a, b)| (a - b).abs()).sum::<f32>() / 2.0
};
// A draft this far from the target is what makes the check bite:
// keeping every proposal would sample the draft instead.
let drafted = next_distribution(&draft, &sampler, &prompt);
assert!(
distance(&first, &drafted) > 0.3,
"{}",
distance(&first, &drafted)
);
let trials = 4000;
let (mut seen_first, mut seen_second) = (vec![0.0; vocab], vec![0.0; vocab]);
for _ in 0..trials {
let got = target
.generate_speculative_with(&draft, &prompt, 3, 2, &mut sampler)
.unwrap();
assert_eq!(got.len(), 3);
seen_first[got[0] as usize] += 1.0 / trials as f32;
seen_second[got[1] as usize] += 1.0 / trials as f32;
}
assert!(
distance(&seen_first, &first) < 0.05,
"{}",
distance(&seen_first, &first)
);
assert!(
distance(&seen_second, &second) < 0.05,
"{}",
distance(&seen_second, &second)
);
}
#[test]
fn speculative_decoding_matches_greedy_decoding() {
let target = tiny().build().unwrap();
let draft = tiny().n_layers(1).moe_layers([]).seed(99).build().unwrap();
assert_speculative_matches_greedy(&target, &draft);
let other_vocab = tiny().vocab_size(25).build().unwrap();
assert!(
target
.generate_speculative(&other_vocab, &[1], 4, 2)
.is_err()
);
}
#[cfg(feature = "cuda")]
#[test]
fn device_speculative_decoding_matches_greedy_or_skips_without_device() {
match crate::cuda_training::cuda_doctor(0, 8192) {
Ok(_) => {}
Err(NetworkError::Cuda(message))
if message.contains("NO_DEVICE") || message.contains("no CUDA-capable device") =>
{
crate::cuda_training::skip_without_cuda();
return;
}
Err(error) => panic!("CUDA is present but the CUDA doctor failed: {error}"),
}
let mut target = tiny().build().unwrap();
let mut draft = tiny().n_layers(1).moe_layers([]).seed(99).build().unwrap();
target.to_cuda(0, 8192).unwrap();
draft.to_cuda(0, 8192).unwrap();
assert_speculative_matches_greedy(&target, &draft);
}
#[test]
fn expert_loads_report_each_moe_layer_and_sum_to_one() {
let batch = TokenBatch::new(&[vec![3u32, 8, 1, 5, 2], vec![9, 4, 0]]).unwrap();
let (_, cache) = tiny().build().unwrap().forward_batch(&batch).unwrap();
let loads = cache.expert_loads();
assert_eq!(loads.len(), 2);
for layer in &loads {
assert_eq!(layer.len(), 4);
assert!((layer.iter().sum::<f32>() - 1.0).abs() < 1e-6);
// Eight real tokens, two slots each: every share is a multiple of 1/16.
assert!(layer.iter().all(|share| (share * 16.0).fract() == 0.0));
}
let dense = tiny().moe_layers([]).build().unwrap();
assert!(
dense
.forward_batch(&batch)
.unwrap()
.1
.expert_loads()
.is_empty()
);
}
#[test]
fn masked_training_needs_a_bidirectional_model_and_drives_the_loss_down() {
use crate::masked_lm::MaskedBatch;
// Every sequence is the same, so the model can learn to reconstruct a
// hole in it from the tokens on both sides.
let sequences = [[3u32, 4, 5, 6, 7, 8], [3, 4, 5, 6, 7, 8]];
let batch = MaskedBatch::corrupt(&sequences, 24, 1, 0.3, Some(5)).unwrap();
let mut causal = tiny().optimizer(Optimizer::adam(3e-3)).build().unwrap();
let error = causal.train_step_masked(&batch).unwrap_err().to_string();
assert!(error.contains("bidirectional"), "{error}");
let mut model = tiny()
.bidirectional(true)
.optimizer(Optimizer::adam(3e-3))
.build()
.unwrap();
let first = model.train_step_masked(&batch).unwrap().lm_loss;
for _ in 0..40 {
model.train_step_masked(&batch).unwrap();
}
let last = model.evaluate_masked(&batch).unwrap().lm_loss;
assert!(last < first * 0.5, "{first} -> {last}");
}
#[test]
fn a_bidirectional_model_carries_the_flag_to_every_block_and_back_from_disk() {
let mut model = tiny().bidirectional(true).build().unwrap();
assert!(
model
.blocks
.iter()
.all(|block| !block.attention.is_causal())
);
let path = std::env::temp_dir().join("rb_bidirectional.rbw");
model.save_bin(&path, Precision::F32).unwrap();
let loaded = TransformerLm::load_bin(&path).unwrap();
std::fs::remove_file(&path).ok();
assert!(!loaded.config.causal);
assert!(
loaded
.blocks
.iter()
.all(|block| !block.attention.is_causal())
);
// Generation needs a cache, and a cache needs causality.
assert!(
loaded
.generate(&[1, 2, 3], 4, &mut crate::sampling::Sampler::greedy())
.is_err()
);
}
#[test]
fn forward_produces_one_logit_row_per_token() {
let model = tiny().build().unwrap();
let (logits, _) = model.forward_train(&[[1, 2, 3, 4]]).unwrap();
assert_eq!((logits.rows, logits.cols), (4, 24));
}
#[test]
fn the_configured_layers_are_the_moe_layers() {
let model = tiny().build().unwrap();
assert!(!model.blocks[0].feed_forward.is_moe());
assert!(model.blocks[1].feed_forward.is_moe());
assert!(model.blocks[2].feed_forward.is_moe());
}
#[test]
fn module_and_config_parameter_counts_agree() {
for tied in [true, false] {
let builder = tiny().tie_embeddings(tied);
let predicted = builder.parameter_counts();
let model = builder.build().unwrap();
assert_eq!(model.parameter_counts(), predicted, "tied: {tied}");
}
}
#[test]
fn a_sparse_model_has_more_total_than_active_parameters() {
let counts = tiny().experts(16, 2).parameter_counts();
assert!(counts.total > counts.active);
assert!(counts.sparsity_ratio() > 1.0);
}
#[test]
fn a_fully_dense_model_has_no_inactive_parameters() {
let counts = tiny().moe_layers([]).parameter_counts();
assert_eq!(counts.total, counts.active);
assert!((counts.sparsity_ratio() - 1.0).abs() < 1e-6);
}
#[test]
fn the_default_configuration_lands_in_the_fifty_million_range() {
let counts = TransformerConfig::default().parameter_counts();
assert!((40e6..80e6).contains(&(counts.total as f64)), "{counts}");
assert!((20e6..60e6).contains(&(counts.active as f64)), "{counts}");
}
#[test]
fn tying_embeddings_removes_the_output_projection() {
let tied = tiny().tie_embeddings(true).build().unwrap();
let untied = tiny().tie_embeddings(false).build().unwrap();
assert!(tied.lm_head.is_none());
assert!(untied.lm_head.is_some());
assert_eq!(
untied.parameter_counts().total - tied.parameter_counts().total,
24 * 16
);
}
#[test]
fn a_cached_decode_reproduces_the_full_sequence_forward() {
let model = tiny().build().unwrap();
let ids = [5u32, 9, 2, 17, 3];
let (expected, _) = model.forward_train(&[&ids[..]]).unwrap();
let mut caches = model.new_kv_caches();
for (position, &id) in ids.iter().enumerate() {
let logits = model.forward_cached(&[id], &mut caches).unwrap();
for (actual, expected) in logits.data.iter().zip(expected.row(position)) {
assert!(
(actual - expected).abs() < 1e-3,
"position {position}: {actual} vs {expected}"
);
}
}
}
#[test]
fn a_prefill_then_decode_reproduces_the_full_sequence_forward() {
let model = tiny().build().unwrap();
let ids = [7u32, 1, 12, 4];
let (expected, _) = model.forward_train(&[&ids[..]]).unwrap();
let mut caches = model.new_kv_caches();
model.forward_cached(&ids[..2], &mut caches).unwrap();
let logits = model.forward_cached(&ids[2..3], &mut caches).unwrap();
for (actual, expected) in logits.data.iter().zip(expected.row(2)) {
assert!((actual - expected).abs() < 1e-3);
}
}
#[test]
fn evaluate_reports_the_loss_a_step_would_and_changes_nothing() {
let mut model = tiny().build().unwrap();
let batch = TokenBatch::new(&[[1u32, 2, 3, 4], [5, 6, 7, 8]]).unwrap();
let before = model.evaluate(&batch).unwrap();
// Same value twice: evaluating must not have moved the weights.
assert_eq!(before, model.evaluate(&batch).unwrap());
// `train_step_batch` reports the loss it measured before updating, so
// the two have to agree.
let stepped = model.train_step_batch(&batch).unwrap();
assert!((before.lm_loss - stepped.lm_loss).abs() < 1e-6);
assert!(model.evaluate(&batch).unwrap().lm_loss < before.lm_loss);
assert!((before.perplexity() - before.lm_loss.exp()).abs() < 1e-4);
}
#[test]
fn greedy_generation_matches_a_hand_written_decode_loop() {
let model = tiny().build().unwrap();
let prompt = [7u32, 1, 12];
let generated = model
.generate(&prompt, 5, &mut crate::Sampler::greedy())
.unwrap();
let mut caches = model.new_kv_caches();
let mut logits = model.forward_cached(&prompt, &mut caches).unwrap();
let mut expected = Vec::new();
for _ in 0..5 {
let row = logits.row(logits.rows - 1);
let next = row
.iter()
.enumerate()
.max_by(|a, b| a.1.total_cmp(b.1))
.unwrap()
.0 as u32;
expected.push(next);
logits = model.forward_cached(&[next], &mut caches).unwrap();
}
assert_eq!(generated, expected);
}
#[test]
fn a_callback_sees_every_token_and_can_stop_the_generation() {
let model = tiny().build().unwrap();
let prompt = [7u32, 1, 12];
let mut seen = Vec::new();
let all = model
.generate_with(&prompt, 5, &mut crate::Sampler::greedy(), |id| {
seen.push(id);
true
})
.unwrap();
assert_eq!(seen, all);
assert_eq!(all.len(), 5);
// Stopping on the second token keeps it: it was sampled.
let mut count = 0;
let stopped = model
.generate_with(&prompt, 5, &mut crate::Sampler::greedy(), |_| {
count += 1;
count < 2
})
.unwrap();
assert_eq!(stopped, all[..2]);
}
#[test]
fn a_decoder_continues_across_turns_and_matches_generate() {
let model = tiny().build().unwrap();
let prompt = [7u32, 1, 12];
let expected = model
.generate(&prompt, 5, &mut crate::Sampler::greedy())
.unwrap();
let mut decoder = model.decoder();
// Sampling before a prompt has nothing to sample from.
assert!(decoder.next(&mut crate::Sampler::greedy()).is_err());
decoder.feed(&prompt).unwrap();
let mut sampler = crate::Sampler::greedy();
let generated: Vec<u32> = (0..5)
.map(|_| decoder.next(&mut sampler).unwrap())
.collect();
assert_eq!(generated, expected);
assert_eq!(decoder.history().len(), prompt.len() + 5);
// A second turn continues from the same caches, and the result is what
// a fresh generation over the whole history would have produced.
let turn = [3u32, 4];
decoder.feed(&turn).unwrap();
let after = decoder.next(&mut sampler).unwrap();
let mut whole = prompt.to_vec();
whole.extend(&generated);
whole.extend(&turn);
assert_eq!(
after,
model
.generate(&whole, 1, &mut crate::Sampler::greedy())
.unwrap()[0]
);
// Deferring the forward pass means a session can fill the context
// exactly, as `generate` can.
let mut decoder = model.decoder();
decoder.feed(&[3]).unwrap();
// 32 tokens from a one-token prompt, the same count `generate` manages,
// because the last one is never run back through the model.
for _ in 0..32 {
decoder.next(&mut sampler).unwrap();
}
assert_eq!(decoder.history().len(), 33);
assert!(decoder.next(&mut sampler).is_err());
}
#[test]
fn generation_can_fill_the_context_exactly() {
let model = tiny().build().unwrap();
// The final token needs no forward pass, so a run that ends on
// `max_seq_len` must not overflow the cache.
let generated = model
.generate(&[3], 32, &mut crate::Sampler::greedy())
.unwrap();
assert_eq!(generated.len(), 32);
assert!(
model
.generate(&[3], 33, &mut crate::Sampler::greedy())
.is_err()
);
}
#[test]
fn generation_rejects_an_empty_prompt() {
let model = tiny().build().unwrap();
assert!(
model
.generate(&[], 4, &mut crate::Sampler::greedy())
.is_err()
);
}
#[test]
fn end_to_end_backward_matches_finite_differences_on_the_embedding() {
let mut model = tiny()
.moe_layers([1])
.aux_loss_weight(0.0)
.router_z_loss_weight(0.0)
.build()
.unwrap();
let ids = [3u32, 8, 1, 5];
let (logits, cache) = model.forward_train(&[&ids[..]]).unwrap();
let loss = causal_lm_loss(&logits, &ids).unwrap();
model.zero_grad();
model.backward(&cache, &loss.grad_logits).unwrap();
let analytic = model.embedding.weight.grad.data.clone();
// Only the rows the sequence actually used can have a gradient, so the
// probe walks one of those. The step stays small because top-k routing
// is a step function: a larger nudge flips a token to another expert and
// the numeric slope then measures a jump, not a derivative.
let epsilon = 1e-4;
let row = 8usize;
for column in 0..model.config.d_model {
let index = row * model.config.d_model + column;
let mut probe = model.clone();
probe.embedding.weight.value.data[index] += epsilon;
let high = causal_lm_loss(&probe.forward_train(&[&ids[..]]).unwrap().0, &ids)
.unwrap()
.loss;
probe.embedding.weight.value.data[index] -= 2.0 * epsilon;
let low = causal_lm_loss(&probe.forward_train(&[&ids[..]]).unwrap().0, &ids)
.unwrap()
.loss;
let numeric = (high - low) / (2.0 * epsilon);
assert!(
(analytic[index] - numeric).abs() < 1e-2,
"column {column}: {} vs {numeric}",
analytic[index]
);
}
}
#[test]
fn an_unused_embedding_row_gets_no_gradient_when_untied() {
let mut model = tiny().tie_embeddings(false).build().unwrap();
let ids = [2u32, 4, 6];
let (logits, cache) = model.forward_train(&[&ids[..]]).unwrap();
let loss = causal_lm_loss(&logits, &ids).unwrap();
model.zero_grad();
model.backward(&cache, &loss.grad_logits).unwrap();
// Row 23 is never gathered, and an untied head is what writes the rest
// of the matrix, so this row must be untouched.
assert!(
model
.embedding
.weight
.grad
.row(23)
.iter()
.all(|&g| g == 0.0)
);
assert!(model.embedding.weight.grad.row(2).iter().any(|&g| g != 0.0));
}
#[test]
fn tied_embeddings_collect_gradients_from_both_ends() {
let mut model = tiny().tie_embeddings(true).build().unwrap();
let ids = [2u32, 4, 6];
let (logits, cache) = model.forward_train(&[&ids[..]]).unwrap();
let loss = causal_lm_loss(&logits, &ids).unwrap();
model.zero_grad();
model.backward(&cache, &loss.grad_logits).unwrap();
// With tying, the unembedding touches every vocabulary row, including
// ones the input never used.
assert!(
model
.embedding
.weight
.grad
.row(23)
.iter()
.any(|&g| g != 0.0)
);
}
#[test]
fn a_batched_forward_matches_one_forward_per_sequence() {
let model = tiny().build().unwrap();
let sequences: [&[u32]; 2] = [&[3, 8, 1, 5], &[7, 2]];
let (batched, _) = model.forward_train(&sequences).unwrap();
let seq_len = 4;
for (sequence, ids) in sequences.iter().enumerate() {
let (alone, _) = model.forward_train(&[*ids]).unwrap();
for position in 0..ids.len() {
let packed = batched.row((sequence * seq_len) + position);
for (left, right) in packed.iter().zip(alone.row(position)) {
assert!((left - right).abs() < 1e-4, "{left} vs {right}");
}
}
}
}
#[test]
fn a_padded_batch_loss_is_the_mean_over_every_predicted_position() {
let model = tiny()
.aux_loss_weight(0.0)
.router_z_loss_weight(0.0)
.build()
.unwrap();
let sequences: [&[u32]; 2] = [&[3, 8, 1, 5], &[7, 2]];
let batch = TokenBatch::new(&sequences).unwrap();
let (logits, _) = model.forward_batch(&batch).unwrap();
let batched = causal_lm_loss_batch(&logits, &batch).unwrap();
let mut total = 0.0;
for ids in sequences {
let (alone, _) = model.forward_train(&[ids]).unwrap();
total += causal_lm_loss(&alone, ids).unwrap().loss * (ids.len() - 1) as f32;
}
let expected = total / batch.predicted() as f32;
assert!(
(batched.loss - expected).abs() < 1e-4,
"{} vs {expected}",
batched.loss
);
}
#[test]
fn a_batched_gradient_is_the_mean_of_the_per_sequence_gradients() {
let mut model = tiny()
.aux_loss_weight(0.0)
.router_z_loss_weight(0.0)
.build()
.unwrap();
let sequences: [&[u32]; 2] = [&[3, 8, 1, 5], &[7, 2, 9, 4]];
let batch = TokenBatch::new(&sequences).unwrap();
let (logits, cache) = model.forward_batch(&batch).unwrap();
let loss = causal_lm_loss_batch(&logits, &batch).unwrap();
model.zero_grad();
model.backward(&cache, &loss.grad_logits).unwrap();
let batched = model.embedding.weight.grad.data.clone();
let mut summed = vec![0.0f32; batched.len()];
for ids in sequences {
let (alone, cache) = model.forward_train(&[ids]).unwrap();
let loss = causal_lm_loss(&alone, ids).unwrap();
model.zero_grad();
model.backward(&cache, &loss.grad_logits).unwrap();
for (total, one) in summed.iter_mut().zip(&model.embedding.weight.grad.data) {
*total += one / sequences.len() as f32;
}
}
for (left, right) in batched.iter().zip(&summed) {
assert!((left - right).abs() < 1e-5, "{left} vs {right}");
}
}
#[test]
fn a_training_step_lowers_the_loss_on_a_repeated_sequence() {
let mut model = tiny()
.optimizer(crate::optimizers::Optimizer::adam(1e-2))
.build()
.unwrap();
let ids = [1u32, 2, 3, 4, 5, 6];
let first = model.train_step(&[&ids[..]]).unwrap();
let mut last = first;
for _ in 0..20 {
last = model.train_step(&[&ids[..]]).unwrap();
}
assert!(
last.lm_loss < first.lm_loss,
"loss went from {} to {}",
first.lm_loss,
last.lm_loss
);
assert!(last.total() >= last.lm_loss);
}
#[test]
fn identical_seeds_produce_identical_models() {
let left = tiny().seed(77).build().unwrap();
let right = tiny().seed(77).build().unwrap();
assert_eq!(left, right);
assert_eq!(
left.forward_train(&[[1, 2, 3]]).unwrap().0,
right.forward_train(&[[1, 2, 3]]).unwrap().0
);
}
#[test]
fn a_binary_snapshot_round_trips_and_is_far_smaller_than_json() {
let mut model = tiny().seed(5).build().unwrap();
let dir = std::env::temp_dir();
let json = dir.join("rusting_brain_size_check.json");
let f32_path = dir.join("rusting_brain_size_check.f32.rbw");
let q8_path = dir.join("rusting_brain_size_check.q8.rbw");
model.save_json(&json).unwrap();
model.save_bin(&f32_path, Precision::F32).unwrap();
model.save_bin(&q8_path, Precision::Q8).unwrap();
let size = |path: &std::path::Path| std::fs::metadata(path).unwrap().len() as f64;
let (json_size, f32_size, q8_size) = (size(&json), size(&f32_path), size(&q8_path));
let restored = TransformerLm::load_bin(&f32_path).unwrap();
assert_eq!(restored, model, "f32 is lossless");
assert_eq!(
restored.forward_train(&[[4, 11, 2]]).unwrap().0,
model.forward_train(&[[4, 11, 2]]).unwrap().0
);
let quantized = TransformerLm::load_bin(&q8_path).unwrap();
assert_eq!(quantized.config, model.config);
let (left, right) = (
&quantized.embedding.weight.value,
&model.embedding.weight.value,
);
let scale = right.data.iter().fold(0.0f32, |acc, v| acc.max(v.abs()));
for (a, b) in left.data.iter().zip(&right.data) {
assert!(
(a - b).abs() <= scale / 127.0,
"q8 weight {a} is further than one quantization step from {b}"
);
}
for path in [&json, &f32_path, &q8_path] {
std::fs::remove_file(path).ok();
}
assert!(
f32_size < json_size / 2.5,
"f32 {f32_size} should be far under json {json_size}"
);
assert!(
q8_size < json_size / 8.0,
"q8 {q8_size} should be far under json {json_size}"
);
}
#[test]
fn a_snapshot_round_trips_and_predicts_identically() {
let model = tiny().build().unwrap();
let path = std::env::temp_dir().join("rusting_brain_transformer_round_trip.json");
model.save_json(&path).unwrap();
let restored = TransformerLm::load_json(&path).unwrap();
std::fs::remove_file(&path).ok();
assert_eq!(restored.config, model.config);
assert_eq!(restored, model);
assert_eq!(
restored.forward_train(&[[4, 11, 2]]).unwrap().0,
model.forward_train(&[[4, 11, 2]]).unwrap().0
);
}
#[test]
fn optimizer_state_round_trips_through_a_file() {
let mut model = tiny().build().unwrap();
model.train_step(&[[1, 2, 3, 4]]).unwrap();
let path = std::env::temp_dir().join("rusting_brain_optimizer_state.bin");
model.save_optimizer_state(&path).unwrap();
// A fresh model has the same shapes and zero moments, so anything that
// comes back non-zero came out of the file.
let mut restored = tiny().build().unwrap();
restored.load_optimizer_state(&path).unwrap();
std::fs::remove_file(&path).unwrap();
assert_eq!(restored.optimizer_step(), model.optimizer_step());
let mut saved = model.params_mut();
let mut loaded = restored.params_mut();
assert_eq!(saved.len(), loaded.len());
let mut moved = 0.0f32;
for (from, to) in saved.iter_mut().zip(loaded.iter_mut()) {
let (first, second) = from.moments().unwrap();
let (first, second) = (first.clone(), second.clone());
let (restored_first, restored_second) = to.moments().unwrap();
assert_eq!(&first, restored_first);
assert_eq!(&second, restored_second);
moved += first.data.iter().map(|v| v.abs()).sum::<f32>();
}
assert!(moved > 0.0, "a training step should leave non-zero moments");
}
#[test]
fn a_snapshot_survives_a_training_step() {
let mut model = tiny().build().unwrap();
model.train_step(&[[1, 2, 3, 4]]).unwrap();
let json = serde_json::to_string(&model).unwrap();
let restored: TransformerLm = serde_json::from_str(&json).unwrap();
assert_eq!(restored, model);
}
#[test]
fn a_sequence_past_the_maximum_is_rejected() {
let model = tiny().max_seq_len(4).build().unwrap();
assert!(matches!(
model.forward_train(&[[1, 2, 3, 4, 5]]),
Err(NetworkError::SequenceTooLong { length: 5, .. })
));
}
#[test]
fn a_cached_decode_past_the_maximum_is_rejected() {
let model = tiny().max_seq_len(3).build().unwrap();
let mut caches = model.new_kv_caches();
model.forward_cached(&[1, 2, 3], &mut caches).unwrap();
assert!(matches!(
model.forward_cached(&[4], &mut caches),
Err(NetworkError::SequenceTooLong { length: 4, .. })
));
}
/// The whole adapter workflow on a model with both dense and routed
/// layers: attaching changes nothing, training moves only the adapters,
/// the adapter file round-trips, and merging keeps the predictions.
#[test]
fn a_lora_adapter_trains_saves_and_merges() {
let batch = TokenBatch::new(&[[1u32, 2, 3, 4]]).unwrap();
let mut model = tiny().build().unwrap();
let base_logits = model.forward_batch(&batch).unwrap().0;
let base_params = model.parameter_counts().total;
model.add_lora(LoraConfig::new(4).alpha(8.0)).unwrap();
assert_eq!(model.forward_batch(&batch).unwrap().0, base_logits);
// A rank-4 adapter over a 16-wide toy model is not the fraction it
// would be over a real one, but it is still strictly less than the
// model, and it is all the optimizer touches.
let trainable = model.trainable_parameters();
assert!(trainable > 0 && trainable < base_params, "{trainable}");
let base_embedding = model.embedding.weight.value.clone();
model.zero_grad();
model.train_step_batch(&batch).unwrap();
model.step(1.0);
// The frozen half did not move; the adapted half did.
assert_eq!(model.embedding.weight.value, base_embedding);
let adapted = model.forward_batch(&batch).unwrap().0;
assert_ne!(adapted, base_logits);
let directory = std::env::temp_dir().join("rusting_brain_lora_test");
std::fs::create_dir_all(&directory).unwrap();
let adapter = directory.join("adapter.rbl");
model.save_lora(&adapter).unwrap();
// A fresh base model plus the adapter file predicts what the trained
// model predicts.
let mut restored = tiny().build().unwrap();
restored.add_lora(LoraConfig::new(4).alpha(8.0)).unwrap();
restored.load_lora(&adapter).unwrap();
assert_eq!(restored.forward_batch(&batch).unwrap().0, adapted);
// A rank the file does not hold is refused rather than half-loaded.
let mut wrong = tiny().build().unwrap();
wrong.add_lora(LoraConfig::new(2)).unwrap();
assert!(wrong.load_lora(&adapter).is_err());
// A full snapshot carries base and adapters, and comes back adapted.
let snapshot = directory.join("adapted.rbw");
model.save_bin(&snapshot, Precision::F32).unwrap();
let reloaded = TransformerLm::load_bin(&snapshot).unwrap();
assert!(reloaded.has_lora());
assert_eq!(reloaded.forward_batch(&batch).unwrap().0, adapted);
model.merge_lora().unwrap();
assert!(!model.has_lora());
assert_eq!(model.trainable_parameters(), base_params);
for (merged, expected) in model
.forward_batch(&batch)
.unwrap()
.0
.data
.iter()
.zip(&adapted.data)
{
assert!((merged - expected).abs() < 1e-4, "{merged} vs {expected}");
}
std::fs::remove_dir_all(&directory).ok();
}
/// A JSON snapshot carries the adapters and the configuration, but not the
/// frozen flags, so loading has to put them back.
#[test]
fn a_json_snapshot_restores_the_frozen_base() {
let directory = std::env::temp_dir().join("rusting_brain_lora_json_test");
std::fs::create_dir_all(&directory).unwrap();
let path = directory.join("adapted.json");
let mut model = tiny().build().unwrap();
model.add_lora(LoraConfig::new(4)).unwrap();
model.save_json(&path).unwrap();
let mut restored = TransformerLm::load_json(&path).unwrap();
assert!(restored.has_lora());
assert!(restored.embedding.weight.is_frozen());
assert_eq!(
restored.trainable_parameters(),
model.trainable_parameters()
);
std::fs::remove_dir_all(&directory).ok();
}
#[test]
fn an_invalid_configuration_is_rejected_before_allocation() {
assert!(tiny().heads(4, 3, 4).build().is_err());
assert!(tiny().heads(4, 2, 5).build().is_err());
assert!(tiny().moe_layers([9]).build().is_err());
assert!(tiny().experts(2, 4).build().is_err());
}
}