rightkit-qts 0.2.3

Qwen3 TTS inference (GGUF + GGML), vendored from yet-another-ai/qts v0.2.0 for RightKit
Documentation
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
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
//! TTS transformer metadata, weights, and prefill-input construction from GGUF.

use std::cmp::max;
use std::ptr::NonNull;
use std::time::{Duration, Instant};

use ggml_sys as sys;
use rand::RngExt;

use super::backend::{
    execute_graph, ggml_soft_max_ext_with_diag_mask_cache, graph_metadata_mem_size, slice_as_bytes,
    slice_as_bytes_mut, BackendKind, BackendSet, OwnedBuffer, TensorDownload, TensorUpload,
};
use crate::model::GgufFile;
use crate::{PresetSpeaker, Qwen3TtsError, TalkerKvMode};

#[derive(Debug, Clone)]
pub struct TtsTransformerConfig {
    pub text_vocab_size: i32,
    pub text_embd_dim: i32,
    pub hidden_size: i32,
    pub n_layers: i32,
    pub n_attention_heads: i32,
    pub n_key_value_heads: i32,
    pub intermediate_size: i32,
    pub head_dim: i32,
    pub rms_norm_eps: f32,
    pub rope_theta: f32,
    pub codec_vocab_size: i32,
    pub n_codebooks: i32,
    pub code_pred_layers: i32,
    pub code_pred_vocab_size: i32,
    pub codec_pad_id: i32,
    pub codec_bos_id: i32,
    pub codec_eos_id: i32,
    pub tts_bos_token_id: i32,
    pub tts_eos_token_id: i32,
    pub tts_pad_token_id: i32,
    pub codec_think_id: i32,
    pub codec_nothink_id: i32,
    pub codec_think_bos_id: i32,
    pub codec_think_eos_id: i32,
    pub english_language_id: i32,
}

impl Default for TtsTransformerConfig {
    fn default() -> Self {
        Self {
            text_vocab_size: 151_936,
            text_embd_dim: 2_048,
            hidden_size: 1_024,
            n_layers: 28,
            n_attention_heads: 16,
            n_key_value_heads: 8,
            intermediate_size: 3_072,
            head_dim: 128,
            rms_norm_eps: 1e-6,
            rope_theta: 1_000_000.0,
            codec_vocab_size: 3_072,
            n_codebooks: 16,
            code_pred_layers: 5,
            code_pred_vocab_size: 2_048,
            codec_pad_id: 2_148,
            codec_bos_id: 2_149,
            codec_eos_id: 2_150,
            tts_bos_token_id: 151_672,
            tts_eos_token_id: 151_673,
            tts_pad_token_id: 151_671,
            codec_think_id: 2_154,
            codec_nothink_id: 2_155,
            codec_think_bos_id: 2_156,
            codec_think_eos_id: 2_157,
            english_language_id: 2_050,
        }
    }
}

/// Independent code-predictor decoder geometry. Codec embeddings remain talker-wide.
#[derive(Debug, Clone)]
pub struct CodePredictorConfig {
    pub hidden_size: i32,
    pub n_layers: i32,
    pub n_attention_heads: i32,
    pub n_key_value_heads: i32,
    pub intermediate_size: i32,
    pub head_dim: i32,
    pub rms_norm_eps: f32,
    pub rope_theta: f32,
    pub vocab_size: i32,
}

pub struct TtsTransformer {
    config: TtsTransformerConfig,
    talker: TalkerWeights,
    code_pred: CodePredWeights,
    code_pred_config: CodePredictorConfig,
    speakers: std::collections::HashMap<String, i32>,
    speaker_languages: std::collections::HashMap<String, i32>,
    chinese_language_id: i32,
}

#[derive(Debug, Clone)]
pub struct PreparedPrefillInputs {
    pub prefill_embd: Vec<f32>,
    pub trailing_text_hidden: Vec<f32>,
    pub tts_pad_embed: Vec<f32>,
}

#[derive(Debug, Clone, Copy)]
pub struct PrefillConditioning<'a> {
    pub text_tokens: &'a [i32],
    pub speaker_embd: Option<&'a [f32]>,
    pub ref_codebook_0: &'a [i32],
    pub language_id: i32,
}

#[derive(Debug, Clone, Copy)]
pub struct IclPrefillConditioning<'a> {
    pub text_tokens: &'a [i32],
    pub ref_text_tokens: &'a [i32],
    pub speaker_embd: Option<&'a [f32]>,
    pub ref_code_frames: &'a [Vec<i32>],
    pub language_id: i32,
}

#[derive(Debug, Clone)]
pub struct PrefillForwardOutputs {
    pub hidden_states: Vec<f32>,
    pub logits: Vec<f32>,
    pub n_tokens: usize,
}

#[derive(Debug, Clone)]
pub struct SelectedCodecFrame {
    pub codebook_0_token: i32,
    pub codebook_tokens: Vec<i32>,
    pub hidden_state: Vec<f32>,
    pub logits: Vec<f32>,
}

/// Sub-component wall-clock breakdown within a single codec rollout.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CodecRolloutSubTimings {
    /// Talker prefill graph execution.
    pub talker_prefill: Duration,
    /// Sum of talker autoregressive step graph executions (excluding KV write-back).
    pub talker_steps: Duration,
    /// Sum of code-predictor forward passes (prefill + per-codebook steps, all frames).
    pub code_pred_total: Duration,
    /// Sum of host-side KV cache write-back (download + quantize + upload).
    pub kv_writeback: Duration,
    /// Sum of host-side KV downloads prior to quantization.
    pub kv_download: Duration,
    /// Sum of host-side quantization time for talker K/V rows.
    pub kv_quantize: Duration,
    /// Sum of cache uploads after host quantization.
    pub kv_upload: Duration,
    /// Total bytes reserved for talker K/V cache storage.
    pub talker_kv_bytes: usize,
}

#[derive(Debug, Clone)]
pub struct CodecRollout {
    pub frames: Vec<SelectedCodecFrame>,
    pub first_frame_elapsed: Duration,
    pub sub_timings: CodecRolloutSubTimings,
}

pub struct VocoderChunk {
    pub codes: Vec<i32>,
    pub n_frames: usize,
}

/// Debug capture contains generated frames only, in frame/codebook order.
struct CodecCodeDump {
    path: Option<std::path::PathBuf>,
    frames: Vec<Vec<i32>>,
}

impl CodecCodeDump {
    fn from_env() -> Result<Self, Qwen3TtsError> {
        Self::new(std::env::var_os("RIGHTKIT_QTS_DUMP_CODES").map(Into::into))
    }

    fn new(path: Option<std::path::PathBuf>) -> Result<Self, Qwen3TtsError> {
        let dump = Self {
            path,
            frames: Vec::new(),
        };
        dump.write()?;
        Ok(dump)
    }

    fn record(&mut self, codes: &[i32]) -> Result<(), Qwen3TtsError> {
        if self.path.is_some() && self.frames.len() < 32 {
            self.frames.push(codes.to_vec());
            // Persist immediately so a later generation failure retains its prefix.
            self.write()?;
        }
        Ok(())
    }

    fn write(&self) -> Result<(), Qwen3TtsError> {
        if let Some(path) = &self.path {
            // Vec<Vec<i32>> Debug syntax is a JSON array of integer arrays.
            std::fs::write(path, format!("{:?}\n", self.frames))?;
        }
        Ok(())
    }
}

#[derive(Debug, Clone)]
struct StepForwardOutputs {
    hidden_state: Vec<f32>,
    logits: Vec<f32>,
    kv_writeback_elapsed: Duration,
    kv_download_elapsed: Duration,
    kv_quantize_elapsed: Duration,
    kv_upload_elapsed: Duration,
}

#[derive(Debug, Clone)]
struct CodePredStepOutputs {
    logits: Vec<f32>,
}

struct KvWritebackTensorDownloads {
    layer_idx: usize,
    token_start: usize,
    n_tokens: usize,
    k_tensor: *mut sys::ggml_tensor,
    v_tensor: *mut sys::ggml_tensor,
    k_data: Vec<f32>,
    v_data: Vec<f32>,
}

impl TtsTransformer {
    fn retain_projected_predictor_hidden(&self, hidden: *mut sys::ggml_tensor) {
        #[cfg(test)]
        if std::env::var_os("QTS_REPLAY_RECYCLE_HIDDEN").is_some() {
            return;
        }
        if self.code_pred.projection.is_some() {
            // The 1.7B predictor consumes this download after graph execution.
            // A graph root alone does not prevent gallocr from recycling it
            // after the codec head reads it. Preserve legacy 0.6B allocation.
            unsafe { sys::ggml_set_output(hidden) };
        }
    }

    fn mask_early_projected_eos(&self, logits: &mut [f32], generated_frames: usize) {
        // Official generate uses min_new_tokens=2. Keep legacy Base sampling.
        if self.code_pred.projection.is_some() && generated_frames < 2 {
            logits[self.config.codec_eos_id as usize] = f32::NEG_INFINITY;
        }
    }

    fn recent_codebook0_tokens_from_frames(frames: &[SelectedCodecFrame]) -> Vec<i32> {
        frames.iter().map(|frame| frame.codebook_0_token).collect()
    }

    fn recent_codebook0_tokens_from_prompt(prompt_frames: &[Vec<i32>]) -> Vec<i32> {
        prompt_frames
            .iter()
            .filter_map(|frame| frame.first().copied())
            .collect()
    }

    pub fn load_from_gguf(file: &GgufFile) -> Result<Self, Qwen3TtsError> {
        Self::load_from_ggufs(file, file)
    }

    /// Load talker & predictor from bundled or separate QTS GGUFs.
    pub fn load_from_ggufs(file: &GgufFile, predictor: &GgufFile) -> Result<Self, Qwen3TtsError> {
        let mut cfg = TtsTransformerConfig::default();
        cfg.text_vocab_size = get_u32_any(
            file,
            &["qwen3-tts.text.vocab_size", "qwen3-tts.text_vocab_size"],
            cfg.text_vocab_size,
        );
        cfg.text_embd_dim = get_u32_any(
            file,
            &["qwen3-tts.text.embedding_dim", "qwen3-tts.text_hidden_size"],
            cfg.text_embd_dim,
        );
        cfg.hidden_size = get_u32_any(
            file,
            &[
                "qwen3-tts.talker.embedding_length",
                "qwen3-tts.talker.hidden_size",
                "qwen3-tts.embedding_length",
            ],
            file.tensor_info("talker.output_norm.weight")
                .ok()
                .and_then(|info| info.dims.first().copied())
                .unwrap_or(cfg.hidden_size as usize) as i32,
        );
        cfg.n_layers = get_u32_any(
            file,
            &["qwen3-tts.talker.block_count", "qwen3-tts.block_count"],
            cfg.n_layers,
        );
        cfg.n_attention_heads = get_u32_any(
            file,
            &[
                "qwen3-tts.talker.attention.head_count",
                "qwen3-tts.attention.head_count",
            ],
            cfg.n_attention_heads,
        );
        cfg.n_key_value_heads = get_u32_any(
            file,
            &[
                "qwen3-tts.talker.attention.head_count_kv",
                "qwen3-tts.attention.head_count_kv",
            ],
            cfg.n_key_value_heads,
        );
        cfg.intermediate_size = get_u32_any(
            file,
            &[
                "qwen3-tts.talker.feed_forward_length",
                "qwen3-tts.feed_forward_length",
            ],
            cfg.intermediate_size,
        );
        cfg.head_dim = get_u32_any(
            file,
            &[
                "qwen3-tts.talker.attention.key_length",
                "qwen3-tts.attention.key_length",
            ],
            cfg.head_dim,
        );
        cfg.rms_norm_eps = get_f32_any(
            file,
            &[
                "qwen3-tts.talker.attention.layer_norm_rms_epsilon",
                "qwen3-tts.attention.layer_norm_rms_epsilon",
            ],
            cfg.rms_norm_eps,
        );
        cfg.rope_theta = get_f32_any(
            file,
            &[
                "qwen3-tts.talker.rope.freq_base",
                "qwen3-tts.rope.freq_base",
            ],
            cfg.rope_theta,
        );
        cfg.codec_vocab_size = get_u32_any(
            file,
            &["qwen3-tts.talker.codec_vocab_size", "qwen3-tts.vocab_size"],
            cfg.codec_vocab_size,
        );
        cfg.n_codebooks = get_u32_any(
            file,
            &[
                "qwen3-tts.talker.num_codebooks",
                "qwen3-tts.num_code_groups",
            ],
            cfg.n_codebooks,
        );
        cfg.code_pred_layers = get_u32_any(
            file,
            &[
                "qwen3-tts.code_pred.layer_count",
                "qwen3-tts.code_predictor.layer_count",
            ],
            cfg.code_pred_layers,
        );
        cfg.code_pred_vocab_size = get_u32_any(
            file,
            &[
                "qwen3-tts.code_pred.vocab_size",
                "qwen3-tts.code_predictor.vocab_size",
            ],
            cfg.code_pred_vocab_size,
        );
        cfg.codec_pad_id = get_u32_any(file, &["qwen3-tts.codec.pad_id"], cfg.codec_pad_id);
        cfg.codec_bos_id = get_u32_any(file, &["qwen3-tts.codec.bos_id"], cfg.codec_bos_id);
        cfg.codec_eos_id = get_u32_any(
            file,
            &["qwen3-tts.codec.eos_id", "qwen3-tts.codec.eos_token_id"],
            cfg.codec_eos_id,
        );
        cfg.tts_bos_token_id = get_u32_any(
            file,
            &[
                "qwen3-tts.tts_bos_token_id",
                "qwen3-tts.tts.bos_token_id",
                "qwen3-tts.tts.bos_id",
            ],
            cfg.tts_bos_token_id,
        );
        cfg.tts_eos_token_id = get_u32_any(
            file,
            &[
                "qwen3-tts.tts_eos_token_id",
                "qwen3-tts.tts.eos_token_id",
                "qwen3-tts.tts.eos_id",
            ],
            cfg.tts_eos_token_id,
        );
        cfg.tts_pad_token_id = get_u32_any(
            file,
            &[
                "qwen3-tts.tts_pad_token_id",
                "qwen3-tts.tts.pad_token_id",
                "qwen3-tts.tts.pad_id",
            ],
            cfg.tts_pad_token_id,
        );
        cfg.codec_think_id = get_u32_any(
            file,
            &["qwen3-tts.codec.think_id", "qwen3-tts.codec_think_id"],
            cfg.codec_think_id,
        );
        cfg.codec_nothink_id = get_u32_any(
            file,
            &["qwen3-tts.codec.nothink_id", "qwen3-tts.codec_nothink_id"],
            cfg.codec_nothink_id,
        );
        cfg.codec_think_bos_id = get_u32_any(
            file,
            &[
                "qwen3-tts.codec.think_bos_id",
                "qwen3-tts.codec_think_bos_id",
            ],
            cfg.codec_think_bos_id,
        );
        cfg.codec_think_eos_id = get_u32_any(
            file,
            &[
                "qwen3-tts.codec.think_eos_id",
                "qwen3-tts.codec_think_eos_id",
            ],
            cfg.codec_think_eos_id,
        );
        cfg.english_language_id = get_u32_any(
            file,
            &[
                "qwen3-tts.language.english_id",
                "qwen3-tts.codec.language.english_id",
                "qwen3-tts.language_id",
            ],
            cfg.english_language_id,
        );

        let code_pred_config = predictor_config(predictor, &cfg)?;
        cfg.code_pred_layers = code_pred_config.n_layers;
        cfg.code_pred_vocab_size = code_pred_config.vocab_size;
        let speakers = load_speaker_table(file, cfg.codec_vocab_size)?;
        let speaker_languages = load_speaker_languages(file)?;
        let chinese_language_id =
            get_u32_any(file, &["qwen3-tts.talker.codec_language_id.chinese"], 2055);
        let talker_backends = BackendSet::new()?;
        let code_pred_backends = BackendSet::new()?;
        let talker = TalkerWeights::load(file, &cfg, talker_backends)?;
        let code_pred =
            CodePredWeights::load(predictor, file, &cfg, &code_pred_config, code_pred_backends)?;

        Ok(Self {
            config: cfg,
            talker,
            code_pred,
            code_pred_config,
            speakers,
            speaker_languages,
            chinese_language_id,
        })
    }

    #[must_use]
    pub fn config(&self) -> &TtsTransformerConfig {
        &self.config
    }

    /// Predictor geometry; legacy `config()` remains talker geometry.
    #[must_use]
    pub fn code_predictor_config(&self) -> &CodePredictorConfig {
        &self.code_pred_config
    }

    pub fn preset_speaker_id(&self, speaker: PresetSpeaker) -> Result<i32, Qwen3TtsError> {
        self.speakers.get(speaker.as_str()).copied().ok_or_else(|| {
            Qwen3TtsError::InvalidInput(format!(
                "preset speaker '{}' missing from GGUF speaker table",
                speaker.as_str()
            ))
        })
    }

    pub fn preset_speaker_embedding(
        &self,
        speaker: PresetSpeaker,
        thread_count: usize,
    ) -> Result<Vec<f32>, Qwen3TtsError> {
        self.lookup_codec_embedding_rows(&[self.preset_speaker_id(speaker)?], thread_count)
    }

    pub(crate) fn preset_language_id(&self, speaker: PresetSpeaker, language_id: i32) -> i32 {
        if language_id < 0 || language_id == self.chinese_language_id {
            self.speaker_languages
                .get(speaker.as_str())
                .copied()
                .unwrap_or(language_id)
        } else {
            language_id
        }
    }

    /// Prepend projected instruction tokens without disturbing assistant/codec alignment.
    pub fn prepend_instruction(
        &self,
        inputs: &mut PreparedPrefillInputs,
        tokens: &[i32],
        thread_count: usize,
    ) -> Result<(), Qwen3TtsError> {
        if !tokens.is_empty() {
            let mut prefix = self.project_text_tokens(tokens, thread_count)?;
            prefix.extend_from_slice(&inputs.prefill_embd);
            inputs.prefill_embd = prefix;
        }
        Ok(())
    }

    #[must_use]
    pub fn primary_backend_kind(&self) -> BackendKind {
        self.talker._backends.primary_kind()
    }

    pub fn build_prefill_inputs(
        &self,
        conditioning: PrefillConditioning<'_>,
        thread_count: usize,
    ) -> Result<PreparedPrefillInputs, Qwen3TtsError> {
        self.build_prefill_inputs_with_text_mode(conditioning, thread_count, false)
    }

    /// Match the official CustomVoice/VoiceDesign wrappers' non-streaming text mode.
    pub(crate) fn build_non_streaming_prefill_inputs(
        &self,
        conditioning: PrefillConditioning<'_>,
        thread_count: usize,
    ) -> Result<PreparedPrefillInputs, Qwen3TtsError> {
        self.build_prefill_inputs_with_text_mode(conditioning, thread_count, true)
    }

    fn build_prefill_inputs_with_text_mode(
        &self,
        conditioning: PrefillConditioning<'_>,
        thread_count: usize,
        non_streaming_mode: bool,
    ) -> Result<PreparedPrefillInputs, Qwen3TtsError> {
        let text_tokens = conditioning.text_tokens;
        let speaker_embd = conditioning.speaker_embd;
        let ref_codebook_0 = conditioning.ref_codebook_0;
        let language_id = conditioning.language_id;
        if text_tokens.len() < 4 {
            return Err(Qwen3TtsError::InvalidInput(
                "need at least 4 text tokens for prefill".into(),
            ));
        }

        let hidden_size = self.config.hidden_size as usize;
        if let Some(speaker_embd) = speaker_embd {
            if speaker_embd.len() != hidden_size {
                return Err(Qwen3TtsError::InvalidInput(format!(
                    "speaker embedding must have {hidden_size} elements"
                )));
            }
        }
        for &token in ref_codebook_0 {
            if token < 0 || token >= self.config.codec_vocab_size {
                return Err(Qwen3TtsError::InvalidInput(format!(
                    "reference codec token {token} out of range 0..{}",
                    self.config.codec_vocab_size - 1
                )));
            }
        }

        let special_tokens = [
            self.config.tts_bos_token_id,
            self.config.tts_eos_token_id,
            self.config.tts_pad_token_id,
        ];
        let mut projected_text_tokens =
            Vec::with_capacity(special_tokens.len() + text_tokens.len());
        projected_text_tokens.extend_from_slice(&special_tokens);
        projected_text_tokens.extend_from_slice(text_tokens);
        let projected_text = self.project_text_tokens(&projected_text_tokens, thread_count)?;
        let special_proj = &projected_text[..hidden_size * special_tokens.len()];
        let text_proj = &projected_text[hidden_size * special_tokens.len()..];
        let tts_bos_embed = special_proj[0..hidden_size].to_vec();
        let tts_eos_embed = special_proj[hidden_size..hidden_size * 2].to_vec();
        let tts_pad_embed = special_proj[hidden_size * 2..hidden_size * 3].to_vec();
        let role_embed = text_proj[..hidden_size * 3].to_vec();

        let codec_prefill_tokens = if language_id < 0 {
            vec![
                self.config.codec_nothink_id,
                self.config.codec_think_bos_id,
                self.config.codec_think_eos_id,
            ]
        } else {
            vec![
                self.config.codec_think_id,
                self.config.codec_think_bos_id,
                language_id,
                self.config.codec_think_eos_id,
            ]
        };
        let codec_tail_tokens = [self.config.codec_pad_id, self.config.codec_bos_id];
        let mut all_codec_tokens = Vec::with_capacity(
            codec_prefill_tokens.len() + ref_codebook_0.len() + codec_tail_tokens.len(),
        );
        all_codec_tokens.extend_from_slice(&codec_prefill_tokens);
        all_codec_tokens.extend_from_slice(ref_codebook_0);
        all_codec_tokens.extend_from_slice(&codec_tail_tokens);
        let all_codec_embed = self.lookup_codec_embedding_rows(&all_codec_tokens, thread_count)?;
        let codec_prefill_embed_len = codec_prefill_tokens.len() * hidden_size;
        let codec_prompt_embed_len = ref_codebook_0.len() * hidden_size;
        let codec_prefill_embed = &all_codec_embed[..codec_prefill_embed_len];
        let codec_prompt_embed = &all_codec_embed
            [codec_prefill_embed_len..codec_prefill_embed_len + codec_prompt_embed_len];
        let codec_tail_embed = &all_codec_embed[codec_prefill_embed_len + codec_prompt_embed_len..];

        let codec_input_len = codec_prefill_tokens.len()
            + ref_codebook_0.len()
            + usize::from(speaker_embd.is_some())
            + 2;
        let mut codec_input_embedding = vec![0.0f32; codec_input_len * hidden_size];
        codec_input_embedding[..codec_prefill_embed.len()].copy_from_slice(codec_prefill_embed);
        let mut dst_token = codec_prefill_tokens.len();

        if !codec_prompt_embed.is_empty() {
            let dst = &mut codec_input_embedding
                [dst_token * hidden_size..(dst_token + ref_codebook_0.len()) * hidden_size];
            dst.copy_from_slice(codec_prompt_embed);
            dst_token += ref_codebook_0.len();
        }

        if let Some(speaker_embd) = speaker_embd {
            let dst =
                &mut codec_input_embedding[dst_token * hidden_size..(dst_token + 1) * hidden_size];
            dst.copy_from_slice(speaker_embd);
            dst_token += 1;
        }

        codec_input_embedding[dst_token * hidden_size..(dst_token + 2) * hidden_size]
            .copy_from_slice(codec_tail_embed);

        let codec_plus_overlay_len = codec_input_len - 1;
        let mut codec_plus_overlay = vec![0.0f32; codec_plus_overlay_len * hidden_size];
        for token_idx in 0..codec_plus_overlay_len {
            let overlay = if token_idx == codec_plus_overlay_len - 1 {
                &tts_bos_embed
            } else {
                &tts_pad_embed
            };
            let codec_row =
                &codec_input_embedding[token_idx * hidden_size..(token_idx + 1) * hidden_size];
            let out_row =
                &mut codec_plus_overlay[token_idx * hidden_size..(token_idx + 1) * hidden_size];
            for h in 0..hidden_size {
                out_row[h] = overlay[h] + codec_row[h];
            }
        }

        let first_text_embed = &text_proj[3 * hidden_size..4 * hidden_size];
        let codec_bos_embed = &codec_input_embedding
            [(codec_input_len - 1) * hidden_size..codec_input_len * hidden_size];
        if non_streaming_mode {
            if text_tokens.len() < 9 {
                return Err(Qwen3TtsError::InvalidInput(
                    "non-streaming text prompt must contain at least one text token".into(),
                ));
            }
            // input_id[:, 3:-5] + TTS EOS, each overlaid on codec PAD;
            // then TTS PAD + codec BOS. No text is injected into later frames.
            let codec_pad_embed = &codec_tail_embed[..hidden_size];
            let content = &text_proj[3 * hidden_size..(text_tokens.len() - 5) * hidden_size];
            let mut prefill_embd = role_embed;
            prefill_embd.extend_from_slice(&codec_plus_overlay);
            for row in content
                .chunks_exact(hidden_size)
                .chain(std::iter::once(tts_eos_embed.as_slice()))
            {
                prefill_embd.extend(
                    row.iter()
                        .zip(codec_pad_embed)
                        .map(|(text, codec)| text + codec),
                );
            }
            prefill_embd.extend(
                tts_pad_embed
                    .iter()
                    .zip(codec_bos_embed)
                    .map(|(text, codec)| text + codec),
            );
            return Ok(PreparedPrefillInputs {
                prefill_embd,
                trailing_text_hidden: tts_pad_embed.clone(),
                tts_pad_embed,
            });
        }
        let mut first_text_plus_codec_bos = vec![0.0f32; hidden_size];
        for h in 0..hidden_size {
            first_text_plus_codec_bos[h] = first_text_embed[h] + codec_bos_embed[h];
        }

        let prefill_len = 3 + codec_plus_overlay_len + 1;
        let mut prefill_embd = vec![0.0f32; prefill_len * hidden_size];
        prefill_embd[..role_embed.len()].copy_from_slice(&role_embed);
        let codec_offset = 3 * hidden_size;
        prefill_embd[codec_offset..codec_offset + codec_plus_overlay.len()]
            .copy_from_slice(&codec_plus_overlay);
        let final_offset = (prefill_len - 1) * hidden_size;
        prefill_embd[final_offset..final_offset + hidden_size]
            .copy_from_slice(&first_text_plus_codec_bos);

        let trailing_token_count = text_tokens.len().saturating_sub(9);
        let trailing_text_proj = if trailing_token_count > 0 {
            text_proj[4 * hidden_size..(4 + trailing_token_count) * hidden_size].to_vec()
        } else {
            Vec::new()
        };

        let trailing_len = trailing_token_count + 1;
        let mut trailing_text_hidden = vec![0.0f32; trailing_len * hidden_size];
        if !trailing_text_proj.is_empty() {
            trailing_text_hidden[..trailing_text_proj.len()].copy_from_slice(&trailing_text_proj);
        }
        let trailing_eos_offset = (trailing_len - 1) * hidden_size;
        trailing_text_hidden[trailing_eos_offset..trailing_eos_offset + hidden_size]
            .copy_from_slice(&tts_eos_embed);

        Ok(PreparedPrefillInputs {
            prefill_embd,
            trailing_text_hidden,
            tts_pad_embed,
        })
    }

    pub fn build_icl_prefill_inputs(
        &self,
        conditioning: IclPrefillConditioning<'_>,
        thread_count: usize,
    ) -> Result<PreparedPrefillInputs, Qwen3TtsError> {
        let text_tokens = conditioning.text_tokens;
        let ref_text_tokens = conditioning.ref_text_tokens;
        let ref_code_frames = conditioning.ref_code_frames;
        let speaker_embd = conditioning.speaker_embd;
        let language_id = conditioning.language_id;
        if text_tokens.len() < 9 {
            return Err(Qwen3TtsError::InvalidInput(
                "ICL target text prompt must contain at least one text token".into(),
            ));
        }
        if ref_text_tokens.len() < 6 {
            return Err(Qwen3TtsError::InvalidInput(
                "ICL reference text prompt must contain at least one text token".into(),
            ));
        }

        let hidden_size = self.config.hidden_size as usize;
        if let Some(speaker_embd) = speaker_embd {
            if speaker_embd.len() != hidden_size {
                return Err(Qwen3TtsError::InvalidInput(format!(
                    "speaker embedding must have {hidden_size} elements"
                )));
            }
        }
        for frame in ref_code_frames {
            self.validate_codebook_frame(frame)?;
        }

        let special_tokens = [
            self.config.tts_bos_token_id,
            self.config.tts_eos_token_id,
            self.config.tts_pad_token_id,
        ];
        let special_proj = self.project_text_tokens(&special_tokens, thread_count)?;
        let tts_bos_embed = special_proj[0..hidden_size].to_vec();
        let tts_eos_embed = special_proj[hidden_size..hidden_size * 2].to_vec();
        let tts_pad_embed = special_proj[hidden_size * 2..hidden_size * 3].to_vec();

        let role_embed = self.project_text_tokens(&text_tokens[..3], thread_count)?;
        let target_text_tokens = &text_tokens[3..text_tokens.len() - 5];
        let ref_text_tokens = &ref_text_tokens[3..ref_text_tokens.len() - 2];
        let mut icl_text_tokens =
            Vec::with_capacity(ref_text_tokens.len() + target_text_tokens.len());
        icl_text_tokens.extend_from_slice(ref_text_tokens);
        icl_text_tokens.extend_from_slice(target_text_tokens);
        let mut text_embed = self.project_text_tokens(&icl_text_tokens, thread_count)?;
        text_embed.extend_from_slice(&tts_eos_embed);

        let codec_prefill_tokens = if language_id < 0 {
            vec![
                self.config.codec_nothink_id,
                self.config.codec_think_bos_id,
                self.config.codec_think_eos_id,
            ]
        } else {
            vec![
                self.config.codec_think_id,
                self.config.codec_think_bos_id,
                language_id,
                self.config.codec_think_eos_id,
            ]
        };
        let codec_tail_tokens = [self.config.codec_pad_id, self.config.codec_bos_id];
        let mut all_codec_tokens =
            Vec::with_capacity(codec_prefill_tokens.len() + codec_tail_tokens.len());
        all_codec_tokens.extend_from_slice(&codec_prefill_tokens);
        all_codec_tokens.extend_from_slice(&codec_tail_tokens);
        let all_codec_embed = self.lookup_codec_embedding_rows(&all_codec_tokens, thread_count)?;
        let codec_prefill_embed_len = codec_prefill_tokens.len() * hidden_size;
        let codec_prefill_embed = &all_codec_embed[..codec_prefill_embed_len];
        let codec_tail_embed = &all_codec_embed[codec_prefill_embed_len..];

        let codec_input_len = codec_prefill_tokens.len() + usize::from(speaker_embd.is_some()) + 2;
        let mut codec_input_embedding = vec![0.0f32; codec_input_len * hidden_size];
        codec_input_embedding[..codec_prefill_embed.len()].copy_from_slice(codec_prefill_embed);
        let mut dst_token = codec_prefill_tokens.len();

        if let Some(speaker_embd) = speaker_embd {
            let dst =
                &mut codec_input_embedding[dst_token * hidden_size..(dst_token + 1) * hidden_size];
            dst.copy_from_slice(speaker_embd);
            dst_token += 1;
        }

        codec_input_embedding[dst_token * hidden_size..(dst_token + 2) * hidden_size]
            .copy_from_slice(codec_tail_embed);

        let codec_plus_overlay_len = codec_input_len - 1;
        let mut codec_plus_overlay = vec![0.0f32; codec_plus_overlay_len * hidden_size];
        for token_idx in 0..codec_plus_overlay_len {
            let overlay = if token_idx == codec_plus_overlay_len - 1 {
                &tts_bos_embed
            } else {
                &tts_pad_embed
            };
            let codec_row =
                &codec_input_embedding[token_idx * hidden_size..(token_idx + 1) * hidden_size];
            let out_row =
                &mut codec_plus_overlay[token_idx * hidden_size..(token_idx + 1) * hidden_size];
            for h in 0..hidden_size {
                out_row[h] = overlay[h] + codec_row[h];
            }
        }

        let codec_bos_embed = &codec_input_embedding
            [(codec_input_len - 1) * hidden_size..codec_input_len * hidden_size];
        let codec_len = ref_code_frames.len() + 1;
        let mut codec_embed = vec![0.0f32; codec_len * hidden_size];
        codec_embed[..hidden_size].copy_from_slice(codec_bos_embed);
        for (frame_idx, frame) in ref_code_frames.iter().enumerate() {
            let row = self.sum_codec_frame_embeddings(frame, thread_count)?;
            let dst = (frame_idx + 1) * hidden_size..(frame_idx + 2) * hidden_size;
            codec_embed[dst].copy_from_slice(&row);
        }

        let text_len = text_embed.len() / hidden_size;
        let mut icl_input_embed = vec![0.0f32; codec_len * hidden_size];
        if text_len > codec_len {
            for row_idx in 0..codec_len {
                let text_row = &text_embed[row_idx * hidden_size..(row_idx + 1) * hidden_size];
                let codec_row = &codec_embed[row_idx * hidden_size..(row_idx + 1) * hidden_size];
                let out_row =
                    &mut icl_input_embed[row_idx * hidden_size..(row_idx + 1) * hidden_size];
                for h in 0..hidden_size {
                    out_row[h] = text_row[h] + codec_row[h];
                }
            }
        } else {
            for row_idx in 0..codec_len {
                let text_row = if row_idx < text_len {
                    &text_embed[row_idx * hidden_size..(row_idx + 1) * hidden_size]
                } else {
                    &tts_pad_embed
                };
                let codec_row = &codec_embed[row_idx * hidden_size..(row_idx + 1) * hidden_size];
                let out_row =
                    &mut icl_input_embed[row_idx * hidden_size..(row_idx + 1) * hidden_size];
                for h in 0..hidden_size {
                    out_row[h] = text_row[h] + codec_row[h];
                }
            }
        }

        let trailing_text_hidden = if text_len > codec_len {
            text_embed[codec_len * hidden_size..].to_vec()
        } else {
            tts_pad_embed.clone()
        };

        let prefill_len = 3 + codec_plus_overlay_len + codec_len;
        let mut prefill_embd = vec![0.0f32; prefill_len * hidden_size];
        prefill_embd[..role_embed.len()].copy_from_slice(&role_embed);
        let codec_offset = 3 * hidden_size;
        prefill_embd[codec_offset..codec_offset + codec_plus_overlay.len()]
            .copy_from_slice(&codec_plus_overlay);
        let icl_offset = codec_offset + codec_plus_overlay.len();
        prefill_embd[icl_offset..icl_offset + icl_input_embed.len()]
            .copy_from_slice(&icl_input_embed);

        Ok(PreparedPrefillInputs {
            prefill_embd,
            trailing_text_hidden,
            tts_pad_embed,
        })
    }

    pub fn forward_prefill(
        &self,
        prefill_embd: &[f32],
        thread_count: usize,
    ) -> Result<PrefillForwardOutputs, Qwen3TtsError> {
        let hidden_size = self.config.hidden_size as usize;
        if prefill_embd.is_empty() || !prefill_embd.len().is_multiple_of(hidden_size) {
            return Err(Qwen3TtsError::InvalidInput(
                "prefill embedding shape is invalid".into(),
            ));
        }

        let n_tokens = prefill_embd.len() / hidden_size;
        let graph_nodes = 4096;
        let ctx = ComputeContext::new_graph(graph_nodes)?;
        let graph = unsafe { sys::ggml_new_graph_custom(ctx.as_ptr(), graph_nodes, false) };
        let graph = NonNull::new(graph).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("failed to allocate prefill graph".into())
        })?;

        let inp_prefill_embd = unsafe {
            sys::ggml_new_tensor_2d(
                ctx.as_ptr(),
                sys::ggml_type_GGML_TYPE_F32,
                hidden_size as i64,
                n_tokens as i64,
            )
        };
        let inp_prefill_embd = NonNull::new(inp_prefill_embd).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("failed to allocate prefill input".into())
        })?;

        let inp_pos = unsafe {
            sys::ggml_new_tensor_1d(ctx.as_ptr(), sys::ggml_type_GGML_TYPE_I32, n_tokens as i64)
        };
        let inp_pos = NonNull::new(inp_pos).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("failed to allocate position input".into())
        })?;
        let positions = (0..n_tokens as i32).collect::<Vec<_>>();

        let mut inp_l = inp_prefill_embd.as_ptr();
        let kq_scale = 1.0f32 / (self.config.head_dim as f32).sqrt();
        let mut attn_softmax_mask: Option<(*mut sys::ggml_tensor, Vec<f32>)> = None;

        for layer in &self.talker.layers {
            let mut cur =
                unsafe { sys::ggml_rms_norm(ctx.as_ptr(), inp_l, self.config.rms_norm_eps) };
            cur = unsafe { sys::ggml_mul(ctx.as_ptr(), cur, layer.attn_norm.as_ptr()) };

            let mut q_cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.attn_q.as_ptr(), cur) };
            let mut k_cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.attn_k.as_ptr(), cur) };
            let mut v_cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.attn_v.as_ptr(), cur) };

            q_cur = unsafe {
                sys::ggml_reshape_3d(
                    ctx.as_ptr(),
                    q_cur,
                    self.config.head_dim as i64,
                    self.config.n_attention_heads as i64,
                    n_tokens as i64,
                )
            };
            k_cur = unsafe {
                sys::ggml_reshape_3d(
                    ctx.as_ptr(),
                    k_cur,
                    self.config.head_dim as i64,
                    self.config.n_key_value_heads as i64,
                    n_tokens as i64,
                )
            };
            v_cur = unsafe {
                sys::ggml_reshape_3d(
                    ctx.as_ptr(),
                    v_cur,
                    self.config.head_dim as i64,
                    self.config.n_key_value_heads as i64,
                    n_tokens as i64,
                )
            };

            if let Some(attn_q_norm) = layer.attn_q_norm {
                q_cur =
                    unsafe { sys::ggml_rms_norm(ctx.as_ptr(), q_cur, self.config.rms_norm_eps) };
                q_cur = unsafe { sys::ggml_mul(ctx.as_ptr(), q_cur, attn_q_norm.as_ptr()) };
            }
            if let Some(attn_k_norm) = layer.attn_k_norm {
                k_cur =
                    unsafe { sys::ggml_rms_norm(ctx.as_ptr(), k_cur, self.config.rms_norm_eps) };
                k_cur = unsafe { sys::ggml_mul(ctx.as_ptr(), k_cur, attn_k_norm.as_ptr()) };
            }

            q_cur = unsafe {
                sys::ggml_rope_ext(
                    ctx.as_ptr(),
                    q_cur,
                    inp_pos.as_ptr(),
                    std::ptr::null_mut(),
                    self.config.head_dim,
                    sys::GGML_ROPE_TYPE_NEOX as i32,
                    0,
                    self.config.rope_theta,
                    1.0,
                    0.0,
                    1.0,
                    0.0,
                    0.0,
                )
            };
            k_cur = unsafe {
                sys::ggml_rope_ext(
                    ctx.as_ptr(),
                    k_cur,
                    inp_pos.as_ptr(),
                    std::ptr::null_mut(),
                    self.config.head_dim,
                    sys::GGML_ROPE_TYPE_NEOX as i32,
                    0,
                    self.config.rope_theta,
                    1.0,
                    0.0,
                    1.0,
                    0.0,
                    0.0,
                )
            };

            let q = unsafe { sys::ggml_permute(ctx.as_ptr(), q_cur, 0, 2, 1, 3) };
            let k = unsafe { sys::ggml_permute(ctx.as_ptr(), k_cur, 0, 2, 1, 3) };
            let mut v = unsafe { sys::ggml_permute(ctx.as_ptr(), v_cur, 0, 2, 1, 3) };

            let mut kq = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), k, q) };
            kq = unsafe { sys::ggml_scale(ctx.as_ptr(), kq, kq_scale) };
            kq = unsafe {
                ggml_soft_max_ext_with_diag_mask_cache(ctx.as_ptr(), kq, 0, &mut attn_softmax_mask)
            };

            v = unsafe { sys::ggml_cont(ctx.as_ptr(), sys::ggml_transpose(ctx.as_ptr(), v)) };

            let mut kqv = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), v, kq) };
            kqv = unsafe { sys::ggml_permute(ctx.as_ptr(), kqv, 0, 2, 1, 3) };
            cur = unsafe {
                sys::ggml_cont_2d(
                    ctx.as_ptr(),
                    kqv,
                    (self.config.n_attention_heads * self.config.head_dim) as i64,
                    n_tokens as i64,
                )
            };

            cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.attn_output.as_ptr(), cur) };
            cur = unsafe { sys::ggml_add(ctx.as_ptr(), cur, inp_l) };
            let inp_ff = cur;

            cur = unsafe { sys::ggml_rms_norm(ctx.as_ptr(), inp_ff, self.config.rms_norm_eps) };
            cur = unsafe { sys::ggml_mul(ctx.as_ptr(), cur, layer.ffn_norm.as_ptr()) };

            let mut gate = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.ffn_gate.as_ptr(), cur) };
            let up = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.ffn_up.as_ptr(), cur) };
            gate = unsafe { sys::ggml_silu(ctx.as_ptr(), gate) };
            cur = unsafe { sys::ggml_mul(ctx.as_ptr(), gate, up) };

            let ffn_down_f32 = layer
                .ffn_down_f32
                .map(NonNull::as_ptr)
                .unwrap_or_else(|| unsafe {
                    sys::ggml_cast(
                        ctx.as_ptr(),
                        layer.ffn_down.as_ptr(),
                        sys::ggml_type_GGML_TYPE_F32,
                    )
                });
            cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), ffn_down_f32, cur) };
            inp_l = unsafe { sys::ggml_add(ctx.as_ptr(), cur, inp_ff) };
        }

        let mut hidden_states =
            unsafe { sys::ggml_rms_norm(ctx.as_ptr(), inp_l, self.config.rms_norm_eps) };
        hidden_states = unsafe {
            sys::ggml_mul(
                ctx.as_ptr(),
                hidden_states,
                self.talker.output_norm.as_ptr(),
            )
        };
        hidden_states = unsafe { sys::ggml_cont(ctx.as_ptr(), hidden_states) };
        self.retain_projected_predictor_hidden(hidden_states);
        let mut logits = unsafe {
            sys::ggml_mul_mat(ctx.as_ptr(), self.talker.codec_head.as_ptr(), hidden_states)
        };
        logits = unsafe { sys::ggml_cont(ctx.as_ptr(), logits) };

        unsafe {
            sys::ggml_build_forward_expand(graph.as_ptr(), hidden_states);
            sys::ggml_build_forward_expand(graph.as_ptr(), logits);
        }
        let hidden_elems = hidden_size * n_tokens;
        let logits_elems = self.config.codec_vocab_size as usize * n_tokens;
        let mut hidden_data = vec![0.0f32; hidden_elems];
        let mut logits_data = vec![0.0f32; logits_elems];
        let mut uploads = vec![
            TensorUpload {
                tensor: inp_prefill_embd.as_ptr(),
                bytes: slice_as_bytes(prefill_embd),
            },
            TensorUpload {
                tensor: inp_pos.as_ptr(),
                bytes: slice_as_bytes(positions.as_slice()),
            },
        ];
        if let Some((t, data)) = &attn_softmax_mask {
            uploads.push(TensorUpload {
                tensor: *t,
                bytes: slice_as_bytes(data.as_slice()),
            });
        }
        execute_graph(
            &self.talker._backends,
            graph,
            uploads.as_slice(),
            &mut [
                TensorDownload {
                    tensor: hidden_states,
                    bytes: slice_as_bytes_mut(hidden_data.as_mut_slice()),
                },
                TensorDownload {
                    tensor: logits,
                    bytes: slice_as_bytes_mut(logits_data.as_mut_slice()),
                },
            ],
            thread_count,
            "prefill graph execution failed",
        )?;

        Ok(PrefillForwardOutputs {
            hidden_states: hidden_data,
            logits: logits_data,
            n_tokens,
        })
    }

    pub fn select_codec_frame_from_prefill(
        &self,
        outputs: &PrefillForwardOutputs,
        repetition_penalty: f32,
        temperature: f32,
        top_k: i32,
        top_p: f32,
        recent_tokens: &[i32],
    ) -> Result<SelectedCodecFrame, Qwen3TtsError> {
        let hidden_size = self.config.hidden_size as usize;
        let vocab_size = self.config.codec_vocab_size as usize;
        if outputs.n_tokens == 0
            || outputs.hidden_states.len() != outputs.n_tokens * hidden_size
            || outputs.logits.len() != outputs.n_tokens * vocab_size
        {
            return Err(Qwen3TtsError::InvalidInput(
                "prefill outputs shape is invalid".into(),
            ));
        }

        let hidden_offset = (outputs.n_tokens - 1) * hidden_size;
        let logits_offset = (outputs.n_tokens - 1) * vocab_size;
        let hidden_state =
            outputs.hidden_states[hidden_offset..hidden_offset + hidden_size].to_vec();
        let mut logits = outputs.logits[logits_offset..logits_offset + vocab_size].to_vec();
        let suppress_start = vocab_size.saturating_sub(1024);
        for (token, logit) in logits.iter_mut().enumerate().skip(suppress_start) {
            if token as i32 != self.config.codec_eos_id {
                *logit = f32::NEG_INFINITY;
            }
        }
        self.mask_early_projected_eos(&mut logits, recent_tokens.len());
        let codebook_0_token = select_token(
            &logits,
            repetition_penalty,
            temperature,
            top_k,
            top_p,
            recent_tokens,
        )?;

        Ok(SelectedCodecFrame {
            codebook_0_token,
            codebook_tokens: vec![codebook_0_token],
            hidden_state,
            logits,
        })
    }

    pub fn predict_remaining_codebooks_recompute(
        &self,
        hidden_state: &[f32],
        codebook_0_token: i32,
        thread_count: usize,
        temperature: f32,
        top_k: i32,
        top_p: f32,
    ) -> Result<Vec<i32>, Qwen3TtsError> {
        let hidden_size = self.config.hidden_size as usize;
        if hidden_state.len() != hidden_size {
            return Err(Qwen3TtsError::InvalidInput(
                "code predictor hidden state shape is invalid".into(),
            ));
        }

        let mut codebook_tokens = Vec::with_capacity(self.config.n_codebooks as usize);
        codebook_tokens.push(codebook_0_token);

        while codebook_tokens.len() < self.config.n_codebooks as usize {
            let prev_codes = &codebook_tokens[1..];
            let logits = self.forward_code_pred_sequence_recompute(
                hidden_state,
                codebook_0_token,
                prev_codes,
                thread_count,
            )?;
            let token = select_token(&logits, 1.0, temperature, top_k, top_p, &[])?;
            codebook_tokens.push(token);
        }

        Ok(codebook_tokens)
    }

    pub fn predict_remaining_codebooks_kv(
        &self,
        hidden_state: &[f32],
        codebook_0_token: i32,
        thread_count: usize,
        temperature: f32,
        top_k: i32,
        top_p: f32,
    ) -> Result<Vec<i32>, Qwen3TtsError> {
        let cache = CodePredKvCache::new(
            &self.code_pred_config,
            self.config.n_codebooks as usize,
            self.code_pred._backends.clone(),
        )?;
        self.predict_remaining_codebooks_kv_with_cache(
            hidden_state,
            codebook_0_token,
            thread_count,
            temperature,
            top_k,
            top_p,
            &cache,
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn predict_remaining_codebooks_kv_with_cache(
        &self,
        hidden_state: &[f32],
        codebook_0_token: i32,
        thread_count: usize,
        temperature: f32,
        top_k: i32,
        top_p: f32,
        cache: &CodePredKvCache,
    ) -> Result<Vec<i32>, Qwen3TtsError> {
        let hidden_size = self.config.hidden_size as usize;
        if hidden_state.len() != hidden_size {
            return Err(Qwen3TtsError::InvalidInput(
                "code predictor hidden state shape is invalid".into(),
            ));
        }

        let mut codebook_tokens = Vec::with_capacity(self.config.n_codebooks as usize);
        codebook_tokens.push(codebook_0_token);

        let first = self.forward_code_pred_prefill_cached(
            hidden_state,
            codebook_0_token,
            thread_count,
            cache,
        )?;
        codebook_tokens.push(select_token(
            &first.logits,
            1.0,
            temperature,
            top_k,
            top_p,
            &[],
        )?);

        while codebook_tokens.len() < self.config.n_codebooks as usize {
            let generation_step = codebook_tokens.len() - 1;
            let prev_code = *codebook_tokens.last().ok_or_else(|| {
                Qwen3TtsError::InvalidInput("code predictor lost previous code".into())
            })?;
            let outputs = self.forward_code_pred_step_cached(
                prev_code,
                generation_step + 1,
                generation_step,
                thread_count,
                cache,
            )?;
            if generation_step == 5 && std::env::var_os("RIGHTKIT_QTS_TRACE_CB6").is_some() {
                let mut ranked = (0..outputs.logits.len()).collect::<Vec<_>>();
                ranked.sort_by(|&a, &b| outputs.logits[b].total_cmp(&outputs.logits[a]));
                eprintln!(
                    "cb6 top2={:?} margin={}",
                    ranked[..2]
                        .iter()
                        .map(|&i| (i, outputs.logits[i]))
                        .collect::<Vec<_>>(),
                    outputs.logits[ranked[0]] - outputs.logits[ranked[1]],
                );
            }
            codebook_tokens.push(select_token(
                &outputs.logits,
                1.0,
                temperature,
                top_k,
                top_p,
                &[],
            )?);
        }

        Ok(codebook_tokens)
    }

    #[allow(clippy::too_many_arguments)]
    pub fn generate_next_codec_frame_recompute(
        &self,
        history_embd: &[f32],
        step_embd: &[f32],
        thread_count: usize,
        repetition_penalty: f32,
        temperature: f32,
        top_k: i32,
        top_p: f32,
        recent_tokens: &[i32],
    ) -> Result<(Vec<f32>, SelectedCodecFrame), Qwen3TtsError> {
        let hidden_size = self.config.hidden_size as usize;
        if history_embd.is_empty() || !history_embd.len().is_multiple_of(hidden_size) {
            return Err(Qwen3TtsError::InvalidInput(
                "history embedding shape is invalid".into(),
            ));
        }
        if step_embd.len() != hidden_size {
            return Err(Qwen3TtsError::InvalidInput(
                "step embedding shape is invalid".into(),
            ));
        }

        let mut extended_history = Vec::with_capacity(history_embd.len() + step_embd.len());
        extended_history.extend_from_slice(history_embd);
        extended_history.extend_from_slice(step_embd);

        let outputs = self.forward_prefill(&extended_history, thread_count)?;
        let selected = self.select_codec_frame_from_prefill(
            &outputs,
            repetition_penalty,
            temperature,
            top_k,
            top_p,
            recent_tokens,
        )?;
        let codebook_tokens = self.predict_remaining_codebooks_recompute(
            &selected.hidden_state,
            selected.codebook_0_token,
            thread_count,
            temperature,
            top_k,
            top_p,
        )?;

        Ok((
            extended_history,
            SelectedCodecFrame {
                codebook_tokens,
                ..selected
            },
        ))
    }

    #[allow(clippy::too_many_arguments)]
    pub fn rollout_codec_frames_recompute(
        &self,
        prefill_embd: &[f32],
        trailing_text_hidden: &[f32],
        tts_pad_embed: &[f32],
        prompt_frames: &[Vec<i32>],
        thread_count: usize,
        max_frames: usize,
        repetition_penalty: f32,
        temperature: f32,
        top_k: i32,
        top_p: f32,
    ) -> Result<CodecRollout, Qwen3TtsError> {
        let mut code_dump = CodecCodeDump::from_env()?;
        if max_frames == 0 {
            return Ok(CodecRollout {
                frames: Vec::new(),
                first_frame_elapsed: Duration::ZERO,
                sub_timings: CodecRolloutSubTimings::default(),
            });
        }
        let t_rollout_start = Instant::now();

        let prefill_outputs = self.forward_prefill(prefill_embd, thread_count)?;
        for frame in prompt_frames {
            self.validate_codebook_frame(frame)?;
        }
        let prompt_recent_tokens = Self::recent_codebook0_tokens_from_prompt(prompt_frames);
        let first = self.select_codec_frame_from_prefill(
            &prefill_outputs,
            repetition_penalty,
            temperature,
            top_k,
            top_p,
            &prompt_recent_tokens,
        )?;
        if first.codebook_0_token == self.config.codec_eos_id {
            return Ok(CodecRollout {
                first_frame_elapsed: t_rollout_start.elapsed(),
                frames: prompt_frames
                    .iter()
                    .map(|codebook_tokens| SelectedCodecFrame {
                        codebook_0_token: codebook_tokens[0],
                        codebook_tokens: codebook_tokens.clone(),
                        hidden_state: Vec::new(),
                        logits: Vec::new(),
                    })
                    .collect(),
                sub_timings: CodecRolloutSubTimings::default(),
            });
        }
        let first = SelectedCodecFrame {
            codebook_tokens: self.predict_remaining_codebooks_recompute(
                &first.hidden_state,
                first.codebook_0_token,
                thread_count,
                temperature,
                top_k,
                top_p,
            )?,
            ..first
        };

        let mut frames = prompt_frames
            .iter()
            .map(|codebook_tokens| SelectedCodecFrame {
                codebook_0_token: codebook_tokens[0],
                codebook_tokens: codebook_tokens.clone(),
                hidden_state: Vec::new(),
                logits: Vec::new(),
            })
            .collect::<Vec<_>>();
        code_dump.record(&first.codebook_tokens)?;
        frames.push(first);
        let first_frame_elapsed = t_rollout_start.elapsed();
        let mut history_embd = prefill_embd.to_vec();
        let hidden_size = self.config.hidden_size as usize;
        if !trailing_text_hidden.len().is_multiple_of(hidden_size) {
            return Err(Qwen3TtsError::InvalidInput(
                "trailing text hidden shape is invalid".into(),
            ));
        }
        if tts_pad_embed.len() != hidden_size {
            return Err(Qwen3TtsError::InvalidInput(
                "tts pad embedding shape is invalid".into(),
            ));
        }
        let trailing_len = trailing_text_hidden.len() / hidden_size;

        while frames.len() < max_frames {
            let generated_frames = frames.len().saturating_sub(prompt_frames.len());
            let recent_tokens = Self::recent_codebook0_tokens_from_frames(&frames);
            let prev_token = frames
                .last()
                .map(|frame| frame.codebook_0_token)
                .ok_or_else(|| Qwen3TtsError::InvalidInput("rollout lost previous token".into()))?;

            if prev_token == self.config.codec_eos_id {
                break;
            }

            let trailing_idx = generated_frames.saturating_sub(1);
            let trailing_row = if trailing_idx < trailing_len {
                &trailing_text_hidden[trailing_idx * hidden_size..(trailing_idx + 1) * hidden_size]
            } else {
                tts_pad_embed
            };
            let step_embd = self.build_talker_step_embedding(
                &frames
                    .last()
                    .ok_or_else(|| {
                        Qwen3TtsError::InvalidInput("rollout lost previous frame".into())
                    })?
                    .codebook_tokens,
                trailing_row,
                thread_count,
            )?;
            let (next_history, next_frame) = self.generate_next_codec_frame_recompute(
                &history_embd,
                &step_embd,
                thread_count,
                repetition_penalty,
                temperature,
                top_k,
                top_p,
                &recent_tokens,
            )?;
            if next_frame.codebook_0_token == self.config.codec_eos_id {
                break;
            }
            history_embd = next_history;
            code_dump.record(&next_frame.codebook_tokens)?;
            frames.push(next_frame);
        }

        Ok(CodecRollout {
            frames,
            first_frame_elapsed,
            sub_timings: CodecRolloutSubTimings::default(),
        })
    }

    #[allow(clippy::too_many_arguments)]
    pub fn rollout_codec_frames_kv(
        &self,
        prefill_embd: &[f32],
        trailing_text_hidden: &[f32],
        tts_pad_embed: &[f32],
        prompt_frames: &[Vec<i32>],
        talker_kv_mode: TalkerKvMode,
        thread_count: usize,
        max_frames: usize,
        repetition_penalty: f32,
        temperature: f32,
        top_k: i32,
        top_p: f32,
    ) -> Result<CodecRollout, Qwen3TtsError> {
        let mut code_dump = CodecCodeDump::from_env()?;
        if max_frames == 0 {
            return Ok(CodecRollout {
                frames: Vec::new(),
                first_frame_elapsed: Duration::ZERO,
                sub_timings: CodecRolloutSubTimings::default(),
            });
        }
        let t_rollout_start = Instant::now();

        let hidden_size = self.config.hidden_size as usize;
        if prefill_embd.is_empty() || !prefill_embd.len().is_multiple_of(hidden_size) {
            return Err(Qwen3TtsError::InvalidInput(
                "prefill embedding shape is invalid".into(),
            ));
        }
        if !trailing_text_hidden.len().is_multiple_of(hidden_size) {
            return Err(Qwen3TtsError::InvalidInput(
                "trailing text hidden shape is invalid".into(),
            ));
        }
        if tts_pad_embed.len() != hidden_size {
            return Err(Qwen3TtsError::InvalidInput(
                "tts pad embedding shape is invalid".into(),
            ));
        }
        for frame in prompt_frames {
            self.validate_codebook_frame(frame)?;
        }

        let prefill_len = prefill_embd.len() / hidden_size;
        let trailing_len = trailing_text_hidden.len() / hidden_size;
        let required_ctx = max(256, prefill_len + max_frames + 16);
        let cache = TalkerKvCache::new(
            &self.config,
            required_ctx,
            self.talker._backends.clone(),
            talker_kv_mode,
        )?;
        let code_pred_cache = CodePredKvCache::new(
            &self.code_pred_config,
            self.config.n_codebooks as usize,
            self.code_pred._backends.clone(),
        )?;

        let t_prefill = Instant::now();
        let first_outputs = self.forward_prefill_cached(prefill_embd, thread_count, &cache)?;
        let talker_prefill_dur = t_prefill.elapsed();

        let mut logits = first_outputs.logits;
        let suppress_start = self.config.codec_vocab_size.saturating_sub(1024) as usize;
        for (token, logit) in logits.iter_mut().enumerate().skip(suppress_start) {
            if token as i32 != self.config.codec_eos_id {
                *logit = f32::NEG_INFINITY;
            }
        }
        let prompt_recent_tokens = Self::recent_codebook0_tokens_from_prompt(prompt_frames);
        self.mask_early_projected_eos(&mut logits, 0);
        let first_codebook_0 = select_token(
            &logits,
            repetition_penalty,
            temperature,
            top_k,
            top_p,
            &prompt_recent_tokens,
        )?;
        if first_codebook_0 == self.config.codec_eos_id {
            return Ok(CodecRollout {
                first_frame_elapsed: t_rollout_start.elapsed(),
                frames: prompt_frames
                    .iter()
                    .map(|codebook_tokens| SelectedCodecFrame {
                        codebook_0_token: codebook_tokens[0],
                        codebook_tokens: codebook_tokens.clone(),
                        hidden_state: Vec::new(),
                        logits: Vec::new(),
                    })
                    .collect(),
                sub_timings: CodecRolloutSubTimings {
                    talker_prefill: talker_prefill_dur,
                    talker_kv_bytes: cache.total_bytes(),
                    ..Default::default()
                },
            });
        }

        let mut code_pred_dur = Duration::ZERO;
        let t_cp = Instant::now();
        let first_codes = self.predict_remaining_codebooks_kv_with_cache(
            &first_outputs.hidden_state,
            first_codebook_0,
            thread_count,
            temperature,
            top_k,
            top_p,
            &code_pred_cache,
        )?;
        code_pred_dur += t_cp.elapsed();

        let mut frames = prompt_frames
            .iter()
            .map(|codebook_tokens| SelectedCodecFrame {
                codebook_0_token: codebook_tokens[0],
                codebook_tokens: codebook_tokens.clone(),
                hidden_state: Vec::new(),
                logits: Vec::new(),
            })
            .collect::<Vec<_>>();
        code_dump.record(&first_codes)?;
        frames.push(SelectedCodecFrame {
            codebook_0_token: first_codebook_0,
            codebook_tokens: first_codes,
            hidden_state: first_outputs.hidden_state,
            logits,
        });
        let first_frame_elapsed = t_rollout_start.elapsed();
        let mut n_past = prefill_len;

        let mut talker_steps_dur = Duration::ZERO;
        let mut kv_writeback_dur = Duration::ZERO;
        let mut kv_download_dur = Duration::ZERO;
        let mut kv_quantize_dur = Duration::ZERO;
        let mut kv_upload_dur = Duration::ZERO;

        while frames.len() < max_frames {
            let generated_frames = frames.len().saturating_sub(prompt_frames.len());
            let recent_tokens = Self::recent_codebook0_tokens_from_frames(&frames);
            let trailing_idx = generated_frames.saturating_sub(1);
            let trailing_row = if trailing_idx < trailing_len {
                &trailing_text_hidden[trailing_idx * hidden_size..(trailing_idx + 1) * hidden_size]
            } else {
                tts_pad_embed
            };
            let step_embd = self.build_talker_step_embedding(
                &frames
                    .last()
                    .ok_or_else(|| {
                        Qwen3TtsError::InvalidInput("rollout lost previous frame".into())
                    })?
                    .codebook_tokens,
                trailing_row,
                thread_count,
            )?;
            let t_step = Instant::now();
            let step_outputs =
                self.forward_step_cached(&step_embd, n_past, thread_count, &cache)?;
            let step_elapsed = t_step.elapsed();
            kv_writeback_dur += step_outputs.kv_writeback_elapsed;
            kv_download_dur += step_outputs.kv_download_elapsed;
            kv_quantize_dur += step_outputs.kv_quantize_elapsed;
            kv_upload_dur += step_outputs.kv_upload_elapsed;
            talker_steps_dur += step_elapsed.saturating_sub(step_outputs.kv_writeback_elapsed);

            let mut logits = step_outputs.logits;
            for (token, logit) in logits.iter_mut().enumerate().skip(suppress_start) {
                if token as i32 != self.config.codec_eos_id {
                    *logit = f32::NEG_INFINITY;
                }
            }
            self.mask_early_projected_eos(&mut logits, generated_frames);
            let codebook_0_token = select_token(
                &logits,
                repetition_penalty,
                temperature,
                top_k,
                top_p,
                &recent_tokens,
            )?;
            if codebook_0_token == self.config.codec_eos_id {
                break;
            }
            let t_cp = Instant::now();
            let codebook_tokens = self.predict_remaining_codebooks_kv_with_cache(
                &step_outputs.hidden_state,
                codebook_0_token,
                thread_count,
                temperature,
                top_k,
                top_p,
                &code_pred_cache,
            )?;
            code_pred_dur += t_cp.elapsed();

            code_dump.record(&codebook_tokens)?;
            frames.push(SelectedCodecFrame {
                codebook_0_token,
                codebook_tokens,
                hidden_state: step_outputs.hidden_state,
                logits,
            });
            n_past += 1;
        }

        Ok(CodecRollout {
            frames,
            first_frame_elapsed,
            sub_timings: CodecRolloutSubTimings {
                talker_prefill: talker_prefill_dur,
                talker_steps: talker_steps_dur,
                code_pred_total: code_pred_dur,
                kv_writeback: kv_writeback_dur,
                kv_download: kv_download_dur,
                kv_quantize: kv_quantize_dur,
                kv_upload: kv_upload_dur,
                talker_kv_bytes: cache.total_bytes(),
            },
        })
    }

    /// Streaming variant that sends `VocoderChunk`s to `chunk_tx` every
    /// `chunk_size` generated frames so the vocoder can decode in parallel.
    #[allow(clippy::too_many_arguments)]
    pub fn rollout_codec_frames_kv_streaming(
        &self,
        prefill_embd: &[f32],
        trailing_text_hidden: &[f32],
        tts_pad_embed: &[f32],
        prompt_frames: &[Vec<i32>],
        talker_kv_mode: TalkerKvMode,
        thread_count: usize,
        max_frames: usize,
        repetition_penalty: f32,
        temperature: f32,
        top_k: i32,
        top_p: f32,
        chunk_size: usize,
        chunk_tx: &std::sync::mpsc::SyncSender<VocoderChunk>,
    ) -> Result<CodecRollout, Qwen3TtsError> {
        let mut code_dump = CodecCodeDump::from_env()?;
        if max_frames == 0 {
            return Ok(CodecRollout {
                frames: Vec::new(),
                first_frame_elapsed: Duration::ZERO,
                sub_timings: CodecRolloutSubTimings::default(),
            });
        }
        let t_rollout_start = Instant::now();

        let hidden_size = self.config.hidden_size as usize;
        if prefill_embd.is_empty() || !prefill_embd.len().is_multiple_of(hidden_size) {
            return Err(Qwen3TtsError::InvalidInput(
                "prefill embedding shape is invalid".into(),
            ));
        }
        if !trailing_text_hidden.len().is_multiple_of(hidden_size) {
            return Err(Qwen3TtsError::InvalidInput(
                "trailing text hidden shape is invalid".into(),
            ));
        }
        if tts_pad_embed.len() != hidden_size {
            return Err(Qwen3TtsError::InvalidInput(
                "tts pad embedding shape is invalid".into(),
            ));
        }
        for frame in prompt_frames {
            self.validate_codebook_frame(frame)?;
        }

        let prefill_len = prefill_embd.len() / hidden_size;
        let trailing_len = trailing_text_hidden.len() / hidden_size;
        let required_ctx = max(256, prefill_len + max_frames + 16);
        let cache = TalkerKvCache::new(
            &self.config,
            required_ctx,
            self.talker._backends.clone(),
            talker_kv_mode,
        )?;
        let code_pred_cache = CodePredKvCache::new(
            &self.code_pred_config,
            self.config.n_codebooks as usize,
            self.code_pred._backends.clone(),
        )?;

        let t_prefill = Instant::now();
        let first_outputs = self.forward_prefill_cached(prefill_embd, thread_count, &cache)?;
        let talker_prefill_dur = t_prefill.elapsed();

        let mut logits = first_outputs.logits;
        let suppress_start = self.config.codec_vocab_size.saturating_sub(1024) as usize;
        for (token, logit) in logits.iter_mut().enumerate().skip(suppress_start) {
            if token as i32 != self.config.codec_eos_id {
                *logit = f32::NEG_INFINITY;
            }
        }
        let prompt_recent_tokens = Self::recent_codebook0_tokens_from_prompt(prompt_frames);
        self.mask_early_projected_eos(&mut logits, 0);
        let first_codebook_0 = select_token(
            &logits,
            repetition_penalty,
            temperature,
            top_k,
            top_p,
            &prompt_recent_tokens,
        )?;
        if first_codebook_0 == self.config.codec_eos_id {
            return Ok(CodecRollout {
                first_frame_elapsed: t_rollout_start.elapsed(),
                frames: prompt_frames
                    .iter()
                    .map(|codebook_tokens| SelectedCodecFrame {
                        codebook_0_token: codebook_tokens[0],
                        codebook_tokens: codebook_tokens.clone(),
                        hidden_state: Vec::new(),
                        logits: Vec::new(),
                    })
                    .collect(),
                sub_timings: CodecRolloutSubTimings {
                    talker_prefill: talker_prefill_dur,
                    talker_kv_bytes: cache.total_bytes(),
                    ..Default::default()
                },
            });
        }

        let mut code_pred_dur = Duration::ZERO;
        let t_cp = Instant::now();
        let first_codes = self.predict_remaining_codebooks_kv_with_cache(
            &first_outputs.hidden_state,
            first_codebook_0,
            thread_count,
            temperature,
            top_k,
            top_p,
            &code_pred_cache,
        )?;
        code_pred_dur += t_cp.elapsed();

        let mut frames = prompt_frames
            .iter()
            .map(|codebook_tokens| SelectedCodecFrame {
                codebook_0_token: codebook_tokens[0],
                codebook_tokens: codebook_tokens.clone(),
                hidden_state: Vec::new(),
                logits: Vec::new(),
            })
            .collect::<Vec<_>>();
        code_dump.record(&first_codes)?;
        frames.push(SelectedCodecFrame {
            codebook_0_token: first_codebook_0,
            codebook_tokens: first_codes,
            hidden_state: first_outputs.hidden_state,
            logits,
        });
        let first_frame_elapsed = t_rollout_start.elapsed();
        let mut n_past = prefill_len;

        let prefix_frame_count = prompt_frames.len();
        let chunk_size = chunk_size.max(1);
        let mut unsent_start = prefix_frame_count;

        let flush_chunk =
            |frames: &[SelectedCodecFrame],
             start: usize,
             end: usize,
             tx: &std::sync::mpsc::SyncSender<VocoderChunk>| {
                if end <= start {
                    return;
                }
                let codes = frames[start..end]
                    .iter()
                    .flat_map(|f| f.codebook_tokens.iter().copied())
                    .collect::<Vec<_>>();
                let _ = tx.send(VocoderChunk {
                    codes,
                    n_frames: end - start,
                });
            };

        let mut talker_steps_dur = Duration::ZERO;
        let mut kv_writeback_dur = Duration::ZERO;
        let mut kv_download_dur = Duration::ZERO;
        let mut kv_quantize_dur = Duration::ZERO;
        let mut kv_upload_dur = Duration::ZERO;

        while frames.len() < max_frames {
            let generated_frames = frames.len().saturating_sub(prompt_frames.len());
            let recent_tokens = Self::recent_codebook0_tokens_from_frames(&frames);
            let trailing_idx = generated_frames.saturating_sub(1);
            let trailing_row = if trailing_idx < trailing_len {
                &trailing_text_hidden[trailing_idx * hidden_size..(trailing_idx + 1) * hidden_size]
            } else {
                tts_pad_embed
            };
            let step_embd = self.build_talker_step_embedding(
                &frames
                    .last()
                    .ok_or_else(|| {
                        Qwen3TtsError::InvalidInput("rollout lost previous frame".into())
                    })?
                    .codebook_tokens,
                trailing_row,
                thread_count,
            )?;
            let t_step = Instant::now();
            let step_outputs =
                self.forward_step_cached(&step_embd, n_past, thread_count, &cache)?;
            let step_elapsed = t_step.elapsed();
            kv_writeback_dur += step_outputs.kv_writeback_elapsed;
            kv_download_dur += step_outputs.kv_download_elapsed;
            kv_quantize_dur += step_outputs.kv_quantize_elapsed;
            kv_upload_dur += step_outputs.kv_upload_elapsed;
            talker_steps_dur += step_elapsed.saturating_sub(step_outputs.kv_writeback_elapsed);

            let mut logits = step_outputs.logits;
            for (token, logit) in logits.iter_mut().enumerate().skip(suppress_start) {
                if token as i32 != self.config.codec_eos_id {
                    *logit = f32::NEG_INFINITY;
                }
            }
            self.mask_early_projected_eos(&mut logits, generated_frames);
            let codebook_0_token = select_token(
                &logits,
                repetition_penalty,
                temperature,
                top_k,
                top_p,
                &recent_tokens,
            )?;
            if codebook_0_token == self.config.codec_eos_id {
                break;
            }
            let t_cp = Instant::now();
            let codebook_tokens = self.predict_remaining_codebooks_kv_with_cache(
                &step_outputs.hidden_state,
                codebook_0_token,
                thread_count,
                temperature,
                top_k,
                top_p,
                &code_pred_cache,
            )?;
            code_pred_dur += t_cp.elapsed();

            code_dump.record(&codebook_tokens)?;
            frames.push(SelectedCodecFrame {
                codebook_0_token,
                codebook_tokens,
                hidden_state: step_outputs.hidden_state,
                logits,
            });
            n_past += 1;

            let generated_since_last = frames.len() - unsent_start;
            if generated_since_last >= chunk_size {
                flush_chunk(&frames, unsent_start, frames.len(), chunk_tx);
                unsent_start = frames.len();
            }
        }

        if frames.len() > unsent_start {
            flush_chunk(&frames, unsent_start, frames.len(), chunk_tx);
        }

        Ok(CodecRollout {
            frames,
            first_frame_elapsed,
            sub_timings: CodecRolloutSubTimings {
                talker_prefill: talker_prefill_dur,
                talker_steps: talker_steps_dur,
                code_pred_total: code_pred_dur,
                kv_writeback: kv_writeback_dur,
                kv_download: kv_download_dur,
                kv_quantize: kv_quantize_dur,
                kv_upload: kv_upload_dur,
                talker_kv_bytes: cache.total_bytes(),
            },
        })
    }

    fn validate_codebook_frame(&self, codebook_tokens: &[i32]) -> Result<(), Qwen3TtsError> {
        if codebook_tokens.len() != self.config.n_codebooks as usize {
            return Err(Qwen3TtsError::InvalidInput(format!(
                "reference codec frame must contain {} codebooks",
                self.config.n_codebooks
            )));
        }
        for (idx, &token) in codebook_tokens.iter().enumerate() {
            let vocab_size = if idx == 0 {
                self.config.codec_vocab_size
            } else {
                self.code_pred_config.vocab_size
            };
            if token < 0 || token >= vocab_size {
                return Err(Qwen3TtsError::InvalidInput(format!(
                    "reference codec token {token} at codebook {idx} out of range 0..{}",
                    vocab_size - 1
                )));
            }
        }
        Ok(())
    }

    fn project_text_tokens(
        &self,
        text_tokens: &[i32],
        thread_count: usize,
    ) -> Result<Vec<f32>, Qwen3TtsError> {
        if text_tokens.is_empty() {
            return Ok(Vec::new());
        }

        let graph_nodes = 16;
        let ctx = ComputeContext::new_graph(graph_nodes)?;
        let graph = unsafe { sys::ggml_new_graph_custom(ctx.as_ptr(), graph_nodes, false) };
        let graph = NonNull::new(graph).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("failed to allocate text projection graph".into())
        })?;

        let inp_tokens = unsafe {
            sys::ggml_new_tensor_1d(
                ctx.as_ptr(),
                sys::ggml_type_GGML_TYPE_I32,
                text_tokens.len() as i64,
            )
        };
        let inp_tokens = NonNull::new(inp_tokens).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("failed to allocate text token input".into())
        })?;
        let mut cur = unsafe {
            sys::ggml_get_rows(
                ctx.as_ptr(),
                self.talker.text_embd.as_ptr(),
                inp_tokens.as_ptr(),
            )
        };
        cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), self.talker.text_proj_fc1.as_ptr(), cur) };
        cur = unsafe { sys::ggml_add(ctx.as_ptr(), cur, self.talker.text_proj_fc1_bias.as_ptr()) };
        cur = unsafe { sys::ggml_silu(ctx.as_ptr(), cur) };
        cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), self.talker.text_proj_fc2.as_ptr(), cur) };
        cur = unsafe { sys::ggml_add(ctx.as_ptr(), cur, self.talker.text_proj_fc2_bias.as_ptr()) };
        cur = unsafe { sys::ggml_cast(ctx.as_ptr(), cur, sys::ggml_type_GGML_TYPE_F32) };

        unsafe {
            sys::ggml_build_forward_expand(graph.as_ptr(), cur);
        }
        let elem_count = self.config.hidden_size as usize * text_tokens.len();
        let mut data = vec![0.0f32; elem_count];
        execute_graph(
            &self.talker._backends,
            graph,
            &[TensorUpload {
                tensor: inp_tokens.as_ptr(),
                bytes: slice_as_bytes(text_tokens),
            }],
            &mut [TensorDownload {
                tensor: cur,
                bytes: slice_as_bytes_mut(data.as_mut_slice()),
            }],
            thread_count,
            "text projection graph execution failed",
        )?;
        Ok(data)
    }

    fn lookup_codec_embedding_rows(
        &self,
        token_ids: &[i32],
        thread_count: usize,
    ) -> Result<Vec<f32>, Qwen3TtsError> {
        if token_ids.is_empty() {
            return Ok(Vec::new());
        }
        for &token_id in token_ids {
            if token_id < 0 || token_id >= self.config.codec_vocab_size {
                return Err(Qwen3TtsError::InvalidInput(format!(
                    "codec token {token_id} out of range 0..{}",
                    self.config.codec_vocab_size - 1
                )));
            }
        }

        let hidden_size = self.config.hidden_size as usize;
        if let Some(codec_table) = self.talker.codec_embd_cpu.as_ref() {
            let mut data = vec![0.0f32; hidden_size * token_ids.len()];
            for (row_idx, &token_id) in token_ids.iter().enumerate() {
                let token = token_id as usize;
                let src = token * hidden_size..(token + 1) * hidden_size;
                let dst = row_idx * hidden_size..(row_idx + 1) * hidden_size;
                if src.end > codec_table.len() {
                    return Err(Qwen3TtsError::InvalidInput(
                        "codec embedding CPU table shape is invalid".into(),
                    ));
                }
                data[dst].copy_from_slice(&codec_table[src]);
            }
            return Ok(data);
        }

        let graph_nodes = 8;
        let ctx = ComputeContext::new_graph(graph_nodes)?;
        let graph = unsafe { sys::ggml_new_graph_custom(ctx.as_ptr(), graph_nodes, false) };
        let graph = NonNull::new(graph).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("failed to allocate embedding graph".into())
        })?;

        let inp_tokens = unsafe {
            sys::ggml_new_tensor_1d(
                ctx.as_ptr(),
                sys::ggml_type_GGML_TYPE_I32,
                token_ids.len() as i64,
            )
        };
        let inp_tokens = NonNull::new(inp_tokens).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("failed to allocate codec token input".into())
        })?;
        let mut rows = unsafe {
            sys::ggml_get_rows(
                ctx.as_ptr(),
                self.talker.codec_embd.as_ptr(),
                inp_tokens.as_ptr(),
            )
        };
        rows = unsafe { sys::ggml_cast(ctx.as_ptr(), rows, sys::ggml_type_GGML_TYPE_F32) };
        unsafe {
            sys::ggml_build_forward_expand(graph.as_ptr(), rows);
        }
        let elem_count = hidden_size * token_ids.len();
        let mut data = vec![0.0f32; elem_count];
        execute_graph(
            &self.talker._backends,
            graph,
            &[TensorUpload {
                tensor: inp_tokens.as_ptr(),
                bytes: slice_as_bytes(token_ids),
            }],
            &mut [TensorDownload {
                tensor: rows,
                bytes: slice_as_bytes_mut(data.as_mut_slice()),
            }],
            thread_count,
            "codec embedding graph execution failed",
        )?;
        Ok(data)
    }

    fn sum_codec_frame_embeddings(
        &self,
        codebook_tokens: &[i32],
        thread_count: usize,
    ) -> Result<Vec<f32>, Qwen3TtsError> {
        self.validate_codebook_frame(codebook_tokens)?;
        let hidden_size = self.config.hidden_size as usize;

        if let (Some(codec_table), Some(pred_tables)) = (
            self.talker.codec_embd_cpu.as_ref(),
            self.code_pred.codec_embd_cpu.as_ref(),
        ) {
            let expected_pred = codebook_tokens.len().saturating_sub(1);
            if pred_tables.len() == expected_pred {
                let mut out = vec![0.0f32; hidden_size];
                let token0 = codebook_tokens[0] as usize;
                let row0 = token0 * hidden_size..(token0 + 1) * hidden_size;
                if row0.end <= codec_table.len() {
                    out.copy_from_slice(&codec_table[row0]);
                    let mut cpu_ok = true;
                    for (cb_idx, &token) in codebook_tokens[1..].iter().enumerate() {
                        let tok = token as usize;
                        let row = tok * hidden_size..(tok + 1) * hidden_size;
                        let table = &pred_tables[cb_idx];
                        if row.end > table.len() {
                            cpu_ok = false;
                            break;
                        }
                        for i in 0..hidden_size {
                            out[i] += table[row.start + i];
                        }
                    }
                    if cpu_ok {
                        return Ok(out);
                    }
                }
            }
        }

        let mut out = self.lookup_codec_embedding_rows(&[codebook_tokens[0]], thread_count)?;
        for (cb_idx, &token) in codebook_tokens[1..].iter().enumerate() {
            let row = self.lookup_code_pred_embedding_row(cb_idx, token, thread_count)?;
            for i in 0..hidden_size {
                out[i] += row[i];
            }
        }
        Ok(out)
    }

    fn forward_code_pred_sequence_recompute(
        &self,
        hidden_state: &[f32],
        codebook_0_token: i32,
        prev_codes: &[i32],
        thread_count: usize,
    ) -> Result<Vec<f32>, Qwen3TtsError> {
        let hidden_size = self.config.hidden_size as usize;
        if hidden_state.len() != hidden_size {
            return Err(Qwen3TtsError::InvalidInput(
                "code predictor hidden state shape is invalid".into(),
            ));
        }
        if prev_codes.len() >= self.config.n_codebooks as usize {
            return Err(Qwen3TtsError::InvalidInput(
                "too many previous code predictor tokens".into(),
            ));
        }

        let mut sequence_embd = Vec::with_capacity((2 + prev_codes.len()) * hidden_size);
        sequence_embd.extend_from_slice(hidden_state);
        sequence_embd.extend_from_slice(
            &self.lookup_codec_embedding_rows(&[codebook_0_token], thread_count)?,
        );
        for (cb_idx, &token) in prev_codes.iter().enumerate() {
            sequence_embd.extend_from_slice(&self.lookup_code_pred_embedding_row(
                cb_idx,
                token,
                thread_count,
            )?);
        }

        let n_tokens = sequence_embd.len() / hidden_size;
        let graph_nodes = 2048;
        let ctx = ComputeContext::new_graph(graph_nodes)?;
        let graph = unsafe { sys::ggml_new_graph_custom(ctx.as_ptr(), graph_nodes, false) };
        let graph = NonNull::new(graph).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("failed to allocate code predictor graph".into())
        })?;

        let inp_embd = unsafe {
            sys::ggml_new_tensor_2d(
                ctx.as_ptr(),
                sys::ggml_type_GGML_TYPE_F32,
                hidden_size as i64,
                n_tokens as i64,
            )
        };
        let inp_embd = NonNull::new(inp_embd).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("failed to allocate code predictor input".into())
        })?;

        let inp_pos = unsafe {
            sys::ggml_new_tensor_1d(ctx.as_ptr(), sys::ggml_type_GGML_TYPE_I32, n_tokens as i64)
        };
        let inp_pos = NonNull::new(inp_pos).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("failed to allocate code predictor positions".into())
        })?;
        let positions = (0..n_tokens as i32).collect::<Vec<_>>();

        let mut inp_l = self
            .code_pred
            .project_input(ctx.as_ptr(), inp_embd.as_ptr());
        let hidden_size = self.code_pred_config.hidden_size as usize;
        let kq_scale = 1.0f32 / (self.code_pred_config.head_dim as f32).sqrt();
        let mut attn_softmax_mask: Option<(*mut sys::ggml_tensor, Vec<f32>)> = None;
        for layer in &self.code_pred.layers {
            let mut cur = unsafe {
                sys::ggml_rms_norm(ctx.as_ptr(), inp_l, self.code_pred_config.rms_norm_eps)
            };
            cur = unsafe { sys::ggml_mul(ctx.as_ptr(), cur, layer.attn_norm.as_ptr()) };

            let mut q_cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.attn_q.as_ptr(), cur) };
            let mut k_cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.attn_k.as_ptr(), cur) };
            let mut v_cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.attn_v.as_ptr(), cur) };

            q_cur = unsafe {
                sys::ggml_reshape_3d(
                    ctx.as_ptr(),
                    q_cur,
                    self.code_pred_config.head_dim as i64,
                    self.code_pred_config.n_attention_heads as i64,
                    n_tokens as i64,
                )
            };
            k_cur = unsafe {
                sys::ggml_reshape_3d(
                    ctx.as_ptr(),
                    k_cur,
                    self.code_pred_config.head_dim as i64,
                    self.code_pred_config.n_key_value_heads as i64,
                    n_tokens as i64,
                )
            };
            v_cur = unsafe {
                sys::ggml_reshape_3d(
                    ctx.as_ptr(),
                    v_cur,
                    self.code_pred_config.head_dim as i64,
                    self.code_pred_config.n_key_value_heads as i64,
                    n_tokens as i64,
                )
            };

            if let Some(attn_q_norm) = layer.attn_q_norm {
                q_cur = unsafe {
                    sys::ggml_rms_norm(ctx.as_ptr(), q_cur, self.code_pred_config.rms_norm_eps)
                };
                q_cur = unsafe { sys::ggml_mul(ctx.as_ptr(), q_cur, attn_q_norm.as_ptr()) };
            }
            if let Some(attn_k_norm) = layer.attn_k_norm {
                k_cur = unsafe {
                    sys::ggml_rms_norm(ctx.as_ptr(), k_cur, self.code_pred_config.rms_norm_eps)
                };
                k_cur = unsafe { sys::ggml_mul(ctx.as_ptr(), k_cur, attn_k_norm.as_ptr()) };
            }

            q_cur = unsafe {
                sys::ggml_rope_ext(
                    ctx.as_ptr(),
                    q_cur,
                    inp_pos.as_ptr(),
                    std::ptr::null_mut(),
                    self.code_pred_config.head_dim,
                    sys::GGML_ROPE_TYPE_NEOX as i32,
                    0,
                    self.code_pred_config.rope_theta,
                    1.0,
                    0.0,
                    1.0,
                    0.0,
                    0.0,
                )
            };
            k_cur = unsafe {
                sys::ggml_rope_ext(
                    ctx.as_ptr(),
                    k_cur,
                    inp_pos.as_ptr(),
                    std::ptr::null_mut(),
                    self.code_pred_config.head_dim,
                    sys::GGML_ROPE_TYPE_NEOX as i32,
                    0,
                    self.code_pred_config.rope_theta,
                    1.0,
                    0.0,
                    1.0,
                    0.0,
                    0.0,
                )
            };

            let q = unsafe { sys::ggml_permute(ctx.as_ptr(), q_cur, 0, 2, 1, 3) };
            let k = unsafe { sys::ggml_permute(ctx.as_ptr(), k_cur, 0, 2, 1, 3) };
            let mut v = unsafe { sys::ggml_permute(ctx.as_ptr(), v_cur, 0, 2, 1, 3) };

            let mut kq = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), k, q) };
            kq = unsafe { sys::ggml_scale(ctx.as_ptr(), kq, kq_scale) };
            kq = unsafe {
                ggml_soft_max_ext_with_diag_mask_cache(ctx.as_ptr(), kq, 0, &mut attn_softmax_mask)
            };

            v = unsafe { sys::ggml_cont(ctx.as_ptr(), sys::ggml_transpose(ctx.as_ptr(), v)) };

            let mut kqv = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), v, kq) };
            kqv = unsafe { sys::ggml_permute(ctx.as_ptr(), kqv, 0, 2, 1, 3) };
            cur = unsafe {
                sys::ggml_cont_2d(
                    ctx.as_ptr(),
                    kqv,
                    (self.code_pred_config.n_attention_heads * self.code_pred_config.head_dim)
                        as i64,
                    n_tokens as i64,
                )
            };

            cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.attn_output.as_ptr(), cur) };
            cur = unsafe { sys::ggml_add(ctx.as_ptr(), cur, inp_l) };
            let inp_ff = cur;

            cur = unsafe {
                sys::ggml_rms_norm(ctx.as_ptr(), inp_ff, self.code_pred_config.rms_norm_eps)
            };
            cur = unsafe { sys::ggml_mul(ctx.as_ptr(), cur, layer.ffn_norm.as_ptr()) };
            let mut gate = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.ffn_gate.as_ptr(), cur) };
            let up = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.ffn_up.as_ptr(), cur) };
            gate = unsafe { sys::ggml_silu(ctx.as_ptr(), gate) };
            cur = unsafe { sys::ggml_mul(ctx.as_ptr(), gate, up) };

            let ffn_down_f32 = layer
                .ffn_down_f32
                .map(NonNull::as_ptr)
                .unwrap_or_else(|| unsafe {
                    sys::ggml_cast(
                        ctx.as_ptr(),
                        layer.ffn_down.as_ptr(),
                        sys::ggml_type_GGML_TYPE_F32,
                    )
                });
            cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), ffn_down_f32, cur) };
            inp_l = unsafe { sys::ggml_add(ctx.as_ptr(), cur, inp_ff) };
        }

        let mut cur =
            unsafe { sys::ggml_rms_norm(ctx.as_ptr(), inp_l, self.code_pred_config.rms_norm_eps) };
        cur = unsafe { sys::ggml_mul(ctx.as_ptr(), cur, self.code_pred.output_norm.as_ptr()) };
        let last_hidden = unsafe {
            sys::ggml_view_2d(
                ctx.as_ptr(),
                cur,
                hidden_size as i64,
                1,
                (*cur).nb[1],
                (n_tokens - 1) * (*cur).nb[1],
            )
        };
        let head = self
            .code_pred
            .heads
            .get(prev_codes.len())
            .ok_or_else(|| Qwen3TtsError::InvalidInput("missing code predictor head".into()))?;
        let mut logits = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), head.as_ptr(), last_hidden) };
        logits = unsafe { sys::ggml_cont(ctx.as_ptr(), logits) };
        unsafe {
            sys::ggml_build_forward_expand(graph.as_ptr(), logits);
        }
        let vocab = self.code_pred_config.vocab_size as usize;
        let mut logits_data = vec![0.0f32; vocab];
        let mut uploads = vec![
            TensorUpload {
                tensor: inp_embd.as_ptr(),
                bytes: slice_as_bytes(sequence_embd.as_slice()),
            },
            TensorUpload {
                tensor: inp_pos.as_ptr(),
                bytes: slice_as_bytes(positions.as_slice()),
            },
        ];
        if let Some((t, data)) = &attn_softmax_mask {
            uploads.push(TensorUpload {
                tensor: *t,
                bytes: slice_as_bytes(data.as_slice()),
            });
        }
        execute_graph(
            &self.code_pred._backends,
            graph,
            uploads.as_slice(),
            &mut [TensorDownload {
                tensor: logits,
                bytes: slice_as_bytes_mut(logits_data.as_mut_slice()),
            }],
            thread_count,
            "code predictor graph execution failed",
        )?;
        Ok(logits_data)
    }

    fn lookup_code_pred_embedding_row(
        &self,
        cb_idx: usize,
        token_id: i32,
        thread_count: usize,
    ) -> Result<Vec<f32>, Qwen3TtsError> {
        if token_id < 0 || token_id >= self.code_pred_config.vocab_size {
            return Err(Qwen3TtsError::InvalidInput(format!(
                "code predictor token {token_id} out of range 0..{} for codebook {}",
                self.code_pred_config.vocab_size - 1,
                cb_idx + 1
            )));
        }
        let weight = self.code_pred.embeddings.get(cb_idx).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("missing code predictor embedding".into())
        })?;
        let hidden_size = self.config.hidden_size as usize;
        let graph_nodes = 16;
        let ctx = ComputeContext::new_graph(graph_nodes)?;
        let graph = unsafe { sys::ggml_new_graph_custom(ctx.as_ptr(), graph_nodes, false) };
        let graph = NonNull::new(graph).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("failed to allocate code predictor embedding graph".into())
        })?;
        let inp_token =
            unsafe { sys::ggml_new_tensor_1d(ctx.as_ptr(), sys::ggml_type_GGML_TYPE_I32, 1) };
        let inp_token = NonNull::new(inp_token).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("failed to allocate code predictor embedding input".into())
        })?;
        let mut rows =
            unsafe { sys::ggml_get_rows(ctx.as_ptr(), weight.as_ptr(), inp_token.as_ptr()) };
        rows = unsafe { sys::ggml_cast(ctx.as_ptr(), rows, sys::ggml_type_GGML_TYPE_F32) };
        unsafe {
            sys::ggml_build_forward_expand(graph.as_ptr(), rows);
        }
        let mut data = vec![0.0f32; hidden_size];
        execute_graph(
            &self.code_pred._backends,
            graph,
            &[TensorUpload {
                tensor: inp_token.as_ptr(),
                bytes: slice_as_bytes(std::slice::from_ref(&token_id)),
            }],
            &mut [TensorDownload {
                tensor: rows,
                bytes: slice_as_bytes_mut(data.as_mut_slice()),
            }],
            thread_count,
            "code predictor embedding lookup failed",
        )?;
        Ok(data)
    }

    fn forward_code_pred_prefill_cached(
        &self,
        hidden_state: &[f32],
        codebook_0_token: i32,
        thread_count: usize,
        cache: &CodePredKvCache,
    ) -> Result<CodePredStepOutputs, Qwen3TtsError> {
        let hidden_size = self.config.hidden_size as usize;
        if hidden_state.len() != hidden_size {
            return Err(Qwen3TtsError::InvalidInput(
                "code predictor hidden state shape is invalid".into(),
            ));
        }
        if codebook_0_token < 0 || codebook_0_token >= self.config.codec_vocab_size {
            return Err(Qwen3TtsError::InvalidInput(format!(
                "codec token {codebook_0_token} out of range 0..{}",
                self.config.codec_vocab_size - 1
            )));
        }

        let graph_nodes = 2048;
        let ctx = ComputeContext::new_graph(graph_nodes)?;
        let graph = unsafe { sys::ggml_new_graph_custom(ctx.as_ptr(), graph_nodes, false) };
        let graph = NonNull::new(graph).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("failed to allocate code predictor prefill graph".into())
        })?;

        let inp_hidden = unsafe {
            sys::ggml_new_tensor_1d(
                ctx.as_ptr(),
                sys::ggml_type_GGML_TYPE_F32,
                hidden_size as i64,
            )
        };
        let inp_hidden = NonNull::new(inp_hidden).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("failed to allocate code predictor hidden input".into())
        })?;

        let inp_cb0_embd = unsafe {
            sys::ggml_new_tensor_2d(
                ctx.as_ptr(),
                sys::ggml_type_GGML_TYPE_F32,
                hidden_size as i64,
                1,
            )
        };
        let inp_cb0_embd = NonNull::new(inp_cb0_embd).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("failed to allocate code predictor cb0 embedding".into())
        })?;

        let inp_pos =
            unsafe { sys::ggml_new_tensor_1d(ctx.as_ptr(), sys::ggml_type_GGML_TYPE_I32, 2) };
        let inp_pos = NonNull::new(inp_pos).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("failed to allocate code predictor positions".into())
        })?;
        let positions = [0i32, 1i32];

        let hidden_2d = unsafe {
            sys::ggml_reshape_2d(ctx.as_ptr(), inp_hidden.as_ptr(), hidden_size as i64, 1)
        };
        let mut inp_l =
            unsafe { sys::ggml_concat(ctx.as_ptr(), hidden_2d, inp_cb0_embd.as_ptr(), 1) };
        inp_l = self.code_pred.project_input(ctx.as_ptr(), inp_l);
        let kq_scale = 1.0f32 / (self.code_pred_config.head_dim as f32).sqrt();
        let mut attn_softmax_mask: Option<(*mut sys::ggml_tensor, Vec<f32>)> = None;

        for (layer_idx, layer) in self.code_pred.layers.iter().enumerate() {
            let mut cur = unsafe {
                sys::ggml_rms_norm(ctx.as_ptr(), inp_l, self.code_pred_config.rms_norm_eps)
            };
            cur = unsafe { sys::ggml_mul(ctx.as_ptr(), cur, layer.attn_norm.as_ptr()) };
            let mut q_cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.attn_q.as_ptr(), cur) };
            let mut k_cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.attn_k.as_ptr(), cur) };
            let mut v_cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.attn_v.as_ptr(), cur) };
            q_cur = unsafe {
                sys::ggml_reshape_3d(
                    ctx.as_ptr(),
                    q_cur,
                    self.code_pred_config.head_dim as i64,
                    self.code_pred_config.n_attention_heads as i64,
                    2,
                )
            };
            k_cur = unsafe {
                sys::ggml_reshape_3d(
                    ctx.as_ptr(),
                    k_cur,
                    self.code_pred_config.head_dim as i64,
                    self.code_pred_config.n_key_value_heads as i64,
                    2,
                )
            };
            v_cur = unsafe {
                sys::ggml_reshape_3d(
                    ctx.as_ptr(),
                    v_cur,
                    self.code_pred_config.head_dim as i64,
                    self.code_pred_config.n_key_value_heads as i64,
                    2,
                )
            };

            if let Some(attn_q_norm) = layer.attn_q_norm {
                q_cur = unsafe {
                    sys::ggml_rms_norm(ctx.as_ptr(), q_cur, self.code_pred_config.rms_norm_eps)
                };
                q_cur = unsafe { sys::ggml_mul(ctx.as_ptr(), q_cur, attn_q_norm.as_ptr()) };
            }
            if let Some(attn_k_norm) = layer.attn_k_norm {
                k_cur = unsafe {
                    sys::ggml_rms_norm(ctx.as_ptr(), k_cur, self.code_pred_config.rms_norm_eps)
                };
                k_cur = unsafe { sys::ggml_mul(ctx.as_ptr(), k_cur, attn_k_norm.as_ptr()) };
            }

            q_cur = unsafe {
                sys::ggml_rope_ext(
                    ctx.as_ptr(),
                    q_cur,
                    inp_pos.as_ptr(),
                    std::ptr::null_mut(),
                    self.code_pred_config.head_dim,
                    sys::GGML_ROPE_TYPE_NEOX as i32,
                    0,
                    self.code_pred_config.rope_theta,
                    1.0,
                    0.0,
                    1.0,
                    0.0,
                    0.0,
                )
            };
            k_cur = unsafe {
                sys::ggml_rope_ext(
                    ctx.as_ptr(),
                    k_cur,
                    inp_pos.as_ptr(),
                    std::ptr::null_mut(),
                    self.code_pred_config.head_dim,
                    sys::GGML_ROPE_TYPE_NEOX as i32,
                    0,
                    self.code_pred_config.rope_theta,
                    1.0,
                    0.0,
                    1.0,
                    0.0,
                    0.0,
                )
            };

            let k_cache = cache.k_cache[layer_idx].as_ptr();
            let v_cache = cache.v_cache[layer_idx].as_ptr();
            let k_cache_view = unsafe {
                sys::ggml_view_3d(
                    ctx.as_ptr(),
                    k_cache,
                    self.code_pred_config.head_dim as i64,
                    self.code_pred_config.n_key_value_heads as i64,
                    2,
                    (*k_cache).nb[1],
                    (*k_cache).nb[2],
                    0,
                )
            };
            let v_cache_view = unsafe {
                sys::ggml_view_3d(
                    ctx.as_ptr(),
                    v_cache,
                    self.code_pred_config.head_dim as i64,
                    self.code_pred_config.n_key_value_heads as i64,
                    2,
                    (*v_cache).nb[1],
                    (*v_cache).nb[2],
                    0,
                )
            };
            unsafe {
                sys::ggml_build_forward_expand(
                    graph.as_ptr(),
                    sys::ggml_cpy(ctx.as_ptr(), k_cur, k_cache_view),
                );
                sys::ggml_build_forward_expand(
                    graph.as_ptr(),
                    sys::ggml_cpy(ctx.as_ptr(), v_cur, v_cache_view),
                );
            }

            let q = unsafe { sys::ggml_permute(ctx.as_ptr(), q_cur, 0, 2, 1, 3) };
            let k = unsafe { sys::ggml_permute(ctx.as_ptr(), k_cur, 0, 2, 1, 3) };
            let mut v = unsafe { sys::ggml_permute(ctx.as_ptr(), v_cur, 0, 2, 1, 3) };
            let mut kq = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), k, q) };
            kq = unsafe { sys::ggml_scale(ctx.as_ptr(), kq, kq_scale) };
            kq = unsafe {
                ggml_soft_max_ext_with_diag_mask_cache(ctx.as_ptr(), kq, 0, &mut attn_softmax_mask)
            };
            v = unsafe { sys::ggml_cont(ctx.as_ptr(), sys::ggml_transpose(ctx.as_ptr(), v)) };
            let mut kqv = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), v, kq) };
            kqv = unsafe { sys::ggml_permute(ctx.as_ptr(), kqv, 0, 2, 1, 3) };
            cur = unsafe {
                sys::ggml_cont_2d(
                    ctx.as_ptr(),
                    kqv,
                    (self.code_pred_config.n_attention_heads * self.code_pred_config.head_dim)
                        as i64,
                    2,
                )
            };
            cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.attn_output.as_ptr(), cur) };
            cur = unsafe { sys::ggml_add(ctx.as_ptr(), cur, inp_l) };
            let inp_ff = cur;
            cur = unsafe {
                sys::ggml_rms_norm(ctx.as_ptr(), inp_ff, self.code_pred_config.rms_norm_eps)
            };
            cur = unsafe { sys::ggml_mul(ctx.as_ptr(), cur, layer.ffn_norm.as_ptr()) };
            let mut gate = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.ffn_gate.as_ptr(), cur) };
            let up = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.ffn_up.as_ptr(), cur) };
            gate = unsafe { sys::ggml_silu(ctx.as_ptr(), gate) };
            cur = unsafe { sys::ggml_mul(ctx.as_ptr(), gate, up) };
            let ffn_down_f32 = layer
                .ffn_down_f32
                .map(NonNull::as_ptr)
                .unwrap_or_else(|| unsafe {
                    sys::ggml_cast(
                        ctx.as_ptr(),
                        layer.ffn_down.as_ptr(),
                        sys::ggml_type_GGML_TYPE_F32,
                    )
                });
            cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), ffn_down_f32, cur) };
            inp_l = unsafe { sys::ggml_add(ctx.as_ptr(), cur, inp_ff) };
        }

        let mut cur =
            unsafe { sys::ggml_rms_norm(ctx.as_ptr(), inp_l, self.code_pred_config.rms_norm_eps) };
        cur = unsafe { sys::ggml_mul(ctx.as_ptr(), cur, self.code_pred.output_norm.as_ptr()) };
        let last_hidden = unsafe {
            sys::ggml_view_2d(
                ctx.as_ptr(),
                cur,
                self.code_pred_config.hidden_size as i64,
                1,
                (*cur).nb[1],
                (*cur).nb[1],
            )
        };
        let mut logits = unsafe {
            sys::ggml_mul_mat(ctx.as_ptr(), self.code_pred.heads[0].as_ptr(), last_hidden)
        };
        logits = unsafe { sys::ggml_cont(ctx.as_ptr(), logits) };
        unsafe {
            sys::ggml_build_forward_expand(graph.as_ptr(), logits);
        }

        let mut logits_data = vec![0.0f32; self.code_pred_config.vocab_size as usize];
        let cb0_embd = self.lookup_codec_embedding_rows(&[codebook_0_token], thread_count)?;
        let mut uploads = vec![
            TensorUpload {
                tensor: inp_hidden.as_ptr(),
                bytes: slice_as_bytes(hidden_state),
            },
            TensorUpload {
                tensor: inp_cb0_embd.as_ptr(),
                bytes: slice_as_bytes(cb0_embd.as_slice()),
            },
            TensorUpload {
                tensor: inp_pos.as_ptr(),
                bytes: slice_as_bytes(&positions),
            },
        ];
        if let Some((t, data)) = &attn_softmax_mask {
            uploads.push(TensorUpload {
                tensor: *t,
                bytes: slice_as_bytes(data.as_slice()),
            });
        }
        execute_graph(
            &cache._backends,
            graph,
            uploads.as_slice(),
            &mut [TensorDownload {
                tensor: logits,
                bytes: slice_as_bytes_mut(logits_data.as_mut_slice()),
            }],
            thread_count,
            "code predictor prefill graph execution failed",
        )?;
        Ok(CodePredStepOutputs {
            logits: logits_data,
        })
    }

    fn forward_code_pred_step_cached(
        &self,
        prev_code: i32,
        n_past: usize,
        generation_step: usize,
        thread_count: usize,
        cache: &CodePredKvCache,
    ) -> Result<CodePredStepOutputs, Qwen3TtsError> {
        if generation_step == 0 || generation_step >= self.code_pred.heads.len() {
            return Err(Qwen3TtsError::InvalidInput(
                "code predictor generation step out of range".into(),
            ));
        }
        if n_past >= cache.n_ctx {
            return Err(Qwen3TtsError::InvalidInput(
                "code predictor context length exceeded".into(),
            ));
        }

        let hidden_size = self.config.hidden_size as usize;
        let graph_nodes = 2048;
        let ctx = ComputeContext::new_graph(graph_nodes)?;
        let graph = unsafe { sys::ggml_new_graph_custom(ctx.as_ptr(), graph_nodes, false) };
        let graph = NonNull::new(graph).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("failed to allocate code predictor step graph".into())
        })?;

        let inp_code =
            unsafe { sys::ggml_new_tensor_1d(ctx.as_ptr(), sys::ggml_type_GGML_TYPE_I32, 1) };
        let inp_code = NonNull::new(inp_code).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("failed to allocate code predictor token input".into())
        })?;

        let inp_pos =
            unsafe { sys::ggml_new_tensor_1d(ctx.as_ptr(), sys::ggml_type_GGML_TYPE_I32, 1) };
        let inp_pos = NonNull::new(inp_pos).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("failed to allocate code predictor position input".into())
        })?;
        let pos = n_past as i32;

        let weight = self
            .code_pred
            .embeddings
            .get(generation_step - 1)
            .ok_or_else(|| {
                Qwen3TtsError::InvalidInput("missing code predictor embedding".into())
            })?;
        let mut inp_l =
            unsafe { sys::ggml_get_rows(ctx.as_ptr(), weight.as_ptr(), inp_code.as_ptr()) };
        inp_l = unsafe { sys::ggml_reshape_2d(ctx.as_ptr(), inp_l, hidden_size as i64, 1) };
        inp_l = self.code_pred.project_input(ctx.as_ptr(), inp_l);
        let kq_scale = 1.0f32 / (self.code_pred_config.head_dim as f32).sqrt();
        let mut attn_softmax_mask: Option<(*mut sys::ggml_tensor, Vec<f32>)> = None;

        for (layer_idx, layer) in self.code_pred.layers.iter().enumerate() {
            let mut cur = unsafe {
                sys::ggml_rms_norm(ctx.as_ptr(), inp_l, self.code_pred_config.rms_norm_eps)
            };
            cur = unsafe { sys::ggml_mul(ctx.as_ptr(), cur, layer.attn_norm.as_ptr()) };
            let mut q_cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.attn_q.as_ptr(), cur) };
            let mut k_cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.attn_k.as_ptr(), cur) };
            let mut v_cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.attn_v.as_ptr(), cur) };
            q_cur = unsafe {
                sys::ggml_reshape_3d(
                    ctx.as_ptr(),
                    q_cur,
                    self.code_pred_config.head_dim as i64,
                    self.code_pred_config.n_attention_heads as i64,
                    1,
                )
            };
            k_cur = unsafe {
                sys::ggml_reshape_3d(
                    ctx.as_ptr(),
                    k_cur,
                    self.code_pred_config.head_dim as i64,
                    self.code_pred_config.n_key_value_heads as i64,
                    1,
                )
            };
            v_cur = unsafe {
                sys::ggml_reshape_3d(
                    ctx.as_ptr(),
                    v_cur,
                    self.code_pred_config.head_dim as i64,
                    self.code_pred_config.n_key_value_heads as i64,
                    1,
                )
            };

            if let Some(attn_q_norm) = layer.attn_q_norm {
                q_cur = unsafe {
                    sys::ggml_rms_norm(ctx.as_ptr(), q_cur, self.code_pred_config.rms_norm_eps)
                };
                q_cur = unsafe { sys::ggml_mul(ctx.as_ptr(), q_cur, attn_q_norm.as_ptr()) };
            }
            if let Some(attn_k_norm) = layer.attn_k_norm {
                k_cur = unsafe {
                    sys::ggml_rms_norm(ctx.as_ptr(), k_cur, self.code_pred_config.rms_norm_eps)
                };
                k_cur = unsafe { sys::ggml_mul(ctx.as_ptr(), k_cur, attn_k_norm.as_ptr()) };
            }

            q_cur = unsafe {
                sys::ggml_rope_ext(
                    ctx.as_ptr(),
                    q_cur,
                    inp_pos.as_ptr(),
                    std::ptr::null_mut(),
                    self.code_pred_config.head_dim,
                    sys::GGML_ROPE_TYPE_NEOX as i32,
                    0,
                    self.code_pred_config.rope_theta,
                    1.0,
                    0.0,
                    1.0,
                    0.0,
                    0.0,
                )
            };
            k_cur = unsafe {
                sys::ggml_rope_ext(
                    ctx.as_ptr(),
                    k_cur,
                    inp_pos.as_ptr(),
                    std::ptr::null_mut(),
                    self.code_pred_config.head_dim,
                    sys::GGML_ROPE_TYPE_NEOX as i32,
                    0,
                    self.code_pred_config.rope_theta,
                    1.0,
                    0.0,
                    1.0,
                    0.0,
                    0.0,
                )
            };

            let k_cache = cache.k_cache[layer_idx].as_ptr();
            let v_cache = cache.v_cache[layer_idx].as_ptr();
            let k_cache_view = unsafe {
                sys::ggml_view_3d(
                    ctx.as_ptr(),
                    k_cache,
                    self.code_pred_config.head_dim as i64,
                    self.code_pred_config.n_key_value_heads as i64,
                    1,
                    (*k_cache).nb[1],
                    (*k_cache).nb[2],
                    n_past * (*k_cache).nb[2],
                )
            };
            let v_cache_view = unsafe {
                sys::ggml_view_3d(
                    ctx.as_ptr(),
                    v_cache,
                    self.code_pred_config.head_dim as i64,
                    self.code_pred_config.n_key_value_heads as i64,
                    1,
                    (*v_cache).nb[1],
                    (*v_cache).nb[2],
                    n_past * (*v_cache).nb[2],
                )
            };
            unsafe {
                sys::ggml_build_forward_expand(
                    graph.as_ptr(),
                    sys::ggml_cpy(ctx.as_ptr(), k_cur, k_cache_view),
                );
                sys::ggml_build_forward_expand(
                    graph.as_ptr(),
                    sys::ggml_cpy(ctx.as_ptr(), v_cur, v_cache_view),
                );
            }

            let n_kv = n_past + 1;
            let mut k = unsafe {
                sys::ggml_view_3d(
                    ctx.as_ptr(),
                    k_cache,
                    self.code_pred_config.head_dim as i64,
                    self.code_pred_config.n_key_value_heads as i64,
                    n_kv as i64,
                    (*k_cache).nb[1],
                    (*k_cache).nb[2],
                    0,
                )
            };
            let mut v = unsafe {
                sys::ggml_view_3d(
                    ctx.as_ptr(),
                    v_cache,
                    self.code_pred_config.head_dim as i64,
                    self.code_pred_config.n_key_value_heads as i64,
                    n_kv as i64,
                    (*v_cache).nb[1],
                    (*v_cache).nb[2],
                    0,
                )
            };
            let q = unsafe { sys::ggml_permute(ctx.as_ptr(), q_cur, 0, 2, 1, 3) };
            k = unsafe { sys::ggml_permute(ctx.as_ptr(), k, 0, 2, 1, 3) };
            v = unsafe { sys::ggml_permute(ctx.as_ptr(), v, 0, 2, 1, 3) };
            let mut kq = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), k, q) };
            kq = unsafe { sys::ggml_scale(ctx.as_ptr(), kq, kq_scale) };
            kq = unsafe {
                ggml_soft_max_ext_with_diag_mask_cache(
                    ctx.as_ptr(),
                    kq,
                    n_past as i32,
                    &mut attn_softmax_mask,
                )
            };
            v = unsafe { sys::ggml_cont(ctx.as_ptr(), sys::ggml_transpose(ctx.as_ptr(), v)) };
            let mut kqv = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), v, kq) };
            kqv = unsafe { sys::ggml_permute(ctx.as_ptr(), kqv, 0, 2, 1, 3) };
            cur = unsafe {
                sys::ggml_cont_2d(
                    ctx.as_ptr(),
                    kqv,
                    (self.code_pred_config.n_attention_heads * self.code_pred_config.head_dim)
                        as i64,
                    1,
                )
            };
            cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.attn_output.as_ptr(), cur) };
            cur = unsafe { sys::ggml_add(ctx.as_ptr(), cur, inp_l) };
            let inp_ff = cur;
            cur = unsafe {
                sys::ggml_rms_norm(ctx.as_ptr(), inp_ff, self.code_pred_config.rms_norm_eps)
            };
            cur = unsafe { sys::ggml_mul(ctx.as_ptr(), cur, layer.ffn_norm.as_ptr()) };
            let mut gate = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.ffn_gate.as_ptr(), cur) };
            let up = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.ffn_up.as_ptr(), cur) };
            gate = unsafe { sys::ggml_silu(ctx.as_ptr(), gate) };
            cur = unsafe { sys::ggml_mul(ctx.as_ptr(), gate, up) };
            let ffn_down_f32 = layer
                .ffn_down_f32
                .map(NonNull::as_ptr)
                .unwrap_or_else(|| unsafe {
                    sys::ggml_cast(
                        ctx.as_ptr(),
                        layer.ffn_down.as_ptr(),
                        sys::ggml_type_GGML_TYPE_F32,
                    )
                });
            cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), ffn_down_f32, cur) };
            inp_l = unsafe { sys::ggml_add(ctx.as_ptr(), cur, inp_ff) };
        }

        let mut cur =
            unsafe { sys::ggml_rms_norm(ctx.as_ptr(), inp_l, self.code_pred_config.rms_norm_eps) };
        cur = unsafe { sys::ggml_mul(ctx.as_ptr(), cur, self.code_pred.output_norm.as_ptr()) };
        let mut logits = unsafe {
            sys::ggml_mul_mat(
                ctx.as_ptr(),
                self.code_pred.heads[generation_step].as_ptr(),
                cur,
            )
        };
        logits = unsafe { sys::ggml_cont(ctx.as_ptr(), logits) };
        unsafe {
            sys::ggml_build_forward_expand(graph.as_ptr(), logits);
        }

        let mut logits_data = vec![0.0f32; self.code_pred_config.vocab_size as usize];
        let mut uploads = vec![
            TensorUpload {
                tensor: inp_code.as_ptr(),
                bytes: slice_as_bytes(std::slice::from_ref(&prev_code)),
            },
            TensorUpload {
                tensor: inp_pos.as_ptr(),
                bytes: slice_as_bytes(std::slice::from_ref(&pos)),
            },
        ];
        if let Some((t, data)) = &attn_softmax_mask {
            uploads.push(TensorUpload {
                tensor: *t,
                bytes: slice_as_bytes(data.as_slice()),
            });
        }
        execute_graph(
            &cache._backends,
            graph,
            uploads.as_slice(),
            &mut [TensorDownload {
                tensor: logits,
                bytes: slice_as_bytes_mut(logits_data.as_mut_slice()),
            }],
            thread_count,
            "code predictor step graph execution failed",
        )?;
        Ok(CodePredStepOutputs {
            logits: logits_data,
        })
    }

    fn build_talker_step_embedding(
        &self,
        codebook_tokens: &[i32],
        trailing_row: &[f32],
        thread_count: usize,
    ) -> Result<Vec<f32>, Qwen3TtsError> {
        let hidden_size = self.config.hidden_size as usize;
        if codebook_tokens.len() != self.config.n_codebooks as usize {
            return Err(Qwen3TtsError::InvalidInput(
                "full codebook frame is required for step embedding".into(),
            ));
        }
        if trailing_row.len() != hidden_size {
            return Err(Qwen3TtsError::InvalidInput(
                "trailing row shape is invalid".into(),
            ));
        }
        let mut cpu_sum = self.sum_codec_frame_embeddings(codebook_tokens, thread_count)?;
        for i in 0..hidden_size {
            cpu_sum[i] += trailing_row[i];
        }
        if self.talker.codec_embd_cpu.is_some() && self.code_pred.codec_embd_cpu.is_some() {
            return Ok(cpu_sum);
        }

        let graph_nodes = 128;
        let ctx = ComputeContext::new_graph(graph_nodes)?;
        let graph = unsafe { sys::ggml_new_graph_custom(ctx.as_ptr(), graph_nodes, false) };
        let graph = NonNull::new(graph).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("failed to allocate step embedding graph".into())
        })?;

        let inp_trailing = unsafe {
            sys::ggml_new_tensor_2d(
                ctx.as_ptr(),
                sys::ggml_type_GGML_TYPE_F32,
                hidden_size as i64,
                1,
            )
        };
        let inp_trailing = NonNull::new(inp_trailing).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("failed to allocate trailing row input".into())
        })?;
        let inp_cb0 =
            unsafe { sys::ggml_new_tensor_1d(ctx.as_ptr(), sys::ggml_type_GGML_TYPE_I32, 1) };
        let inp_cb0 = NonNull::new(inp_cb0).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("failed to allocate codec token input".into())
        })?;

        let mut cur = unsafe {
            sys::ggml_get_rows(
                ctx.as_ptr(),
                self.talker.codec_embd.as_ptr(),
                inp_cb0.as_ptr(),
            )
        };
        cur = unsafe { sys::ggml_cast(ctx.as_ptr(), cur, sys::ggml_type_GGML_TYPE_F32) };

        let mut code_inputs = Vec::with_capacity(codebook_tokens.len().saturating_sub(1));
        for (cb_idx, weight) in self.code_pred.embeddings.iter().enumerate() {
            let inp_code =
                unsafe { sys::ggml_new_tensor_1d(ctx.as_ptr(), sys::ggml_type_GGML_TYPE_I32, 1) };
            let inp_code = NonNull::new(inp_code).ok_or_else(|| {
                Qwen3TtsError::InvalidInput("failed to allocate code predictor token input".into())
            })?;
            let mut embd =
                unsafe { sys::ggml_get_rows(ctx.as_ptr(), weight.as_ptr(), inp_code.as_ptr()) };
            embd = unsafe { sys::ggml_cast(ctx.as_ptr(), embd, sys::ggml_type_GGML_TYPE_F32) };
            cur = unsafe { sys::ggml_add(ctx.as_ptr(), cur, embd) };
            code_inputs.push((cb_idx, inp_code));
        }
        cur = unsafe { sys::ggml_add(ctx.as_ptr(), cur, inp_trailing.as_ptr()) };

        unsafe {
            sys::ggml_build_forward_expand(graph.as_ptr(), cur);
        }

        let mut step_embd = vec![0.0f32; hidden_size];
        let mut uploads = Vec::with_capacity(code_inputs.len() + 2);
        uploads.push(TensorUpload {
            tensor: inp_trailing.as_ptr(),
            bytes: slice_as_bytes(trailing_row),
        });
        uploads.push(TensorUpload {
            tensor: inp_cb0.as_ptr(),
            bytes: slice_as_bytes(std::slice::from_ref(&codebook_tokens[0])),
        });
        for (cb_idx, inp_code) in &code_inputs {
            uploads.push(TensorUpload {
                tensor: inp_code.as_ptr(),
                bytes: slice_as_bytes(std::slice::from_ref(&codebook_tokens[*cb_idx + 1])),
            });
        }

        execute_graph(
            &self.talker._backends,
            graph,
            uploads.as_slice(),
            &mut [TensorDownload {
                tensor: cur,
                bytes: slice_as_bytes_mut(step_embd.as_mut_slice()),
            }],
            thread_count,
            "step embedding graph execution failed",
        )?;
        Ok(step_embd)
    }

    fn forward_prefill_cached(
        &self,
        prefill_embd: &[f32],
        thread_count: usize,
        cache: &TalkerKvCache,
    ) -> Result<StepForwardOutputs, Qwen3TtsError> {
        let hidden_size = self.config.hidden_size as usize;
        if prefill_embd.is_empty() || !prefill_embd.len().is_multiple_of(hidden_size) {
            return Err(Qwen3TtsError::InvalidInput(
                "prefill embedding shape is invalid".into(),
            ));
        }

        let n_tokens = prefill_embd.len() / hidden_size;
        if n_tokens > cache.n_ctx {
            return Err(Qwen3TtsError::InvalidInput(
                "talker context length exceeded".into(),
            ));
        }

        let graph_nodes = 4096;
        let ctx = ComputeContext::new_graph(graph_nodes)?;
        let graph = unsafe { sys::ggml_new_graph_custom(ctx.as_ptr(), graph_nodes, false) };
        let graph = NonNull::new(graph).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("failed to allocate cached prefill graph".into())
        })?;

        let inp_prefill_embd = unsafe {
            sys::ggml_new_tensor_2d(
                ctx.as_ptr(),
                sys::ggml_type_GGML_TYPE_F32,
                hidden_size as i64,
                n_tokens as i64,
            )
        };
        let inp_prefill_embd = NonNull::new(inp_prefill_embd).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("failed to allocate prefill input".into())
        })?;

        let inp_pos = unsafe {
            sys::ggml_new_tensor_1d(ctx.as_ptr(), sys::ggml_type_GGML_TYPE_I32, n_tokens as i64)
        };
        let inp_pos = NonNull::new(inp_pos).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("failed to allocate position input".into())
        })?;
        let positions = (0..n_tokens as i32).collect::<Vec<_>>();

        let mut inp_l = inp_prefill_embd.as_ptr();
        let kq_scale = 1.0f32 / (self.config.head_dim as f32).sqrt();
        let mut attn_softmax_mask: Option<(*mut sys::ggml_tensor, Vec<f32>)> = None;
        let mut kv_writeback = Vec::<KvWritebackTensorDownloads>::new();

        for (layer_idx, layer) in self.talker.layers.iter().enumerate() {
            let mut cur =
                unsafe { sys::ggml_rms_norm(ctx.as_ptr(), inp_l, self.config.rms_norm_eps) };
            cur = unsafe { sys::ggml_mul(ctx.as_ptr(), cur, layer.attn_norm.as_ptr()) };

            let mut q_cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.attn_q.as_ptr(), cur) };
            let mut k_cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.attn_k.as_ptr(), cur) };
            let mut v_cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.attn_v.as_ptr(), cur) };

            q_cur = unsafe {
                sys::ggml_reshape_3d(
                    ctx.as_ptr(),
                    q_cur,
                    self.config.head_dim as i64,
                    self.config.n_attention_heads as i64,
                    n_tokens as i64,
                )
            };
            k_cur = unsafe {
                sys::ggml_reshape_3d(
                    ctx.as_ptr(),
                    k_cur,
                    self.config.head_dim as i64,
                    self.config.n_key_value_heads as i64,
                    n_tokens as i64,
                )
            };
            v_cur = unsafe {
                sys::ggml_reshape_3d(
                    ctx.as_ptr(),
                    v_cur,
                    self.config.head_dim as i64,
                    self.config.n_key_value_heads as i64,
                    n_tokens as i64,
                )
            };

            if let Some(attn_q_norm) = layer.attn_q_norm {
                q_cur =
                    unsafe { sys::ggml_rms_norm(ctx.as_ptr(), q_cur, self.config.rms_norm_eps) };
                q_cur = unsafe { sys::ggml_mul(ctx.as_ptr(), q_cur, attn_q_norm.as_ptr()) };
            }
            if let Some(attn_k_norm) = layer.attn_k_norm {
                k_cur =
                    unsafe { sys::ggml_rms_norm(ctx.as_ptr(), k_cur, self.config.rms_norm_eps) };
                k_cur = unsafe { sys::ggml_mul(ctx.as_ptr(), k_cur, attn_k_norm.as_ptr()) };
            }

            q_cur = unsafe {
                sys::ggml_rope_ext(
                    ctx.as_ptr(),
                    q_cur,
                    inp_pos.as_ptr(),
                    std::ptr::null_mut(),
                    self.config.head_dim,
                    sys::GGML_ROPE_TYPE_NEOX as i32,
                    0,
                    self.config.rope_theta,
                    1.0,
                    0.0,
                    1.0,
                    0.0,
                    0.0,
                )
            };
            k_cur = unsafe {
                sys::ggml_rope_ext(
                    ctx.as_ptr(),
                    k_cur,
                    inp_pos.as_ptr(),
                    std::ptr::null_mut(),
                    self.config.head_dim,
                    sys::GGML_ROPE_TYPE_NEOX as i32,
                    0,
                    self.config.rope_theta,
                    1.0,
                    0.0,
                    1.0,
                    0.0,
                    0.0,
                )
            };

            match cache.storage() {
                TalkerKvStorage::F16 => {
                    let k_cache = cache.k_cache[layer_idx].as_ptr();
                    let v_cache = cache.v_cache[layer_idx].as_ptr();
                    let k_cache_view = unsafe {
                        sys::ggml_view_3d(
                            ctx.as_ptr(),
                            k_cache,
                            self.config.head_dim as i64,
                            self.config.n_key_value_heads as i64,
                            n_tokens as i64,
                            (*k_cache).nb[1],
                            (*k_cache).nb[2],
                            0,
                        )
                    };
                    let v_cache_view = unsafe {
                        sys::ggml_view_3d(
                            ctx.as_ptr(),
                            v_cache,
                            self.config.head_dim as i64,
                            self.config.n_key_value_heads as i64,
                            n_tokens as i64,
                            (*v_cache).nb[1],
                            (*v_cache).nb[2],
                            0,
                        )
                    };
                    unsafe {
                        sys::ggml_build_forward_expand(
                            graph.as_ptr(),
                            sys::ggml_cpy(ctx.as_ptr(), k_cur, k_cache_view),
                        );
                        sys::ggml_build_forward_expand(
                            graph.as_ptr(),
                            sys::ggml_cpy(ctx.as_ptr(), v_cur, v_cache_view),
                        );
                    }
                }
                TalkerKvStorage::TurboQuantQ8_0 => {
                    let k_store = unsafe { sys::ggml_cont(ctx.as_ptr(), k_cur) };
                    let v_store = unsafe { sys::ggml_cont(ctx.as_ptr(), v_cur) };
                    unsafe {
                        sys::ggml_build_forward_expand(graph.as_ptr(), k_store);
                        sys::ggml_build_forward_expand(graph.as_ptr(), v_store);
                    }
                    let rows = self.config.n_key_value_heads as usize
                        * n_tokens
                        * self.config.head_dim as usize;
                    kv_writeback.push(KvWritebackTensorDownloads {
                        layer_idx,
                        token_start: 0,
                        n_tokens,
                        k_tensor: k_store,
                        v_tensor: v_store,
                        k_data: vec![0.0; rows],
                        v_data: vec![0.0; rows],
                    });
                }
            }

            let q = unsafe { sys::ggml_permute(ctx.as_ptr(), q_cur, 0, 2, 1, 3) };
            let k = unsafe { sys::ggml_permute(ctx.as_ptr(), k_cur, 0, 2, 1, 3) };
            let mut v = unsafe { sys::ggml_permute(ctx.as_ptr(), v_cur, 0, 2, 1, 3) };

            let mut kq = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), k, q) };
            kq = unsafe { sys::ggml_scale(ctx.as_ptr(), kq, kq_scale) };
            kq = unsafe {
                ggml_soft_max_ext_with_diag_mask_cache(ctx.as_ptr(), kq, 0, &mut attn_softmax_mask)
            };

            v = unsafe { sys::ggml_cont(ctx.as_ptr(), sys::ggml_transpose(ctx.as_ptr(), v)) };

            let mut kqv = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), v, kq) };
            kqv = unsafe { sys::ggml_permute(ctx.as_ptr(), kqv, 0, 2, 1, 3) };
            cur = unsafe {
                sys::ggml_cont_2d(
                    ctx.as_ptr(),
                    kqv,
                    (self.config.n_attention_heads * self.config.head_dim) as i64,
                    n_tokens as i64,
                )
            };

            cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.attn_output.as_ptr(), cur) };
            cur = unsafe { sys::ggml_add(ctx.as_ptr(), cur, inp_l) };
            let inp_ff = cur;

            cur = unsafe { sys::ggml_rms_norm(ctx.as_ptr(), inp_ff, self.config.rms_norm_eps) };
            cur = unsafe { sys::ggml_mul(ctx.as_ptr(), cur, layer.ffn_norm.as_ptr()) };

            let mut gate = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.ffn_gate.as_ptr(), cur) };
            let up = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.ffn_up.as_ptr(), cur) };
            gate = unsafe { sys::ggml_silu(ctx.as_ptr(), gate) };
            cur = unsafe { sys::ggml_mul(ctx.as_ptr(), gate, up) };

            let ffn_down_f32 = layer
                .ffn_down_f32
                .map(NonNull::as_ptr)
                .unwrap_or_else(|| unsafe {
                    sys::ggml_cast(
                        ctx.as_ptr(),
                        layer.ffn_down.as_ptr(),
                        sys::ggml_type_GGML_TYPE_F32,
                    )
                });
            cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), ffn_down_f32, cur) };
            inp_l = unsafe { sys::ggml_add(ctx.as_ptr(), cur, inp_ff) };
        }

        let mut hidden_states =
            unsafe { sys::ggml_rms_norm(ctx.as_ptr(), inp_l, self.config.rms_norm_eps) };
        hidden_states = unsafe {
            sys::ggml_mul(
                ctx.as_ptr(),
                hidden_states,
                self.talker.output_norm.as_ptr(),
            )
        };
        let last_hidden = unsafe {
            sys::ggml_view_2d(
                ctx.as_ptr(),
                hidden_states,
                hidden_size as i64,
                1,
                (*hidden_states).nb[1],
                (n_tokens - 1) * (*hidden_states).nb[1],
            )
        };
        let last_hidden = unsafe { sys::ggml_cont(ctx.as_ptr(), last_hidden) };
        self.retain_projected_predictor_hidden(last_hidden);
        let mut logits = unsafe {
            sys::ggml_mul_mat(ctx.as_ptr(), self.talker.codec_head.as_ptr(), last_hidden)
        };
        logits = unsafe { sys::ggml_cont(ctx.as_ptr(), logits) };

        unsafe {
            sys::ggml_build_forward_expand(graph.as_ptr(), last_hidden);
            sys::ggml_build_forward_expand(graph.as_ptr(), logits);
        }

        let mut hidden_data = vec![0.0f32; hidden_size];
        let mut logits_data = vec![0.0f32; self.config.codec_vocab_size as usize];
        let mut uploads = vec![
            TensorUpload {
                tensor: inp_prefill_embd.as_ptr(),
                bytes: slice_as_bytes(prefill_embd),
            },
            TensorUpload {
                tensor: inp_pos.as_ptr(),
                bytes: slice_as_bytes(positions.as_slice()),
            },
        ];
        if let Some((t, data)) = &attn_softmax_mask {
            uploads.push(TensorUpload {
                tensor: *t,
                bytes: slice_as_bytes(data.as_slice()),
            });
        }
        let mut downloads = vec![
            TensorDownload {
                tensor: last_hidden,
                bytes: slice_as_bytes_mut(hidden_data.as_mut_slice()),
            },
            TensorDownload {
                tensor: logits,
                bytes: slice_as_bytes_mut(logits_data.as_mut_slice()),
            },
        ];
        execute_graph(
            &cache._backends,
            graph,
            uploads.as_slice(),
            downloads.as_mut_slice(),
            thread_count,
            "cached prefill graph execution failed",
        )?;
        if cache.storage().is_quantized() {
            let layout = QuantizedKvWriteLayout {
                token_start: 0,
                n_tokens,
                rows_per_token: self.config.n_key_value_heads as usize,
                row_len: self.config.head_dim as usize,
            };
            for mut pending in kv_writeback {
                unsafe {
                    sys::ggml_backend_tensor_get(
                        pending.k_tensor,
                        pending.k_data.as_mut_ptr().cast(),
                        0,
                        std::mem::size_of_val(pending.k_data.as_slice()),
                    );
                    sys::ggml_backend_tensor_get(
                        pending.v_tensor,
                        pending.v_data.as_mut_ptr().cast(),
                        0,
                        std::mem::size_of_val(pending.v_data.as_slice()),
                    );
                }
                let _ = cache.quantized_write_layer(
                    pending.layer_idx,
                    QuantizedKvWriteLayout {
                        token_start: pending.token_start,
                        n_tokens: pending.n_tokens,
                        ..layout
                    },
                    pending.k_data.as_slice(),
                    pending.v_data.as_slice(),
                )?;
            }
        }

        Ok(StepForwardOutputs {
            hidden_state: hidden_data,
            logits: logits_data,
            kv_writeback_elapsed: Duration::ZERO,
            kv_download_elapsed: Duration::ZERO,
            kv_quantize_elapsed: Duration::ZERO,
            kv_upload_elapsed: Duration::ZERO,
        })
    }

    #[allow(dead_code)]
    fn forward_step_cached(
        &self,
        step_embd: &[f32],
        n_past: usize,
        thread_count: usize,
        cache: &TalkerKvCache,
    ) -> Result<StepForwardOutputs, Qwen3TtsError> {
        let hidden_size = self.config.hidden_size as usize;
        if step_embd.len() != hidden_size {
            return Err(Qwen3TtsError::InvalidInput(
                "step embedding shape is invalid".into(),
            ));
        }
        if n_past >= cache.n_ctx {
            return Err(Qwen3TtsError::InvalidInput(
                "talker context length exceeded".into(),
            ));
        }

        let graph_nodes = 4096;
        let ctx = ComputeContext::new_graph(graph_nodes)?;
        let graph = unsafe { sys::ggml_new_graph_custom(ctx.as_ptr(), graph_nodes, false) };
        let graph = NonNull::new(graph)
            .ok_or_else(|| Qwen3TtsError::InvalidInput("failed to allocate step graph".into()))?;

        let inp_step = unsafe {
            sys::ggml_new_tensor_2d(
                ctx.as_ptr(),
                sys::ggml_type_GGML_TYPE_F32,
                hidden_size as i64,
                1,
            )
        };
        let inp_step = NonNull::new(inp_step)
            .ok_or_else(|| Qwen3TtsError::InvalidInput("failed to allocate step input".into()))?;

        let inp_pos =
            unsafe { sys::ggml_new_tensor_1d(ctx.as_ptr(), sys::ggml_type_GGML_TYPE_I32, 1) };
        let inp_pos = NonNull::new(inp_pos).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("failed to allocate step position".into())
        })?;
        let pos = n_past as i32;

        let mut inp_l = inp_step.as_ptr();
        let kq_scale = 1.0f32 / (self.config.head_dim as f32).sqrt();
        let mut attn_softmax_mask: Option<(*mut sys::ggml_tensor, Vec<f32>)> = None;
        let mut kv_writeback = Vec::<KvWritebackTensorDownloads>::new();
        for (layer_idx, layer) in self.talker.layers.iter().enumerate() {
            let mut cur =
                unsafe { sys::ggml_rms_norm(ctx.as_ptr(), inp_l, self.config.rms_norm_eps) };
            cur = unsafe { sys::ggml_mul(ctx.as_ptr(), cur, layer.attn_norm.as_ptr()) };

            let mut q_cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.attn_q.as_ptr(), cur) };
            let mut k_cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.attn_k.as_ptr(), cur) };
            let mut v_cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.attn_v.as_ptr(), cur) };

            q_cur = unsafe {
                sys::ggml_reshape_3d(
                    ctx.as_ptr(),
                    q_cur,
                    self.config.head_dim as i64,
                    self.config.n_attention_heads as i64,
                    1,
                )
            };
            k_cur = unsafe {
                sys::ggml_reshape_3d(
                    ctx.as_ptr(),
                    k_cur,
                    self.config.head_dim as i64,
                    self.config.n_key_value_heads as i64,
                    1,
                )
            };
            v_cur = unsafe {
                sys::ggml_reshape_3d(
                    ctx.as_ptr(),
                    v_cur,
                    self.config.head_dim as i64,
                    self.config.n_key_value_heads as i64,
                    1,
                )
            };

            if let Some(attn_q_norm) = layer.attn_q_norm {
                q_cur =
                    unsafe { sys::ggml_rms_norm(ctx.as_ptr(), q_cur, self.config.rms_norm_eps) };
                q_cur = unsafe { sys::ggml_mul(ctx.as_ptr(), q_cur, attn_q_norm.as_ptr()) };
            }
            if let Some(attn_k_norm) = layer.attn_k_norm {
                k_cur =
                    unsafe { sys::ggml_rms_norm(ctx.as_ptr(), k_cur, self.config.rms_norm_eps) };
                k_cur = unsafe { sys::ggml_mul(ctx.as_ptr(), k_cur, attn_k_norm.as_ptr()) };
            }

            q_cur = unsafe {
                sys::ggml_rope_ext(
                    ctx.as_ptr(),
                    q_cur,
                    inp_pos.as_ptr(),
                    std::ptr::null_mut(),
                    self.config.head_dim,
                    sys::GGML_ROPE_TYPE_NEOX as i32,
                    0,
                    self.config.rope_theta,
                    1.0,
                    0.0,
                    1.0,
                    0.0,
                    0.0,
                )
            };
            k_cur = unsafe {
                sys::ggml_rope_ext(
                    ctx.as_ptr(),
                    k_cur,
                    inp_pos.as_ptr(),
                    std::ptr::null_mut(),
                    self.config.head_dim,
                    sys::GGML_ROPE_TYPE_NEOX as i32,
                    0,
                    self.config.rope_theta,
                    1.0,
                    0.0,
                    1.0,
                    0.0,
                    0.0,
                )
            };

            let k_cache = cache.k_cache[layer_idx].as_ptr();
            let v_cache = cache.v_cache[layer_idx].as_ptr();
            let (mut k, mut v) = match cache.storage() {
                TalkerKvStorage::F16 => {
                    let k_cache_view = unsafe {
                        sys::ggml_view_3d(
                            ctx.as_ptr(),
                            k_cache,
                            self.config.head_dim as i64,
                            self.config.n_key_value_heads as i64,
                            1,
                            (*k_cache).nb[1],
                            (*k_cache).nb[2],
                            n_past * (*k_cache).nb[2],
                        )
                    };
                    let v_cache_view = unsafe {
                        sys::ggml_view_3d(
                            ctx.as_ptr(),
                            v_cache,
                            self.config.head_dim as i64,
                            self.config.n_key_value_heads as i64,
                            1,
                            (*v_cache).nb[1],
                            (*v_cache).nb[2],
                            n_past * (*v_cache).nb[2],
                        )
                    };
                    unsafe {
                        sys::ggml_build_forward_expand(
                            graph.as_ptr(),
                            sys::ggml_cpy(ctx.as_ptr(), k_cur, k_cache_view),
                        );
                        sys::ggml_build_forward_expand(
                            graph.as_ptr(),
                            sys::ggml_cpy(ctx.as_ptr(), v_cur, v_cache_view),
                        );
                    }

                    let n_kv = n_past + 1;
                    let k = unsafe {
                        sys::ggml_view_3d(
                            ctx.as_ptr(),
                            k_cache,
                            self.config.head_dim as i64,
                            self.config.n_key_value_heads as i64,
                            n_kv as i64,
                            (*k_cache).nb[1],
                            (*k_cache).nb[2],
                            0,
                        )
                    };
                    let v = unsafe {
                        sys::ggml_view_3d(
                            ctx.as_ptr(),
                            v_cache,
                            self.config.head_dim as i64,
                            self.config.n_key_value_heads as i64,
                            n_kv as i64,
                            (*v_cache).nb[1],
                            (*v_cache).nb[2],
                            0,
                        )
                    };
                    (k, v)
                }
                TalkerKvStorage::TurboQuantQ8_0 => {
                    let k_store = unsafe { sys::ggml_cont(ctx.as_ptr(), k_cur) };
                    let v_store = unsafe { sys::ggml_cont(ctx.as_ptr(), v_cur) };
                    unsafe {
                        sys::ggml_build_forward_expand(graph.as_ptr(), k_store);
                        sys::ggml_build_forward_expand(graph.as_ptr(), v_store);
                    }
                    let rows =
                        self.config.n_key_value_heads as usize * self.config.head_dim as usize;
                    kv_writeback.push(KvWritebackTensorDownloads {
                        layer_idx,
                        token_start: n_past,
                        n_tokens: 1,
                        k_tensor: k_store,
                        v_tensor: v_store,
                        k_data: vec![0.0; rows],
                        v_data: vec![0.0; rows],
                    });
                    if n_past == 0 {
                        (k_cur, v_cur)
                    } else {
                        let k_prefix_q = unsafe {
                            sys::ggml_view_3d(
                                ctx.as_ptr(),
                                k_cache,
                                self.config.head_dim as i64,
                                self.config.n_key_value_heads as i64,
                                n_past as i64,
                                (*k_cache).nb[1],
                                (*k_cache).nb[2],
                                0,
                            )
                        };
                        let v_prefix_q = unsafe {
                            sys::ggml_view_3d(
                                ctx.as_ptr(),
                                v_cache,
                                self.config.head_dim as i64,
                                self.config.n_key_value_heads as i64,
                                n_past as i64,
                                (*v_cache).nb[1],
                                (*v_cache).nb[2],
                                0,
                            )
                        };
                        let k_prefix = unsafe {
                            sys::ggml_cast(ctx.as_ptr(), k_prefix_q, sys::ggml_type_GGML_TYPE_F32)
                        };
                        let v_prefix = unsafe {
                            sys::ggml_cast(ctx.as_ptr(), v_prefix_q, sys::ggml_type_GGML_TYPE_F32)
                        };
                        let k = unsafe { sys::ggml_concat(ctx.as_ptr(), k_prefix, k_cur, 2) };
                        let v = unsafe { sys::ggml_concat(ctx.as_ptr(), v_prefix, v_cur, 2) };
                        (k, v)
                    }
                }
            };

            let q = unsafe { sys::ggml_permute(ctx.as_ptr(), q_cur, 0, 2, 1, 3) };
            k = unsafe { sys::ggml_permute(ctx.as_ptr(), k, 0, 2, 1, 3) };
            v = unsafe { sys::ggml_permute(ctx.as_ptr(), v, 0, 2, 1, 3) };

            let mut kq = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), k, q) };
            kq = unsafe { sys::ggml_scale(ctx.as_ptr(), kq, kq_scale) };
            kq = unsafe {
                ggml_soft_max_ext_with_diag_mask_cache(
                    ctx.as_ptr(),
                    kq,
                    n_past as i32,
                    &mut attn_softmax_mask,
                )
            };

            v = unsafe { sys::ggml_cont(ctx.as_ptr(), sys::ggml_transpose(ctx.as_ptr(), v)) };
            let mut kqv = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), v, kq) };
            kqv = unsafe { sys::ggml_permute(ctx.as_ptr(), kqv, 0, 2, 1, 3) };
            cur = unsafe {
                sys::ggml_cont_2d(
                    ctx.as_ptr(),
                    kqv,
                    (self.config.n_attention_heads * self.config.head_dim) as i64,
                    1,
                )
            };

            cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.attn_output.as_ptr(), cur) };
            cur = unsafe { sys::ggml_add(ctx.as_ptr(), cur, inp_l) };
            let inp_ff = cur;

            cur = unsafe { sys::ggml_rms_norm(ctx.as_ptr(), inp_ff, self.config.rms_norm_eps) };
            cur = unsafe { sys::ggml_mul(ctx.as_ptr(), cur, layer.ffn_norm.as_ptr()) };
            let mut gate = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.ffn_gate.as_ptr(), cur) };
            let up = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), layer.ffn_up.as_ptr(), cur) };
            gate = unsafe { sys::ggml_silu(ctx.as_ptr(), gate) };
            cur = unsafe { sys::ggml_mul(ctx.as_ptr(), gate, up) };

            let ffn_down_f32 = layer
                .ffn_down_f32
                .map(NonNull::as_ptr)
                .unwrap_or_else(|| unsafe {
                    sys::ggml_cast(
                        ctx.as_ptr(),
                        layer.ffn_down.as_ptr(),
                        sys::ggml_type_GGML_TYPE_F32,
                    )
                });
            cur = unsafe { sys::ggml_mul_mat(ctx.as_ptr(), ffn_down_f32, cur) };
            inp_l = unsafe { sys::ggml_add(ctx.as_ptr(), cur, inp_ff) };
        }

        let mut hidden_state =
            unsafe { sys::ggml_rms_norm(ctx.as_ptr(), inp_l, self.config.rms_norm_eps) };
        hidden_state =
            unsafe { sys::ggml_mul(ctx.as_ptr(), hidden_state, self.talker.output_norm.as_ptr()) };
        hidden_state = unsafe { sys::ggml_cont(ctx.as_ptr(), hidden_state) };
        self.retain_projected_predictor_hidden(hidden_state);
        let mut logits = unsafe {
            sys::ggml_mul_mat(ctx.as_ptr(), self.talker.codec_head.as_ptr(), hidden_state)
        };
        logits = unsafe { sys::ggml_cont(ctx.as_ptr(), logits) };
        unsafe {
            sys::ggml_build_forward_expand(graph.as_ptr(), hidden_state);
            sys::ggml_build_forward_expand(graph.as_ptr(), logits);
        }

        let mut hidden = vec![0.0f32; hidden_size];
        let mut logits_data = vec![0.0f32; self.config.codec_vocab_size as usize];
        let mut uploads = vec![
            TensorUpload {
                tensor: inp_step.as_ptr(),
                bytes: slice_as_bytes(step_embd),
            },
            TensorUpload {
                tensor: inp_pos.as_ptr(),
                bytes: slice_as_bytes(std::slice::from_ref(&pos)),
            },
        ];
        if let Some((t, data)) = &attn_softmax_mask {
            uploads.push(TensorUpload {
                tensor: *t,
                bytes: slice_as_bytes(data.as_slice()),
            });
        }
        let mut downloads = vec![
            TensorDownload {
                tensor: hidden_state,
                bytes: slice_as_bytes_mut(hidden.as_mut_slice()),
            },
            TensorDownload {
                tensor: logits,
                bytes: slice_as_bytes_mut(logits_data.as_mut_slice()),
            },
        ];
        execute_graph(
            &cache._backends,
            graph,
            uploads.as_slice(),
            downloads.as_mut_slice(),
            thread_count,
            "step graph execution failed",
        )?;
        let (kv_writeback_elapsed, kv_download_elapsed, kv_quantize_elapsed, kv_upload_elapsed) =
            if cache.storage().is_quantized() {
                let t_writeback = Instant::now();
                let t_download = Instant::now();
                for pending in &mut kv_writeback {
                    unsafe {
                        sys::ggml_backend_tensor_get(
                            pending.k_tensor,
                            pending.k_data.as_mut_ptr().cast(),
                            0,
                            std::mem::size_of_val(pending.k_data.as_slice()),
                        );
                        sys::ggml_backend_tensor_get(
                            pending.v_tensor,
                            pending.v_data.as_mut_ptr().cast(),
                            0,
                            std::mem::size_of_val(pending.v_data.as_slice()),
                        );
                    }
                }
                let download_elapsed = t_download.elapsed();
                let mut quantize_elapsed = Duration::ZERO;
                let mut upload_elapsed = Duration::ZERO;
                let base_layout = QuantizedKvWriteLayout {
                    token_start: 0,
                    n_tokens: 0,
                    rows_per_token: self.config.n_key_value_heads as usize,
                    row_len: self.config.head_dim as usize,
                };
                for pending in kv_writeback {
                    let (quantize, upload) = cache.quantized_write_layer(
                        pending.layer_idx,
                        QuantizedKvWriteLayout {
                            token_start: pending.token_start,
                            n_tokens: pending.n_tokens,
                            ..base_layout
                        },
                        pending.k_data.as_slice(),
                        pending.v_data.as_slice(),
                    )?;
                    quantize_elapsed += quantize;
                    upload_elapsed += upload;
                }
                let total = t_writeback.elapsed();
                (total, download_elapsed, quantize_elapsed, upload_elapsed)
            } else {
                (
                    Duration::ZERO,
                    Duration::ZERO,
                    Duration::ZERO,
                    Duration::ZERO,
                )
            };
        Ok(StepForwardOutputs {
            hidden_state: hidden,
            logits: logits_data,
            kv_writeback_elapsed,
            kv_download_elapsed,
            kv_quantize_elapsed,
            kv_upload_elapsed,
        })
    }
}

/// Pre-built, pre-allocated step graph whose tensor shapes are independent of `n_past`.
///
/// Attention reads `K_cache[0..n_kv_max-1]` (the cache slots filled so far **plus** garbage
// Predictor metadata is independent; tensor widths also support older exports.
fn predictor_config(
    file: &GgufFile,
    talker: &TtsTransformerConfig,
) -> Result<CodePredictorConfig, Qwen3TtsError> {
    let mut cfg = CodePredictorConfig {
        hidden_size: talker.hidden_size,
        n_layers: talker.code_pred_layers,
        n_attention_heads: talker.n_attention_heads,
        n_key_value_heads: talker.n_key_value_heads,
        intermediate_size: talker.intermediate_size,
        head_dim: talker.head_dim,
        rms_norm_eps: talker.rms_norm_eps,
        rope_theta: talker.rope_theta,
        vocab_size: talker.code_pred_vocab_size,
    };
    let tensor_width = file
        .tensor_info("code_pred.output_norm.weight")
        .ok()
        .and_then(|info| info.dims.first().copied())
        .unwrap_or(talker.hidden_size as usize) as i32;
    let integer = |suffix: &str, default| {
        get_u32_any(
            file,
            &[
                &format!("qwen3-tts.code_pred.{suffix}"),
                &format!("qwen3-tts.code_predictor.{suffix}"),
            ],
            default,
        )
    };
    cfg.hidden_size = integer("embedding_length", integer("hidden_size", tensor_width));
    // The legacy 0.6B Base graph used talker geometry for the predictor.
    // Keep that exact configuration when no width projection is present;
    // independently inferred head layouts or norm/RoPE values change its graph.
    if talker.hidden_size == 1024
        && cfg.hidden_size == talker.hidden_size
        && tensor_width == talker.hidden_size
        && projection_source(file, file, talker.hidden_size, cfg.hidden_size)?.is_none()
    {
        return Ok(cfg);
    }
    cfg.head_dim = integer("attention.key_length", talker.head_dim);
    if cfg.hidden_size <= 0 || cfg.head_dim <= 0 {
        return Err(Qwen3TtsError::InvalidInput(
            "predictor dimensions must be positive".into(),
        ));
    }
    let tensor_heads = |name: &str, default| {
        file.tensor_info(name)
            .ok()
            .and_then(|info| info.dims.get(1).copied())
            .map_or(default, |width| width as i32 / cfg.head_dim)
    };
    cfg.n_attention_heads = integer(
        "attention.head_count",
        tensor_heads("code_pred.blk.0.attn_q.weight", talker.n_attention_heads),
    );
    cfg.n_key_value_heads = integer(
        "attention.head_count_kv",
        tensor_heads("code_pred.blk.0.attn_k.weight", talker.n_key_value_heads),
    );
    cfg.intermediate_size = integer(
        "feed_forward_length",
        file.tensor_info("code_pred.blk.0.ffn_gate.weight")
            .ok()
            .and_then(|info| info.dims.get(1).copied())
            .unwrap_or(talker.intermediate_size as usize) as i32,
    );
    cfg.n_layers = integer(
        "layer_count",
        integer("block_count", talker.code_pred_layers),
    );
    cfg.vocab_size = integer("vocab_size", talker.code_pred_vocab_size);
    cfg.rms_norm_eps = get_f32_any(
        file,
        &[
            "qwen3-tts.code_pred.attention.layer_norm_rms_epsilon",
            "qwen3-tts.code_predictor.attention.layer_norm_rms_epsilon",
        ],
        talker.rms_norm_eps,
    );
    cfg.rope_theta = get_f32_any(
        file,
        &[
            "qwen3-tts.code_pred.rope.freq_base",
            "qwen3-tts.code_predictor.rope.freq_base",
        ],
        talker.rope_theta,
    );
    if cfg.n_attention_heads <= 0
        || cfg.n_key_value_heads <= 0
        || cfg.n_attention_heads % cfg.n_key_value_heads != 0
        || cfg.intermediate_size <= 0
        || cfg.n_layers < 0
        || cfg.vocab_size <= 0
    {
        return Err(Qwen3TtsError::InvalidInput(
            "invalid predictor configuration".into(),
        ));
    }
    Ok(cfg)
}

fn validate_projection_shapes(
    input: i32,
    output: i32,
    weight: Option<&[usize]>,
    bias: Option<&[usize]>,
) -> Result<(), Qwen3TtsError> {
    match (weight, bias) {
        (None, None) if input == output => Ok(()),
        (Some(weight), Some(bias)) if weight == [input as usize, output as usize] && bias == [output as usize] => Ok(()),
        _ => Err(Qwen3TtsError::InvalidInput(format!("small_to_mtp_projection requires weight [{input}, {output}] & bias [{output}] when widths differ"))),
    }
}

fn projection_source<'a>(
    predictor: &'a GgufFile,
    talker: &'a GgufFile,
    input: i32,
    output: i32,
) -> Result<Option<(&'a GgufFile, String, String)>, Qwen3TtsError> {
    for file in [predictor, talker] {
        for prefix in [
            "code_pred.small_to_mtp_projection",
            "talker.code_predictor.small_to_mtp_projection",
            "small_to_mtp_projection",
        ] {
            let weight = format!("{prefix}.weight");
            let bias = format!("{prefix}.bias");
            let w = file.tensor_info(&weight).ok();
            let b = file.tensor_info(&bias).ok();
            if w.is_some() || b.is_some() {
                validate_projection_shapes(
                    input,
                    output,
                    w.as_ref().map(|i| i.dims.as_slice()),
                    b.as_ref().map(|i| i.dims.as_slice()),
                )?;
                return Ok(Some((file, weight, bias)));
            }
        }
    }
    validate_projection_shapes(input, output, None, None)?;
    Ok(None)
}

fn load_speaker_table(
    file: &GgufFile,
    vocab_size: i32,
) -> Result<std::collections::HashMap<String, i32>, Qwen3TtsError> {
    let mut table = std::collections::HashMap::new();
    for speaker in PresetSpeaker::ALL {
        let key = format!("qwen3-tts.talker.spk_id.{}", speaker.as_str());
        if file.key_index(&key).is_some() {
            let id = file.get_u32(&key, 0) as i32;
            if id < 0 || id >= vocab_size {
                return Err(Qwen3TtsError::InvalidInput(format!(
                    "speaker id out of codec vocabulary: {key}"
                )));
            }
            table.insert(speaker.as_str().to_owned(), id);
        }
    }
    Ok(table)
}

fn load_speaker_languages(
    file: &GgufFile,
) -> Result<std::collections::HashMap<String, i32>, Qwen3TtsError> {
    let mut languages = std::collections::HashMap::new();
    for speaker in PresetSpeaker::ALL {
        if let Some(dialect) = file.get_str(&format!(
            "qwen3-tts.talker.spk_is_dialect.{}",
            speaker.as_str()
        )) {
            let key = format!("qwen3-tts.talker.codec_language_id.{dialect}");
            if file.key_index(&key).is_none() {
                return Err(Qwen3TtsError::InvalidInput(format!(
                    "missing dialect language id: {key}"
                )));
            }
            languages.insert(speaker.as_str().to_owned(), file.get_u32(&key, 0) as i32);
        }
    }
    Ok(languages)
}

fn get_u32_any(file: &GgufFile, keys: &[&str], default: i32) -> i32 {
    for key in keys {
        if file.key_index(key).is_some() {
            return file.get_u32(key, default as u32) as i32;
        }
    }
    default
}

fn get_f32_any(file: &GgufFile, keys: &[&str], default: f32) -> f32 {
    for key in keys {
        if file.key_index(key).is_some() {
            return file.get_f32(key, default);
        }
    }
    default
}

struct TalkerWeights {
    _ctx: OwnedContext,
    _backends: BackendSet,
    _buffer: OwnedBuffer,
    text_embd: NonNull<sys::ggml_tensor>,
    text_proj_fc1: NonNull<sys::ggml_tensor>,
    text_proj_fc1_bias: NonNull<sys::ggml_tensor>,
    text_proj_fc2: NonNull<sys::ggml_tensor>,
    text_proj_fc2_bias: NonNull<sys::ggml_tensor>,
    codec_embd: NonNull<sys::ggml_tensor>,
    /// Row-major `[codec_vocab_size * hidden_size]` when GGUF stores `codec_embd` as F16/F32.
    codec_embd_cpu: Option<Vec<f32>>,
    output_norm: NonNull<sys::ggml_tensor>,
    codec_head: NonNull<sys::ggml_tensor>,
    layers: Vec<TalkerLayerWeights>,
}

impl TalkerWeights {
    fn load(
        file: &GgufFile,
        cfg: &TtsTransformerConfig,
        backends: BackendSet,
    ) -> Result<Self, Qwen3TtsError> {
        unsafe {
            sys::ggml_cpu_init();
        }
        let tensor_count = 8 + cfg.n_layers as usize * 12;
        let ctx = OwnedContext::new_for_tensor_metadata(tensor_count)?;

        let text_embd = load_tensor_into_context(file, ctx.as_ptr(), "talker.text_embd.weight")?;
        let text_proj_fc1 =
            load_tensor_into_context(file, ctx.as_ptr(), "talker.text_proj.fc1.weight")?;
        let text_proj_fc1_bias =
            load_tensor_into_context(file, ctx.as_ptr(), "talker.text_proj.fc1.bias")?;
        let text_proj_fc2 =
            load_tensor_into_context(file, ctx.as_ptr(), "talker.text_proj.fc2.weight")?;
        let text_proj_fc2_bias =
            load_tensor_into_context(file, ctx.as_ptr(), "talker.text_proj.fc2.bias")?;
        let codec_embd = load_tensor_into_context(file, ctx.as_ptr(), "talker.codec_embd.weight")?;
        let hidden_u = cfg.hidden_size as usize;
        let codec_vocab_u = cfg.codec_vocab_size as usize;
        let codec_embd_cpu = try_read_embedding_matrix_f32(
            file,
            "talker.codec_embd.weight",
            codec_embd,
            hidden_u,
            codec_vocab_u,
        );
        let output_norm =
            load_tensor_into_context(file, ctx.as_ptr(), "talker.output_norm.weight")?;
        let codec_head = load_tensor_into_context(file, ctx.as_ptr(), "talker.codec_head.weight")?;
        let mut layers = Vec::with_capacity(cfg.n_layers as usize);
        for layer_idx in 0..cfg.n_layers {
            let prefix = format!("talker.blk.{layer_idx}.");
            let ffn_down_name = prefix.clone() + "ffn_down.weight";
            layers.push(TalkerLayerWeights {
                attn_norm: load_tensor_into_context(
                    file,
                    ctx.as_ptr(),
                    &(prefix.clone() + "attn_norm.weight"),
                )?,
                attn_q_norm: load_optional_tensor_into_context(
                    file,
                    ctx.as_ptr(),
                    &(prefix.clone() + "attn_q_norm.weight"),
                )?,
                attn_k_norm: load_optional_tensor_into_context(
                    file,
                    ctx.as_ptr(),
                    &(prefix.clone() + "attn_k_norm.weight"),
                )?,
                attn_q: load_tensor_into_context(
                    file,
                    ctx.as_ptr(),
                    &(prefix.clone() + "attn_q.weight"),
                )?,
                attn_k: load_tensor_into_context(
                    file,
                    ctx.as_ptr(),
                    &(prefix.clone() + "attn_k.weight"),
                )?,
                attn_v: load_tensor_into_context(
                    file,
                    ctx.as_ptr(),
                    &(prefix.clone() + "attn_v.weight"),
                )?,
                attn_output: load_tensor_into_context(
                    file,
                    ctx.as_ptr(),
                    &(prefix.clone() + "attn_output.weight"),
                )?,
                ffn_norm: load_tensor_into_context(
                    file,
                    ctx.as_ptr(),
                    &(prefix.clone() + "ffn_norm.weight"),
                )?,
                ffn_gate: load_tensor_into_context(
                    file,
                    ctx.as_ptr(),
                    &(prefix.clone() + "ffn_gate.weight"),
                )?,
                ffn_up: load_tensor_into_context(
                    file,
                    ctx.as_ptr(),
                    &(prefix.clone() + "ffn_up.weight"),
                )?,
                ffn_down: load_tensor_into_context(file, ctx.as_ptr(), &ffn_down_name)?,
                ffn_down_f32: load_tensor_f32_into_context(file, ctx.as_ptr(), &ffn_down_name)?,
            });
        }

        let buffer = OwnedBuffer::alloc(ctx.as_ptr(), backends.primary_ptr())?;
        for (name, tensor) in [
            ("talker.text_embd.weight", text_embd),
            ("talker.text_proj.fc1.weight", text_proj_fc1),
            ("talker.text_proj.fc1.bias", text_proj_fc1_bias),
            ("talker.text_proj.fc2.weight", text_proj_fc2),
            ("talker.text_proj.fc2.bias", text_proj_fc2_bias),
            ("talker.codec_embd.weight", codec_embd),
            ("talker.output_norm.weight", output_norm),
            ("talker.codec_head.weight", codec_head),
        ] {
            let (_, raw) = file.read_tensor_bytes(name)?;
            unsafe {
                sys::ggml_backend_tensor_set(tensor.as_ptr(), raw.as_ptr().cast(), 0, raw.len());
            }
        }
        for (layer_idx, layer) in layers.iter().enumerate() {
            for (suffix, tensor) in [
                ("attn_norm.weight", Some(layer.attn_norm)),
                ("attn_q_norm.weight", layer.attn_q_norm),
                ("attn_k_norm.weight", layer.attn_k_norm),
                ("attn_q.weight", Some(layer.attn_q)),
                ("attn_k.weight", Some(layer.attn_k)),
                ("attn_v.weight", Some(layer.attn_v)),
                ("attn_output.weight", Some(layer.attn_output)),
                ("ffn_norm.weight", Some(layer.ffn_norm)),
                ("ffn_gate.weight", Some(layer.ffn_gate)),
                ("ffn_up.weight", Some(layer.ffn_up)),
                ("ffn_down.weight", Some(layer.ffn_down)),
            ] {
                if let Some(tensor) = tensor {
                    let name = format!("talker.blk.{layer_idx}.{suffix}");
                    let (_, raw) = file.read_tensor_bytes(&name)?;
                    unsafe {
                        sys::ggml_backend_tensor_set(
                            tensor.as_ptr(),
                            raw.as_ptr().cast(),
                            0,
                            raw.len(),
                        );
                    }
                }
            }
            if let Some(tensor) = layer.ffn_down_f32 {
                let name = format!("talker.blk.{layer_idx}.ffn_down.weight");
                let (_, raw) = file.read_tensor_f32(&name)?;
                unsafe {
                    sys::ggml_backend_tensor_set(
                        tensor.as_ptr(),
                        raw.as_ptr().cast(),
                        0,
                        std::mem::size_of_val(raw.as_slice()),
                    );
                }
            }
        }

        Ok(Self {
            _ctx: ctx,
            _backends: backends,
            _buffer: buffer,
            text_embd,
            text_proj_fc1,
            text_proj_fc1_bias,
            text_proj_fc2,
            text_proj_fc2_bias,
            codec_embd,
            codec_embd_cpu,
            output_norm,
            codec_head,
            layers,
        })
    }
}

struct TalkerLayerWeights {
    attn_norm: NonNull<sys::ggml_tensor>,
    attn_q_norm: Option<NonNull<sys::ggml_tensor>>,
    attn_k_norm: Option<NonNull<sys::ggml_tensor>>,
    attn_q: NonNull<sys::ggml_tensor>,
    attn_k: NonNull<sys::ggml_tensor>,
    attn_v: NonNull<sys::ggml_tensor>,
    attn_output: NonNull<sys::ggml_tensor>,
    ffn_norm: NonNull<sys::ggml_tensor>,
    ffn_gate: NonNull<sys::ggml_tensor>,
    ffn_up: NonNull<sys::ggml_tensor>,
    ffn_down: NonNull<sys::ggml_tensor>,
    ffn_down_f32: Option<NonNull<sys::ggml_tensor>>,
}

struct CodePredWeights {
    _ctx: OwnedContext,
    _backends: BackendSet,
    _buffer: OwnedBuffer,
    embeddings: Vec<NonNull<sys::ggml_tensor>>,
    projection: Option<(NonNull<sys::ggml_tensor>, NonNull<sys::ggml_tensor>)>,
    /// Per codebook row-major `[code_pred_vocab_size * hidden_size]`, only when all tables are F16/F32 in GGUF.
    codec_embd_cpu: Option<Vec<Vec<f32>>>,
    output_norm: NonNull<sys::ggml_tensor>,
    heads: Vec<NonNull<sys::ggml_tensor>>,
    layers: Vec<TalkerLayerWeights>,
}

struct TalkerKvCache {
    _ctx: OwnedContext,
    _backends: BackendSet,
    _buffer: OwnedBuffer,
    k_cache: Vec<NonNull<sys::ggml_tensor>>,
    v_cache: Vec<NonNull<sys::ggml_tensor>>,
    storage: TalkerKvStorage,
    n_ctx: usize,
}

#[derive(Debug, Clone, Copy)]
struct QuantizedKvWriteLayout {
    token_start: usize,
    n_tokens: usize,
    rows_per_token: usize,
    row_len: usize,
}

struct CodePredKvCache {
    _ctx: OwnedContext,
    _backends: BackendSet,
    _buffer: OwnedBuffer,
    k_cache: Vec<NonNull<sys::ggml_tensor>>,
    v_cache: Vec<NonNull<sys::ggml_tensor>>,
    n_ctx: usize,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TalkerKvStorage {
    F16,
    TurboQuantQ8_0,
}

impl TalkerKvStorage {
    fn from_mode(mode: TalkerKvMode) -> Self {
        match mode {
            TalkerKvMode::F16 => Self::F16,
            TalkerKvMode::TurboQuant => Self::TurboQuantQ8_0,
        }
    }

    fn tensor_type(self) -> sys::ggml_type {
        match self {
            Self::F16 => sys::ggml_type_GGML_TYPE_F16,
            Self::TurboQuantQ8_0 => sys::ggml_type_GGML_TYPE_Q8_0,
        }
    }

    fn is_quantized(self) -> bool {
        matches!(self, Self::TurboQuantQ8_0)
    }
}

impl TalkerKvCache {
    fn new(
        cfg: &TtsTransformerConfig,
        n_ctx: usize,
        backends: BackendSet,
        mode: TalkerKvMode,
    ) -> Result<Self, Qwen3TtsError> {
        unsafe {
            sys::ggml_cpu_init();
        }
        let storage = TalkerKvStorage::from_mode(mode);
        let ctx = OwnedContext::new_for_tensor_metadata(cfg.n_layers as usize * 2)?;
        let mut k_cache = Vec::with_capacity(cfg.n_layers as usize);
        let mut v_cache = Vec::with_capacity(cfg.n_layers as usize);
        for _ in 0..cfg.n_layers {
            let k = unsafe {
                sys::ggml_new_tensor_3d(
                    ctx.as_ptr(),
                    storage.tensor_type(),
                    cfg.head_dim as i64,
                    cfg.n_key_value_heads as i64,
                    n_ctx as i64,
                )
            };
            let v = unsafe {
                sys::ggml_new_tensor_3d(
                    ctx.as_ptr(),
                    storage.tensor_type(),
                    cfg.head_dim as i64,
                    cfg.n_key_value_heads as i64,
                    n_ctx as i64,
                )
            };
            k_cache.push(
                NonNull::new(k).ok_or_else(|| {
                    Qwen3TtsError::InvalidInput("failed to allocate K cache".into())
                })?,
            );
            v_cache.push(
                NonNull::new(v).ok_or_else(|| {
                    Qwen3TtsError::InvalidInput("failed to allocate V cache".into())
                })?,
            );
        }
        let buffer = OwnedBuffer::alloc(ctx.as_ptr(), backends.primary_ptr())?;
        unsafe {
            let nbytes = sys::ggml_nbytes(k_cache[0].as_ptr());
            let zeros = vec![0u8; nbytes];
            for k in &k_cache {
                sys::ggml_backend_tensor_set(k.as_ptr(), zeros.as_ptr().cast(), 0, nbytes);
            }
            for v in &v_cache {
                sys::ggml_backend_tensor_set(v.as_ptr(), zeros.as_ptr().cast(), 0, nbytes);
            }
        }
        Ok(Self {
            _ctx: ctx,
            _backends: backends,
            _buffer: buffer,
            k_cache,
            v_cache,
            storage,
            n_ctx,
        })
    }

    fn storage(&self) -> TalkerKvStorage {
        self.storage
    }

    fn total_bytes(&self) -> usize {
        let per_tensor = self
            .k_cache
            .first()
            .map(|tensor| unsafe { sys::ggml_nbytes(tensor.as_ptr()) })
            .unwrap_or(0);
        per_tensor.saturating_mul(self.k_cache.len() + self.v_cache.len())
    }

    fn quantized_write_layer(
        &self,
        layer_idx: usize,
        layout: QuantizedKvWriteLayout,
        k_src: &[f32],
        v_src: &[f32],
    ) -> Result<(Duration, Duration), Qwen3TtsError> {
        debug_assert!(self.storage.is_quantized());
        let k = self.k_cache.get(layer_idx).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("talker K cache layer out of range".into())
        })?;
        let v = self.v_cache.get(layer_idx).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("talker V cache layer out of range".into())
        })?;
        let (k_quantize, k_upload) =
            quantized_tensor_write_rows(k.as_ptr(), self.storage.tensor_type(), layout, k_src)?;
        let (v_quantize, v_upload) =
            quantized_tensor_write_rows(v.as_ptr(), self.storage.tensor_type(), layout, v_src)?;
        Ok((k_quantize + v_quantize, k_upload + v_upload))
    }
}

fn quantized_tensor_write_rows(
    tensor: *mut sys::ggml_tensor,
    quant_type: sys::ggml_type,
    layout: QuantizedKvWriteLayout,
    src: &[f32],
) -> Result<(Duration, Duration), Qwen3TtsError> {
    let QuantizedKvWriteLayout {
        token_start,
        n_tokens,
        rows_per_token,
        row_len,
    } = layout;
    if src.len()
        != n_tokens
            .saturating_mul(rows_per_token)
            .saturating_mul(row_len)
    {
        return Err(Qwen3TtsError::InvalidInput(
            "quantized KV source rows had an unexpected size".into(),
        ));
    }
    let block_size = unsafe { sys::ggml_blck_size(quant_type) as usize };
    if block_size == 0 || !row_len.is_multiple_of(block_size) {
        return Err(Qwen3TtsError::InvalidInput(format!(
            "quantized KV row length {row_len} is incompatible with block size {block_size}"
        )));
    }
    let type_size = unsafe { sys::ggml_type_size(quant_type) };
    let bytes_per_row = row_len / block_size * type_size;
    let total_bytes = n_tokens
        .saturating_mul(rows_per_token)
        .saturating_mul(bytes_per_row);
    let mut quantized = vec![0u8; total_bytes];
    let t_quantize = Instant::now();
    let written = unsafe {
        sys::ggml_quantize_chunk(
            quant_type,
            src.as_ptr(),
            quantized.as_mut_ptr().cast(),
            0,
            (n_tokens * rows_per_token) as i64,
            row_len as i64,
            std::ptr::null(),
        )
    };
    let quantize_elapsed = t_quantize.elapsed();
    if written != quantized.len() {
        return Err(Qwen3TtsError::InvalidInput(format!(
            "quantized KV write produced {written} bytes, expected {}",
            quantized.len()
        )));
    }
    let offset = unsafe { token_start * (*tensor).nb[2] };
    let t_upload = Instant::now();
    unsafe {
        sys::ggml_backend_tensor_set(tensor, quantized.as_ptr().cast(), offset, quantized.len());
    }
    Ok((quantize_elapsed, t_upload.elapsed()))
}

impl CodePredKvCache {
    fn new(
        cfg: &CodePredictorConfig,
        n_ctx: usize,
        backends: BackendSet,
    ) -> Result<Self, Qwen3TtsError> {
        unsafe {
            sys::ggml_cpu_init();
        }
        let ctx = OwnedContext::new_for_tensor_metadata(cfg.n_layers as usize * 2)?;
        let mut k_cache = Vec::with_capacity(cfg.n_layers as usize);
        let mut v_cache = Vec::with_capacity(cfg.n_layers as usize);
        for _ in 0..cfg.n_layers {
            let k = unsafe {
                sys::ggml_new_tensor_3d(
                    ctx.as_ptr(),
                    sys::ggml_type_GGML_TYPE_F16,
                    cfg.head_dim as i64,
                    cfg.n_key_value_heads as i64,
                    n_ctx as i64,
                )
            };
            let v = unsafe {
                sys::ggml_new_tensor_3d(
                    ctx.as_ptr(),
                    sys::ggml_type_GGML_TYPE_F16,
                    cfg.head_dim as i64,
                    cfg.n_key_value_heads as i64,
                    n_ctx as i64,
                )
            };
            k_cache.push(NonNull::new(k).ok_or_else(|| {
                Qwen3TtsError::InvalidInput("failed to allocate code predictor K cache".into())
            })?);
            v_cache.push(NonNull::new(v).ok_or_else(|| {
                Qwen3TtsError::InvalidInput("failed to allocate code predictor V cache".into())
            })?);
        }
        let buffer = OwnedBuffer::alloc(ctx.as_ptr(), backends.primary_ptr())?;
        Ok(Self {
            _ctx: ctx,
            _backends: backends,
            _buffer: buffer,
            k_cache,
            v_cache,
            n_ctx,
        })
    }
}

impl CodePredWeights {
    fn project_input(
        &self,
        ctx: *mut sys::ggml_context,
        input: *mut sys::ggml_tensor,
    ) -> *mut sys::ggml_tensor {
        match self.projection {
            Some((weight, bias)) => unsafe {
                let projected = sys::ggml_mul_mat(ctx, weight.as_ptr(), input);
                sys::ggml_add(ctx, projected, bias.as_ptr())
            },
            None => input,
        }
    }

    fn load(
        file: &GgufFile,
        talker_file: &GgufFile,
        talker_cfg: &TtsTransformerConfig,
        cfg: &CodePredictorConfig,
        backends: BackendSet,
    ) -> Result<Self, Qwen3TtsError> {
        let check = |name: &str, expected: &[usize]| -> Result<(), Qwen3TtsError> {
            if file.tensor_info(name)?.dims != expected {
                return Err(Qwen3TtsError::InvalidTensor(name.into()));
            }
            Ok(())
        };
        check("code_pred.output_norm.weight", &[cfg.hidden_size as usize])?;
        for layer in 0..cfg.n_layers {
            let prefix = format!("code_pred.blk.{layer}");
            let hidden = cfg.hidden_size as usize;
            let query = (cfg.n_attention_heads * cfg.head_dim) as usize;
            let kv = (cfg.n_key_value_heads * cfg.head_dim) as usize;
            let intermediate = cfg.intermediate_size as usize;
            for (suffix, shape) in [
                ("attn_norm.weight", vec![hidden]),
                ("ffn_norm.weight", vec![hidden]),
                ("attn_q.weight", vec![hidden, query]),
                ("attn_k.weight", vec![hidden, kv]),
                ("attn_v.weight", vec![hidden, kv]),
                ("attn_output.weight", vec![query, hidden]),
                ("ffn_gate.weight", vec![hidden, intermediate]),
                ("ffn_up.weight", vec![hidden, intermediate]),
                ("ffn_down.weight", vec![intermediate, hidden]),
            ] {
                check(&format!("{prefix}.{suffix}"), &shape)?;
            }
        }
        for cb_idx in 0..talker_cfg.n_codebooks - 1 {
            check(
                &format!("code_pred.codec_embd.{cb_idx}.weight"),
                &[talker_cfg.hidden_size as usize, cfg.vocab_size as usize],
            )?;
            check(
                &format!("code_pred.lm_head.{cb_idx}.weight"),
                &[cfg.hidden_size as usize, cfg.vocab_size as usize],
            )?;
        }
        unsafe {
            sys::ggml_cpu_init();
        }
        let per_codebook = (talker_cfg.n_codebooks - 1) as usize;
        let projection_source =
            projection_source(file, talker_file, talker_cfg.hidden_size, cfg.hidden_size)?;
        let tensor_count = 1
            + usize::from(projection_source.is_some()) * 2
            + per_codebook * 2
            + cfg.n_layers as usize * 12;
        let ctx = OwnedContext::new_for_tensor_metadata(tensor_count)?;

        let projection = if let Some((source, weight, bias)) = &projection_source {
            Some((
                load_tensor_into_context(source, ctx.as_ptr(), weight)?,
                load_tensor_into_context(source, ctx.as_ptr(), bias)?,
            ))
        } else {
            None
        };
        let mut embeddings = Vec::with_capacity(per_codebook);
        let mut heads = Vec::with_capacity(per_codebook);
        for cb_idx in 0..per_codebook {
            embeddings.push(load_tensor_into_context(
                file,
                ctx.as_ptr(),
                &format!("code_pred.codec_embd.{cb_idx}.weight"),
            )?);
            heads.push(load_tensor_into_context(
                file,
                ctx.as_ptr(),
                &format!("code_pred.lm_head.{cb_idx}.weight"),
            )?);
        }
        let hidden_u = talker_cfg.hidden_size as usize;
        let pred_vocab_u = cfg.vocab_size as usize;
        let mut codec_embd_cpu: Option<Vec<Vec<f32>>> = Some(Vec::with_capacity(per_codebook));
        for (cb_idx, embedding) in embeddings.iter().enumerate().take(per_codebook) {
            let name = format!("code_pred.codec_embd.{cb_idx}.weight");
            let row =
                try_read_embedding_matrix_f32(file, &name, *embedding, hidden_u, pred_vocab_u);
            match (&mut codec_embd_cpu, row) {
                (Some(rows), Some(data)) => rows.push(data),
                _ => {
                    codec_embd_cpu = None;
                    break;
                }
            }
        }
        if codec_embd_cpu.as_ref().map(|v| v.len()) != Some(per_codebook) {
            codec_embd_cpu = None;
        }
        let output_norm =
            load_tensor_into_context(file, ctx.as_ptr(), "code_pred.output_norm.weight")?;
        let mut layers = Vec::with_capacity(cfg.n_layers as usize);
        for layer_idx in 0..cfg.n_layers {
            let prefix = format!("code_pred.blk.{layer_idx}.");
            let ffn_down_name = prefix.clone() + "ffn_down.weight";
            layers.push(TalkerLayerWeights {
                attn_norm: load_tensor_into_context(
                    file,
                    ctx.as_ptr(),
                    &(prefix.clone() + "attn_norm.weight"),
                )?,
                attn_q_norm: load_optional_tensor_into_context(
                    file,
                    ctx.as_ptr(),
                    &(prefix.clone() + "attn_q_norm.weight"),
                )?,
                attn_k_norm: load_optional_tensor_into_context(
                    file,
                    ctx.as_ptr(),
                    &(prefix.clone() + "attn_k_norm.weight"),
                )?,
                attn_q: load_tensor_into_context(
                    file,
                    ctx.as_ptr(),
                    &(prefix.clone() + "attn_q.weight"),
                )?,
                attn_k: load_tensor_into_context(
                    file,
                    ctx.as_ptr(),
                    &(prefix.clone() + "attn_k.weight"),
                )?,
                attn_v: load_tensor_into_context(
                    file,
                    ctx.as_ptr(),
                    &(prefix.clone() + "attn_v.weight"),
                )?,
                attn_output: load_tensor_into_context(
                    file,
                    ctx.as_ptr(),
                    &(prefix.clone() + "attn_output.weight"),
                )?,
                ffn_norm: load_tensor_into_context(
                    file,
                    ctx.as_ptr(),
                    &(prefix.clone() + "ffn_norm.weight"),
                )?,
                ffn_gate: load_tensor_into_context(
                    file,
                    ctx.as_ptr(),
                    &(prefix.clone() + "ffn_gate.weight"),
                )?,
                ffn_up: load_tensor_into_context(
                    file,
                    ctx.as_ptr(),
                    &(prefix.clone() + "ffn_up.weight"),
                )?,
                ffn_down: load_tensor_into_context(file, ctx.as_ptr(), &ffn_down_name)?,
                ffn_down_f32: load_tensor_f32_into_context(file, ctx.as_ptr(), &ffn_down_name)?,
            });
        }

        let buffer = OwnedBuffer::alloc(ctx.as_ptr(), backends.primary_ptr())?;
        if let (Some((source, weight_name, bias_name)), Some((weight, bias))) =
            (&projection_source, projection)
        {
            for (name, tensor) in [(weight_name, weight), (bias_name, bias)] {
                let (_, raw) = source.read_tensor_bytes(name)?;
                unsafe {
                    sys::ggml_backend_tensor_set(
                        tensor.as_ptr(),
                        raw.as_ptr().cast(),
                        0,
                        raw.len(),
                    );
                }
            }
        }
        for cb_idx in 0..per_codebook {
            for name in [
                format!("code_pred.codec_embd.{cb_idx}.weight"),
                format!("code_pred.lm_head.{cb_idx}.weight"),
            ] {
                let tensor = if name.contains("codec_embd") {
                    embeddings[cb_idx]
                } else {
                    heads[cb_idx]
                };
                let (_, raw) = file.read_tensor_bytes(&name)?;
                unsafe {
                    sys::ggml_backend_tensor_set(
                        tensor.as_ptr(),
                        raw.as_ptr().cast(),
                        0,
                        raw.len(),
                    );
                }
            }
        }
        let (_, raw) = file.read_tensor_bytes("code_pred.output_norm.weight")?;
        unsafe {
            sys::ggml_backend_tensor_set(output_norm.as_ptr(), raw.as_ptr().cast(), 0, raw.len());
        }
        for (layer_idx, layer) in layers.iter().enumerate() {
            for (suffix, tensor) in [
                ("attn_norm.weight", Some(layer.attn_norm)),
                ("attn_q_norm.weight", layer.attn_q_norm),
                ("attn_k_norm.weight", layer.attn_k_norm),
                ("attn_q.weight", Some(layer.attn_q)),
                ("attn_k.weight", Some(layer.attn_k)),
                ("attn_v.weight", Some(layer.attn_v)),
                ("attn_output.weight", Some(layer.attn_output)),
                ("ffn_norm.weight", Some(layer.ffn_norm)),
                ("ffn_gate.weight", Some(layer.ffn_gate)),
                ("ffn_up.weight", Some(layer.ffn_up)),
                ("ffn_down.weight", Some(layer.ffn_down)),
            ] {
                if let Some(tensor) = tensor {
                    let name = format!("code_pred.blk.{layer_idx}.{suffix}");
                    let (_, raw) = file.read_tensor_bytes(&name)?;
                    unsafe {
                        sys::ggml_backend_tensor_set(
                            tensor.as_ptr(),
                            raw.as_ptr().cast(),
                            0,
                            raw.len(),
                        );
                    }
                }
            }
            if let Some(tensor) = layer.ffn_down_f32 {
                let name = format!("code_pred.blk.{layer_idx}.ffn_down.weight");
                let (_, raw) = file.read_tensor_f32(&name)?;
                unsafe {
                    sys::ggml_backend_tensor_set(
                        tensor.as_ptr(),
                        raw.as_ptr().cast(),
                        0,
                        std::mem::size_of_val(raw.as_slice()),
                    );
                }
            }
        }

        Ok(Self {
            _ctx: ctx,
            _backends: backends,
            _buffer: buffer,
            embeddings,
            projection,
            codec_embd_cpu,
            output_norm,
            heads,
            layers,
        })
    }
}

struct OwnedContext {
    raw: NonNull<sys::ggml_context>,
}

impl OwnedContext {
    fn new(mem_size: usize, no_alloc: bool) -> Result<Self, Qwen3TtsError> {
        let raw = unsafe {
            sys::ggml_init(sys::ggml_init_params {
                mem_size,
                mem_buffer: std::ptr::null_mut(),
                no_alloc,
            })
        };
        let raw = NonNull::new(raw).ok_or_else(|| {
            Qwen3TtsError::InvalidInput("failed to initialize ggml context".into())
        })?;
        Ok(Self { raw })
    }

    fn new_for_tensor_metadata(n_tensors: usize) -> Result<Self, Qwen3TtsError> {
        Self::new(
            max(1, n_tensors) * unsafe { sys::ggml_tensor_overhead() },
            true,
        )
    }

    fn as_ptr(&self) -> *mut sys::ggml_context {
        self.raw.as_ptr()
    }
}

impl Drop for OwnedContext {
    fn drop(&mut self) {
        unsafe {
            sys::ggml_free(self.raw.as_ptr());
        }
    }
}

struct ComputeContext(OwnedContext);

impl ComputeContext {
    fn new_graph(max_nodes: usize) -> Result<Self, Qwen3TtsError> {
        Ok(Self(OwnedContext::new(
            graph_metadata_mem_size(max_nodes),
            true,
        )?))
    }

    fn as_ptr(&self) -> *mut sys::ggml_context {
        self.0.as_ptr()
    }
}

/// When the GGUF tensor is F32/F16 and shaped with `ne[0] == hidden`, `ne[1] == vocab`,
/// return row-major `f32` weights in the same layout as `ggml_get_rows` on that tensor.
fn try_read_embedding_matrix_f32(
    file: &GgufFile,
    name: &str,
    tensor: NonNull<sys::ggml_tensor>,
    hidden: usize,
    vocab: usize,
) -> Option<Vec<f32>> {
    let n0 = unsafe { (*tensor.as_ptr()).ne[0] as usize };
    let n1 = unsafe { (*tensor.as_ptr()).ne[1] as usize };
    if n0 != hidden || n1 != vocab {
        return None;
    }
    let (_, data) = file.read_tensor_f32(name).ok()?;
    (data.len() == hidden * vocab).then_some(data)
}

fn load_tensor_into_context(
    file: &GgufFile,
    ctx: *mut sys::ggml_context,
    name: &str,
) -> Result<NonNull<sys::ggml_tensor>, Qwen3TtsError> {
    let info = file.tensor_info(name)?;
    let mut ne = [1i64; 4];
    for (idx, dim) in info.dims.iter().copied().enumerate() {
        ne[idx] = dim as i64;
    }
    let tensor = unsafe { sys::ggml_new_tensor(ctx, info.ty, info.dims.len() as i32, ne.as_ptr()) };
    NonNull::new(tensor).ok_or_else(|| Qwen3TtsError::InvalidTensor(name.into()))
}

fn load_tensor_f32_into_context(
    file: &GgufFile,
    ctx: *mut sys::ggml_context,
    name: &str,
) -> Result<Option<NonNull<sys::ggml_tensor>>, Qwen3TtsError> {
    let info = match file.tensor_info(name) {
        Ok(info) => info,
        Err(Qwen3TtsError::MissingTensor(_)) => return Ok(None),
        Err(err) => return Err(err),
    };
    // Decide availability based on metadata only: this helper is for tensors
    // that are actually stored as F32 in the GGUF file.
    if info.ty != sys::ggml_type_GGML_TYPE_F32 {
        return Ok(None);
    }
    let mut ne = [1i64; 4];
    for (idx, dim) in info.dims.iter().copied().enumerate() {
        ne[idx] = dim as i64;
    }
    let tensor = unsafe {
        sys::ggml_new_tensor(
            ctx,
            sys::ggml_type_GGML_TYPE_F32,
            info.dims.len() as i32,
            ne.as_ptr(),
        )
    };
    Ok(NonNull::new(tensor))
}

fn load_optional_tensor_into_context(
    file: &GgufFile,
    ctx: *mut sys::ggml_context,
    name: &str,
) -> Result<Option<NonNull<sys::ggml_tensor>>, Qwen3TtsError> {
    match file.tensor_info(name) {
        Ok(info) => {
            let mut ne = [1i64; 4];
            for (idx, dim) in info.dims.iter().copied().enumerate() {
                ne[idx] = dim as i64;
            }
            let tensor =
                unsafe { sys::ggml_new_tensor(ctx, info.ty, info.dims.len() as i32, ne.as_ptr()) };
            Ok(NonNull::new(tensor))
        }
        Err(Qwen3TtsError::MissingTensor(_)) => Ok(None),
        Err(err) => Err(err),
    }
}

fn select_token(
    logits: &[f32],
    repetition_penalty: f32,
    temperature: f32,
    top_k: i32,
    top_p: f32,
    recent_tokens: &[i32],
) -> Result<i32, Qwen3TtsError> {
    if logits.is_empty() {
        return Err(Qwen3TtsError::InvalidInput(
            "logits must not be empty".into(),
        ));
    }

    let mut adjusted = logits.to_vec();
    if repetition_penalty != 1.0 {
        let mut unique_tokens = recent_tokens.to_vec();
        unique_tokens.sort_unstable();
        unique_tokens.dedup();
        for token in unique_tokens {
            let idx = token as usize;
            if idx >= adjusted.len() {
                continue;
            }
            if adjusted[idx] > 0.0 {
                adjusted[idx] /= repetition_penalty;
            } else {
                adjusted[idx] *= repetition_penalty;
            }
        }
    }

    // A top-one request is greedy even when multiple logits share the maximum.
    // Threshold filtering below retains ties, which otherwise reach the RNG.
    if temperature <= 0.0 || top_k == 1 {
        let (best_idx, best_value) = adjusted
            .iter()
            .copied()
            .enumerate()
            .max_by(|a, b| a.1.total_cmp(&b.1))
            .ok_or_else(|| Qwen3TtsError::InvalidInput("failed to select token".into()))?;
        if !best_value.is_finite() {
            return Err(Qwen3TtsError::InvalidInput(
                "all candidate logits were filtered out".into(),
            ));
        }
        return Ok(best_idx as i32);
    }

    if temperature > 0.0 {
        for logit in &mut adjusted {
            *logit /= temperature;
        }
    }

    if top_k > 0 && (top_k as usize) < adjusted.len() {
        let mut ranked = adjusted
            .iter()
            .copied()
            .enumerate()
            .collect::<Vec<(usize, f32)>>();
        ranked.sort_by(|a, b| b.1.total_cmp(&a.1));
        let threshold = ranked[top_k as usize - 1].1;
        for logit in &mut adjusted {
            if *logit < threshold {
                *logit = f32::NEG_INFINITY;
            }
        }
    }

    if top_p.is_finite() && top_p > 0.0 && top_p < 1.0 {
        let mut ranked = adjusted
            .iter()
            .copied()
            .enumerate()
            .collect::<Vec<(usize, f32)>>();
        ranked.sort_by(|a, b| b.1.total_cmp(&a.1));
        let max_logit = ranked
            .iter()
            .map(|(_, logit)| *logit)
            .find(|logit| logit.is_finite())
            .ok_or_else(|| Qwen3TtsError::InvalidInput("all logits are filtered out".into()))?;

        let exp_values = ranked
            .iter()
            .map(|(_, logit)| {
                if logit.is_finite() {
                    (logit - max_logit).exp()
                } else {
                    0.0
                }
            })
            .collect::<Vec<_>>();
        let total = exp_values.iter().sum::<f32>();
        if total <= 0.0 {
            return Err(Qwen3TtsError::InvalidInput(
                "all logits are filtered out".into(),
            ));
        }
        let mut cumulative = 0.0f32;
        let mut keep = vec![false; adjusted.len()];
        for ((idx, logit), prob) in ranked.into_iter().zip(exp_values) {
            if !logit.is_finite() {
                break;
            }
            cumulative += prob / total;
            keep[idx] = true;
            if cumulative >= top_p {
                break;
            }
        }

        if keep.iter().any(|value| *value) {
            for (idx, logit) in adjusted.iter_mut().enumerate() {
                if !keep[idx] {
                    *logit = f32::NEG_INFINITY;
                }
            }
        }
    }

    let mut ranked = adjusted
        .iter()
        .copied()
        .enumerate()
        .filter(|(_, logit)| logit.is_finite())
        .collect::<Vec<_>>();
    if ranked.is_empty() {
        return Err(Qwen3TtsError::InvalidInput(
            "all candidate logits were filtered out".into(),
        ));
    }
    ranked.sort_by(|a, b| b.1.total_cmp(&a.1));
    let max_logit = ranked[0].1;
    let probs = ranked
        .iter()
        .map(|(_, logit)| (logit - max_logit).exp())
        .collect::<Vec<_>>();
    let total = probs.iter().sum::<f32>();
    if !total.is_finite() || total <= 0.0 {
        return Err(Qwen3TtsError::InvalidInput(
            "invalid probability mass during sampling".into(),
        ));
    }
    let mut target = rand::rng().random::<f32>() * total;
    for ((idx, _), prob) in ranked.into_iter().zip(probs) {
        target -= prob;
        if target <= 0.0 {
            return Ok(idx as i32);
        }
    }

    adjusted
        .iter()
        .copied()
        .enumerate()
        .rfind(|(_, logit)| logit.is_finite())
        .map(|(idx, _)| idx as i32)
        .ok_or_else(|| Qwen3TtsError::InvalidInput("failed to sample token".into()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::test_fixture::TestGguf;

    #[test]
    fn select_token_prefers_best_logit() {
        let token = select_token(&[0.1, 2.0, 1.0], 1.0, 0.0, 0, 1.0, &[]).unwrap();
        assert_eq!(token, 1);
    }

    #[test]
    fn select_token_applies_repetition_penalty() {
        let token = select_token(&[5.0, 4.0], 2.0, 0.0, 0, 1.0, &[0]).unwrap();
        assert_eq!(token, 1);
    }

    #[test]
    fn top_one_uses_greedy_tie_break_after_repetition_penalty() {
        let logits = [4.0, 2.0, f32::NEG_INFINITY];
        let expected = select_token(&logits, 2.0, 0.0, 0, 1.0, &[0]).unwrap();
        assert_eq!(expected, 1);
        for _ in 0..64 {
            assert_eq!(
                select_token(&logits, 2.0, 1.0, 1, 1.0, &[0]).unwrap(),
                expected,
            );
        }
    }

    #[test]
    fn top_one_rejects_non_finite_maximum() {
        assert!(select_token(&[f32::NAN, 1.0], 1.0, 1.0, 1, 1.0, &[]).is_err());
        assert!(select_token(&[f32::INFINITY, 1.0], 1.0, 1.0, 1, 1.0, &[]).is_err());
    }
    fn tiny_model(predictor_width: usize, projection: bool) -> TestGguf {
        let mut tensors = vec![
            (
                "talker.text_embd.weight".to_owned(),
                vec![4, 12],
                vec![0.25; 48],
            ),
            (
                "talker.text_proj.fc1.weight".into(),
                vec![4, 4],
                vec![0.1; 16],
            ),
            ("talker.text_proj.fc1.bias".into(), vec![4], vec![0.0; 4]),
            (
                "talker.text_proj.fc2.weight".into(),
                vec![4, 4],
                vec![0.1; 16],
            ),
            ("talker.text_proj.fc2.bias".into(), vec![4], vec![0.0; 4]),
            (
                "talker.codec_embd.weight".into(),
                vec![4, 6],
                (0..24).map(|i| i as f32 / 10.0).collect(),
            ),
            ("talker.output_norm.weight".into(), vec![4], vec![1.0; 4]),
            ("talker.codec_head.weight".into(), vec![4, 6], vec![0.1; 24]),
            (
                "code_pred.output_norm.weight".into(),
                vec![predictor_width as i64],
                vec![1.0; predictor_width],
            ),
        ];
        for cb in 0..2 {
            tensors.push((
                format!("code_pred.codec_embd.{cb}.weight"),
                vec![4, 3],
                (0..12).map(|i| (i + cb) as f32 / 10.0).collect(),
            ));
            tensors.push((
                format!("code_pred.lm_head.{cb}.weight"),
                vec![predictor_width as i64, 3],
                (0..predictor_width * 3)
                    .map(|i| (i + 1) as f32 / 10.0)
                    .collect(),
            ));
        }
        for suffix in ["attn_norm.weight", "ffn_norm.weight"] {
            tensors.push((
                format!("code_pred.blk.0.{suffix}"),
                vec![predictor_width as i64],
                vec![1.0; predictor_width],
            ));
        }
        for suffix in [
            "attn_q.weight",
            "attn_k.weight",
            "attn_v.weight",
            "attn_output.weight",
        ] {
            tensors.push((
                format!("code_pred.blk.0.{suffix}"),
                vec![predictor_width as i64, predictor_width as i64],
                (0..predictor_width * predictor_width)
                    .map(|i| {
                        if i / predictor_width == i % predictor_width {
                            1.0
                        } else {
                            0.0
                        }
                    })
                    .collect(),
            ));
        }
        for suffix in ["ffn_gate.weight", "ffn_up.weight"] {
            tensors.push((
                format!("code_pred.blk.0.{suffix}"),
                vec![predictor_width as i64, 3],
                vec![0.1; predictor_width * 3],
            ));
        }
        tensors.push((
            "code_pred.blk.0.ffn_down.weight".into(),
            vec![3, predictor_width as i64],
            vec![0.1; predictor_width * 3],
        ));
        if projection {
            tensors.push((
                "code_pred.small_to_mtp_projection.weight".into(),
                vec![4, 2],
                vec![1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0],
            ));
            tensors.push((
                "code_pred.small_to_mtp_projection.bias".into(),
                vec![2],
                vec![10.0, 20.0],
            ));
        }
        let specs = tensors
            .iter()
            .map(|(name, dims, values)| (name.as_str(), dims.as_slice(), values.as_slice()))
            .collect::<Vec<_>>();
        TestGguf::write(
            &[
                ("qwen3-tts.talker.embedding_length", 4),
                ("qwen3-tts.talker.block_count", 0),
                ("qwen3-tts.talker.attention.head_count", 2),
                ("qwen3-tts.talker.attention.head_count_kv", 2),
                ("qwen3-tts.talker.attention.key_length", 2),
                ("qwen3-tts.talker.codec_vocab_size", 6),
                ("qwen3-tts.text.vocab_size", 12),
                ("qwen3-tts.text.embedding_dim", 4),
                ("qwen3-tts.talker.num_codebooks", 3),
                ("qwen3-tts.code_pred.layer_count", 1),
                (
                    "qwen3-tts.code_pred.embedding_length",
                    predictor_width as u32,
                ),
                (
                    "qwen3-tts.code_pred.attention.key_length",
                    predictor_width as u32,
                ),
                ("qwen3-tts.code_pred.attention.head_count", 1),
                ("qwen3-tts.code_pred.attention.head_count_kv", 1),
                ("qwen3-tts.code_pred.vocab_size", 3),
                ("qwen3-tts.code_pred.feed_forward_length", 3),
                ("qwen3-tts.tts_bos_token_id", 0),
                ("qwen3-tts.tts_eos_token_id", 1),
                ("qwen3-tts.tts_pad_token_id", 2),
                ("qwen3-tts.codec.pad_id", 0),
                ("qwen3-tts.codec.bos_id", 1),
                ("qwen3-tts.codec.think_id", 2),
                ("qwen3-tts.codec.think_bos_id", 3),
                ("qwen3-tts.codec.think_eos_id", 4),
                ("qwen3-tts.talker.spk_id.vivian", 4),
                ("qwen3-tts.talker.spk_id.ryan", 5),
                ("qwen3-tts.talker.codec_language_id.chinese", 2),
                ("qwen3-tts.talker.codec_language_id.cantonese", 3),
            ],
            &[("qwen3-tts.talker.spk_is_dialect.ryan", "cantonese")],
            &specs,
        )
    }

    #[test]
    fn no_projection_is_exact_identity_without_tensor_or_graph_op() {
        let fixture = tiny_model(4, false);
        let file = GgufFile::open(&fixture.0).unwrap();
        let model = TtsTransformer::load_from_gguf(&file).unwrap();
        assert!(model.code_pred.projection.is_none());
        let ctx = ComputeContext::new_graph(32).unwrap();
        let graph =
            NonNull::new(unsafe { sys::ggml_new_graph_custom(ctx.as_ptr(), 32, false) }).unwrap();
        let input =
            unsafe { sys::ggml_new_tensor_2d(ctx.as_ptr(), sys::ggml_type_GGML_TYPE_F32, 4, 2) };
        assert!(!input.is_null());
        let used_before = unsafe { sys::ggml_used_mem(ctx.as_ptr()) };
        let output = model.code_pred.project_input(ctx.as_ptr(), input);
        assert_eq!(output, input);
        assert_eq!(unsafe { sys::ggml_used_mem(ctx.as_ptr()) }, used_before);
        unsafe { sys::ggml_build_forward_expand(graph.as_ptr(), output) };
        assert_eq!(unsafe { sys::ggml_graph_n_nodes(graph.as_ptr()) }, 0);
    }

    #[test]
    fn split_width_projection_preserves_talker_embeddings() {
        let fixture = tiny_model(2, true);
        let file = GgufFile::open(&fixture.0).unwrap();
        let model = TtsTransformer::load_from_gguf(&file).unwrap();
        assert_eq!(model.config().hidden_size, 4);
        assert_eq!(model.code_predictor_config().hidden_size, 2);
        assert_eq!(model.code_predictor_config().head_dim, 2);
        assert_eq!(model.code_predictor_config().n_attention_heads, 1);
        assert_eq!(model.code_predictor_config().intermediate_size, 3);
        assert_eq!(
            model.lookup_code_pred_embedding_row(0, 1, 1).unwrap().len(),
            4
        );
        assert_eq!(
            model
                .sum_codec_frame_embeddings(&[1, 1, 1], 1)
                .unwrap()
                .len(),
            4
        );
        let ctx = ComputeContext::new_graph(32).unwrap();
        let graph =
            NonNull::new(unsafe { sys::ggml_new_graph_custom(ctx.as_ptr(), 32, false) }).unwrap();
        let input =
            unsafe { sys::ggml_new_tensor_2d(ctx.as_ptr(), sys::ggml_type_GGML_TYPE_F32, 4, 2) };
        let output = model.code_pred.project_input(ctx.as_ptr(), input);
        unsafe {
            sys::ggml_build_forward_expand(graph.as_ptr(), output);
        }
        let values = [1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0];
        let mut result = [0.0f32; 4];
        execute_graph(
            &model.code_pred._backends,
            graph,
            &[TensorUpload {
                tensor: input,
                bytes: slice_as_bytes(&values),
            }],
            &mut [TensorDownload {
                tensor: output,
                bytes: slice_as_bytes_mut(&mut result),
            }],
            1,
            "synthetic projection",
        )
        .unwrap();
        assert_eq!(result, [11.0, 22.0, 15.0, 26.0]);
    }

    #[test]
    #[ignore = "requires QTS_REPLAY_TALKER, QTS_REPLAY_PREDICTOR, QTS_REPLAY_HIDDEN, QTS_REPLAY_CB0"]
    fn replay_predictor_from_reference_hidden() {
        let talker = GgufFile::open(std::env::var("QTS_REPLAY_TALKER").unwrap()).unwrap();
        let predictor = GgufFile::open(std::env::var("QTS_REPLAY_PREDICTOR").unwrap()).unwrap();
        let model = TtsTransformer::load_from_ggufs(&talker, &predictor).unwrap();
        let raw = std::fs::read(std::env::var("QTS_REPLAY_HIDDEN").unwrap()).unwrap();
        assert_eq!(raw.len(), model.config.hidden_size as usize * 4);
        let hidden = raw
            .as_chunks::<4>()
            .0
            .iter()
            .map(|bytes| f32::from_le_bytes(*bytes))
            .collect::<Vec<_>>();
        let cb0 = std::env::var("QTS_REPLAY_CB0").unwrap().parse().unwrap();
        let cache = CodePredKvCache::new(
            &model.code_pred_config,
            model.config.n_codebooks as usize,
            model.code_pred._backends.clone(),
        )
        .unwrap();
        let mut previous = Vec::new();
        for step in 0..model.code_pred.heads.len() {
            let cached = if step == 0 {
                model
                    .forward_code_pred_prefill_cached(&hidden, cb0, 1, &cache)
                    .unwrap()
                    .logits
            } else {
                model
                    .forward_code_pred_step_cached(previous[step - 1], step + 1, step, 1, &cache)
                    .unwrap()
                    .logits
            };
            let recompute = model
                .forward_code_pred_sequence_recompute(&hidden, cb0, &previous, 1)
                .unwrap();
            let mut top = (0..cached.len()).collect::<Vec<_>>();
            top.sort_by(|&a, &b| cached[b].total_cmp(&cached[a]));
            let top5 = top[..5.min(top.len())]
                .iter()
                .map(|&i| (i, cached[i]))
                .collect::<Vec<_>>();
            let max_error = cached
                .iter()
                .zip(&recompute)
                .map(|(a, b)| (a - b).abs())
                .fold(0.0f32, f32::max);
            println!(
                "step={step} top5={top5:?} top2_margin={} cached_recompute_max_error={max_error}",
                cached[top[0]] - cached[top[1]],
            );
            assert!(
                max_error.is_finite() && max_error < 0.1,
                "step {step}: {max_error}"
            );
            previous.push(top[0] as i32);
        }
        println!(
            "codes={:?}",
            std::iter::once(cb0).chain(previous).collect::<Vec<_>>()
        );
    }

    #[test]
    #[ignore = "requires QTS_REPLAY_TALKER, QTS_REPLAY_PREDICTOR, QTS_REPLAY_PREFIX"]
    fn replay_talker_from_reference_inputs() {
        fn read_f32(path: String) -> Vec<f32> {
            let bytes = std::fs::read(path).unwrap();
            assert!(bytes.len().is_multiple_of(4));
            bytes
                .as_chunks::<4>()
                .0
                .iter()
                .map(|b| f32::from_le_bytes(*b))
                .collect()
        }
        let talker = GgufFile::open(std::env::var("QTS_REPLAY_TALKER").unwrap()).unwrap();
        let predictor = GgufFile::open(std::env::var("QTS_REPLAY_PREDICTOR").unwrap()).unwrap();
        let model = TtsTransformer::load_from_ggufs(&talker, &predictor).unwrap();
        let prefix = std::env::var("QTS_REPLAY_PREFIX").unwrap();
        let inputs = read_f32(format!("{prefix}-inputs.f32"));
        let expected = read_f32(format!("{prefix}-logits.f32"));
        let expected_hidden = read_f32(format!("{prefix}-hidden.f32"));
        let hidden = model.config.hidden_size as usize;
        let vocab = model.config.codec_vocab_size as usize;
        assert!(inputs.len().is_multiple_of(hidden));
        assert!(expected.len().is_multiple_of(vocab));
        let steps = expected.len() / vocab;
        assert!(steps > 0 && inputs.len() / hidden >= steps);
        assert_eq!(expected_hidden.len(), steps * hidden);
        let prefill_len = inputs.len() / hidden - steps + 1;
        let cache = TalkerKvCache::new(
            &model.config,
            inputs.len() / hidden + 16,
            model.talker._backends.clone(),
            TalkerKvMode::F16,
        )
        .unwrap();
        let mut logits_dump = Vec::new();
        let mut hidden_dump = Vec::new();
        for step in 0..steps {
            let end = (prefill_len + step) * hidden;
            let out = if step == 0 {
                model
                    .forward_prefill_cached(&inputs[..end], 4, &cache)
                    .unwrap()
            } else {
                model
                    .forward_step_cached(
                        &inputs[end - hidden..end],
                        prefill_len + step - 1,
                        4,
                        &cache,
                    )
                    .unwrap()
            };
            let reference = &expected[step * vocab..(step + 1) * vocab];
            let rms = (out
                .logits
                .iter()
                .zip(reference)
                .map(|(a, b)| (a - b).powi(2))
                .sum::<f32>()
                / vocab as f32)
                .sqrt();
            let hidden_rms = (out
                .hidden_state
                .iter()
                .zip(&expected_hidden[step * hidden..(step + 1) * hidden])
                .map(|(a, b)| (a - b).powi(2))
                .sum::<f32>()
                / hidden as f32)
                .sqrt();
            let mut top = (0..vocab).collect::<Vec<_>>();
            top.sort_by(|&a, &b| out.logits[b].total_cmp(&out.logits[a]));
            println!("step={step} top2={:?} margin={} eos={} reference_eos={} reference_rms={rms} hidden_rms={hidden_rms}",
                top[..2].iter().map(|&i| (i, out.logits[i])).collect::<Vec<_>>(),
                out.logits[top[0]] - out.logits[top[1]],
                out.logits[model.config.codec_eos_id as usize],
                reference[model.config.codec_eos_id as usize],
            );
            if step < 2 {
                let full = model.forward_prefill(&inputs[..end], 4).unwrap();
                let recompute = &full.logits[full.logits.len() - vocab..];
                let error = out
                    .logits
                    .iter()
                    .zip(recompute)
                    .map(|(a, b)| (a - b).abs())
                    .fold(0.0f32, f32::max);
                println!("step={step} cached_recompute_max_error={error}");
            }
            logits_dump.extend(out.logits);
            hidden_dump.extend(out.hidden_state);
        }
        std::fs::write(
            format!("{prefix}-ours-logits.f32"),
            slice_as_bytes(&logits_dump),
        )
        .unwrap();
        std::fs::write(
            format!("{prefix}-ours-hidden.f32"),
            slice_as_bytes(&hidden_dump),
        )
        .unwrap();
    }

    #[test]
    fn projected_talker_masks_eos_for_only_first_two_generated_tokens() {
        for projection in [false, true] {
            let fixture = tiny_model(if projection { 2 } else { 4 }, projection);
            let file = GgufFile::open(&fixture.0).unwrap();
            let mut model = TtsTransformer::load_from_gguf(&file).unwrap();
            model.config.codec_eos_id = 5;
            for generated in 0..4 {
                let mut logits = [0.0f32; 6];
                logits[5] = 10.0;
                model.mask_early_projected_eos(&mut logits, generated);
                assert_eq!(
                    logits[5],
                    if projection && generated < 2 {
                        f32::NEG_INFINITY
                    } else {
                        10.0
                    },
                );
                assert_eq!(&logits[..5], &[0.0; 5]);
            }
        }
    }

    #[test]
    fn projected_talker_hidden_survives_codec_head_allocation() {
        let fixture = tiny_model(2, true);
        let file = GgufFile::open(&fixture.0).unwrap();
        let mut model = TtsTransformer::load_from_gguf(&file).unwrap();
        // A zero-weight layer exercises positions and KV writes without changing
        // the residual. The hidden download must equal RMSNorm(input),
        // independently of codec-head values and graph allocation reuse.
        let zero = model.talker.text_proj_fc1;
        unsafe {
            sys::ggml_backend_tensor_set(zero.as_ptr(), [0.0f32; 16].as_ptr().cast(), 0, 64);
        }
        let norm = model.talker.output_norm;
        model.config.n_layers = 1;
        model.talker.layers.push(TalkerLayerWeights {
            attn_norm: norm,
            attn_q_norm: None,
            attn_k_norm: None,
            attn_q: zero,
            attn_k: zero,
            attn_v: zero,
            attn_output: zero,
            ffn_norm: norm,
            ffn_gate: zero,
            ffn_up: zero,
            ffn_down: zero,
            ffn_down_f32: None,
        });
        let input = [0.2f32, -0.3, 0.4, -0.5];
        let scale = (input.iter().map(|x| x * x).sum::<f32>() / 4.0 + model.config.rms_norm_eps)
            .sqrt()
            .recip();
        let expected = input.map(|x| x * scale);
        let cache = TalkerKvCache::new(
            &model.config,
            16,
            model.talker._backends.clone(),
            TalkerKvMode::F16,
        )
        .unwrap();
        let check = |actual: &[f32]| {
            assert_eq!(actual.len(), expected.len());
            for (a, b) in actual.iter().zip(expected) {
                assert!((a - b).abs() < 1e-5, "hidden overwritten: {actual:?}");
            }
        };
        check(&model.forward_prefill(&input, 1).unwrap().hidden_states);
        check(
            &model
                .forward_prefill_cached(&input, 1, &cache)
                .unwrap()
                .hidden_state,
        );
        check(
            &model
                .forward_step_cached(&input, 1, 1, &cache)
                .unwrap()
                .hidden_state,
        );
    }

    #[test]
    fn predictor_cached_and_recompute_match_with_split_or_equal_widths() {
        for (width, projection) in [(2, true), (4, false)] {
            let fixture = tiny_model(width, projection);
            let file = GgufFile::open(&fixture.0).unwrap();
            let model = TtsTransformer::load_from_gguf(&file).unwrap();
            assert_eq!(model.code_pred.projection.is_some(), projection);
            let cache = CodePredKvCache::new(
                &model.code_pred_config,
                3,
                model.code_pred._backends.clone(),
            )
            .unwrap();
            let hidden = [0.2, 0.3, 0.4, 0.5];
            let recompute = model
                .forward_code_pred_sequence_recompute(&hidden, 1, &[], 1)
                .unwrap();
            let cached = model
                .forward_code_pred_prefill_cached(&hidden, 1, 1, &cache)
                .unwrap()
                .logits;
            assert_eq!(cached.len(), 3);
            for (a, b) in recompute.iter().zip(cached) {
                assert!((a - b).abs() < 0.01);
            }
            let recompute = model
                .forward_code_pred_sequence_recompute(&hidden, 1, &[1], 1)
                .unwrap();
            let cached = model
                .forward_code_pred_step_cached(1, 2, 1, 1, &cache)
                .unwrap()
                .logits;
            for (a, b) in recompute.iter().zip(cached) {
                assert!((a - b).abs() < 0.01);
            }
        }
    }

    #[test]
    fn projection_shape_errors_fail_before_graph_construction() {
        assert!(validate_projection_shapes(4, 4, None, None).is_ok());
        assert!(validate_projection_shapes(4, 2, Some(&[4, 2]), Some(&[2])).is_ok());
        for (weight, bias) in [
            (None, None),
            (Some(&[2, 4][..]), Some(&[2][..])),
            (Some(&[4, 2][..]), None),
            (None, Some(&[2][..])),
            (Some(&[4, 2][..]), Some(&[4][..])),
        ] {
            assert!(validate_projection_shapes(4, 2, weight, bias).is_err());
        }
        let fixture = tiny_model(2, false);
        let file = GgufFile::open(&fixture.0).unwrap();
        assert!(TtsTransformer::load_from_gguf(&file).is_err());
    }

    #[test]
    fn predictor_tensor_fallback_reads_independent_geometry() {
        let fixture = TestGguf::write(
            &[],
            &[],
            &[
                ("code_pred.output_norm.weight", &[2], &[1.0; 2]),
                ("code_pred.blk.0.attn_q.weight", &[2, 4], &[0.0; 8]),
                ("code_pred.blk.0.attn_k.weight", &[2, 2], &[0.0; 4]),
                ("code_pred.blk.0.ffn_gate.weight", &[2, 3], &[0.0; 6]),
            ],
        );
        let file = GgufFile::open(&fixture.0).unwrap();
        let cfg = predictor_config(
            &file,
            &TtsTransformerConfig {
                hidden_size: 4,
                head_dim: 2,
                ..Default::default()
            },
        )
        .unwrap();
        assert_eq!(
            (
                cfg.hidden_size,
                cfg.n_attention_heads,
                cfg.n_key_value_heads,
                cfg.intermediate_size
            ),
            (2, 2, 1, 3)
        );
    }

    #[test]
    fn legacy_base_predictor_keeps_0_1_1_geometry_without_projection() {
        let fixture = TestGguf::write(
            &[
                ("qwen3-tts.code_pred.embedding_length", 1024),
                ("qwen3-tts.code_pred.attention.key_length", 256),
                ("qwen3-tts.code_pred.attention.head_count", 8),
                ("qwen3-tts.code_pred.attention.head_count_kv", 4),
                ("qwen3-tts.code_pred.feed_forward_length", 4096),
                ("qwen3-tts.code_pred.block_count", 3),
            ],
            &[],
            &[("code_pred.output_norm.weight", &[1024], &[1.0; 1024])],
        );
        let file = GgufFile::open(&fixture.0).unwrap();
        let talker = TtsTransformerConfig::default();
        let cfg = predictor_config(&file, &talker).unwrap();
        assert_eq!(cfg.hidden_size, talker.hidden_size);
        assert_eq!(cfg.n_layers, talker.code_pred_layers);
        assert_eq!(cfg.n_attention_heads, talker.n_attention_heads);
        assert_eq!(cfg.n_key_value_heads, talker.n_key_value_heads);
        assert_eq!(cfg.intermediate_size, talker.intermediate_size);
        assert_eq!(cfg.head_dim, talker.head_dim);
        assert_eq!(cfg.rms_norm_eps.to_bits(), talker.rms_norm_eps.to_bits());
        assert_eq!(cfg.rope_theta.to_bits(), talker.rope_theta.to_bits());
        assert_eq!(cfg.vocab_size, talker.code_pred_vocab_size);
    }

    #[test]
    fn presets_use_metadata_ids_and_dialect_language() {
        let fixture = tiny_model(2, true);
        let file = GgufFile::open(&fixture.0).unwrap();
        let model = TtsTransformer::load_from_gguf(&file).unwrap();
        assert_eq!(model.preset_speaker_id(PresetSpeaker::Vivian).unwrap(), 4);
        assert_eq!(model.preset_speaker_id(PresetSpeaker::Ryan).unwrap(), 5);
        assert!(model.preset_speaker_id(PresetSpeaker::Sohee).is_err());
        assert_eq!(
            model
                .preset_speaker_embedding(PresetSpeaker::Ryan, 1)
                .unwrap(),
            vec![2.0, 2.1, 2.2, 2.3]
        );
        assert_eq!(model.preset_language_id(PresetSpeaker::Ryan, -1), 3);
        assert_eq!(model.preset_language_id(PresetSpeaker::Ryan, 2), 3);
        assert_eq!(model.preset_language_id(PresetSpeaker::Ryan, 1), 1);
    }

    #[test]
    fn codec_dump_keeps_first_32_complete_frames_and_survives_later_failure() {
        let fixture = tiny_model(4, false);
        let path = fixture.0.with_extension("codes.json");
        std::fs::write(&path, "stale capture").unwrap();
        let mut dump = CodecCodeDump::new(Some(path.clone())).unwrap();
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "[]\n");
        for frame in 0..32 {
            let codes = (0..16).map(|cb| frame * 100 + cb).collect::<Vec<i32>>();
            dump.record(&codes).unwrap();
        }
        assert_eq!(dump.frames.len(), 32);
        assert_eq!(dump.frames[0], (0..16).collect::<Vec<i32>>());
        assert_eq!(dump.frames[31], (3100..3116).collect::<Vec<i32>>());
        let captured = std::fs::read(&path).unwrap();
        assert!(captured.starts_with(b"[[0, 1, 2, 3,"));
        assert!(captured.ends_with(b"3114, 3115]]\n"));
        dump.record(&[9999; 16]).unwrap();
        drop(dump); // No finalization is needed to retain a failed rollout's prefix.
        assert_eq!(std::fs::read(&path).unwrap(), captured);
        std::fs::remove_file(path).unwrap();
    }

    #[test]
    fn codec_dump_disabled_retains_nothing_and_invalid_path_reports_io_error() {
        let mut dump = CodecCodeDump::new(None).unwrap();
        dump.record(&[1, 2, 3]).unwrap();
        assert!(dump.frames.is_empty());
        let fixture = tiny_model(4, false);
        // Existing file cannot serve as a parent directory.
        assert!(matches!(
            CodecCodeDump::new(Some(fixture.0.join("codes.json"))),
            Err(Qwen3TtsError::Io(_))
        ));
    }

    #[test]
    fn non_streaming_prefill_contains_full_text_eos_and_padded_codec_bos() {
        for (width, projection) in [(2, true), (4, false)] {
            let fixture = tiny_model(width, projection);
            let file = GgufFile::open(&fixture.0).unwrap();
            let model = TtsTransformer::load_from_gguf(&file).unwrap();
            // Distinct text rows detect missing, reordered, or duplicated content/EOS.
            let text_table = (0..48).map(|i| i as f32 / 10.0).collect::<Vec<_>>();
            unsafe {
                sys::ggml_backend_tensor_set(
                    model.talker.text_embd.as_ptr(),
                    text_table.as_ptr().cast(),
                    0,
                    std::mem::size_of_val(text_table.as_slice()),
                );
            }
            let text_tokens = [1, 3, 4, 5, 6, 7, 8, 9, 10, 2, 4];
            let speaker = model
                .preset_speaker_embedding(PresetSpeaker::Vivian, 1)
                .unwrap();
            for speaker_embd in [None, Some(speaker.as_slice())] {
                let conditioning = PrefillConditioning {
                    text_tokens: &text_tokens,
                    speaker_embd,
                    ref_codebook_0: &[],
                    language_id: 1,
                };
                let incremental = model.build_prefill_inputs(conditioning, 1).unwrap();
                let full = model
                    .build_non_streaming_prefill_inputs(conditioning, 1)
                    .unwrap();
                let prefix_len = incremental.prefill_embd.len() - 4;
                let codec_tail = model.lookup_codec_embedding_rows(&[0, 1], 1).unwrap();
                // Explicit upstream layout: content tokens, TTS EOS, then TTS PAD + codec BOS.
                let projected = model.project_text_tokens(&[5, 6, 7, 1, 2], 1).unwrap();
                let mut expected = incremental.prefill_embd[..prefix_len].to_vec();
                for row in projected[..16].as_chunks::<4>().0 {
                    expected.extend(row.iter().zip(&codec_tail[..4]).map(|(a, b)| a + b));
                }
                expected.extend(
                    projected[16..]
                        .iter()
                        .zip(&codec_tail[4..])
                        .map(|(a, b)| a + b),
                );
                assert_eq!(full.prefill_embd, expected);
                assert_eq!(full.trailing_text_hidden, full.tts_pad_embed);
                assert_eq!(full.tts_pad_embed, incremental.tts_pad_embed);
                assert_eq!(incremental.trailing_text_hidden, projected[4..16]);
                let mut with_instruction = full.clone();
                model
                    .prepend_instruction(&mut with_instruction, &[1, 7, 4], 1)
                    .unwrap();
                assert_eq!(&with_instruction.prefill_embd[12..], full.prefill_embd);
                assert_eq!(with_instruction.trailing_text_hidden, full.tts_pad_embed);
            }
        }
    }

    #[test]
    fn instruction_prefill_precedes_assistant_and_design_omits_speaker() {
        let fixture = tiny_model(2, true);
        let file = GgufFile::open(&fixture.0).unwrap();
        let model = TtsTransformer::load_from_gguf(&file).unwrap();
        let text_tokens = [1, 3, 4, 5, 6, 2, 4, 1, 3, 4];
        let speaker = model
            .preset_speaker_embedding(PresetSpeaker::Vivian, 1)
            .unwrap();
        let build = |speaker_embd| {
            model
                .build_prefill_inputs(
                    PrefillConditioning {
                        text_tokens: &text_tokens,
                        speaker_embd,
                        ref_codebook_0: &[],
                        language_id: 1,
                    },
                    1,
                )
                .unwrap()
        };
        let mut design = build(None);
        let custom = build(Some(speaker.as_slice()));
        assert_eq!(custom.prefill_embd.len(), design.prefill_embd.len() + 4);
        let original = design.clone();
        let instruction = [1, 7, 4, 5, 6, 2, 4];
        let expected_prefix = model.project_text_tokens(&instruction, 1).unwrap();
        model
            .prepend_instruction(&mut design, &instruction, 1)
            .unwrap();
        assert_eq!(&design.prefill_embd[..28], expected_prefix);
        assert_eq!(&design.prefill_embd[28..], original.prefill_embd);
        assert_eq!(design.trailing_text_hidden, original.trailing_text_hidden);
        assert_eq!(design.tts_pad_embed, original.tts_pad_embed);
    }
    #[test]
    fn one_seven_b_predictor_metadata_is_not_talker_geometry() {
        let fixture = TestGguf::write(
            &[
                ("qwen3-tts.code_predictor.embedding_length", 1024),
                ("qwen3-tts.code_predictor.attention.head_count", 16),
                ("qwen3-tts.code_predictor.attention.head_count_kv", 8),
                ("qwen3-tts.code_predictor.attention.key_length", 128),
                ("qwen3-tts.code_predictor.feed_forward_length", 3072),
            ],
            &[],
            &[],
        );
        let file = GgufFile::open(&fixture.0).unwrap();
        let talker = TtsTransformerConfig {
            hidden_size: 2048,
            intermediate_size: 6144,
            ..Default::default()
        };
        let cfg = predictor_config(&file, &talker).unwrap();
        assert_eq!((talker.hidden_size, cfg.hidden_size), (2048, 1024));
        assert_eq!(
            (talker.intermediate_size, cfg.intermediate_size),
            (6144, 3072)
        );
        assert!(validate_projection_shapes(2048, 1024, Some(&[2048, 1024]), Some(&[1024])).is_ok());
    }

    #[test]
    fn separate_ggufs_read_predictor_config_and_projection_from_either_file() {
        for projection_in_talker in [false, true] {
            let talker_fixture = tiny_model(
                if projection_in_talker { 2 } else { 4 },
                projection_in_talker,
            );
            let predictor_fixture = tiny_model(2, !projection_in_talker);
            let talker = GgufFile::open(&talker_fixture.0).unwrap();
            let predictor = GgufFile::open(&predictor_fixture.0).unwrap();
            let model = TtsTransformer::load_from_ggufs(&talker, &predictor).unwrap();
            assert_eq!(
                (
                    model.config().hidden_size,
                    model.code_predictor_config().hidden_size
                ),
                (4, 2)
            );
            assert!(model.code_pred.projection.is_some());
        }
    }
}