tpt-gpu-runtime 0.1.0

TPT Runtime - Core library
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
//! LLM inference API for the TPT runtime.
//!
//! # Architecture
//! - `LlmInference` — stable public trait; tpt-spark and tpt-crucible depend on this.
//! - `GpuInferenceEngine` — implementation that routes through layer5 kernel handles
//!   (`EmbeddingKernel`, `RmsNormKernel`, `AttentionKernel`, `GemmKernel`, `SoftmaxKernel`)
//!   with `VendorBackend::detect()` providing automatic CUDA → ROCm → Metal → TPTIR routing.
//! - `ModelInfo` — fields extracted from the GGUF binary header.
//!
//! Weights are zero-initialised at `load()` time; real weight loading from the
//! GGUF tensor section is the next increment. All kernel calls are real — the
//! output is numerically trivial (uniform logits → argmax → token 0) but the
//! full forward-pass path is exercised end-to-end.

use std::io;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

use tpt_gpu_primitives::memory::{BufferFlags, DType, Shape};
use tpt_gpu_primitives::{
    AttentionKernel, EmbeddingKernel, GemmKernel, GpuBuffer, QuantGemmKernel, RmsNormKernel,
    SoftmaxKernel, VendorBackend,
};

use crate::arch::{template_for_arch, ArchTemplate, ForwardOp};
use crate::error::{ErrorCode, TptrError, TptrResult};
use crate::kv_cache::KvCache;
use crate::rope::RopeConfig;

// ---------------------------------------------------------------------------
// ModelInfo
// ---------------------------------------------------------------------------

/// Metadata extracted from the GGUF or TPTF file header.
#[derive(Debug, Clone)]
pub struct ModelInfo {
    pub path: PathBuf,
    /// Architecture tag (e.g. `"llama3"`, `"qwen2"`).
    pub arch: String,
    /// Maximum sequence length supported by this model.
    pub context_len: u32,
    /// Vocabulary size (number of tokens).
    pub vocab_size: u32,
    /// Width of hidden state vectors.
    pub hidden_dim: u32,
    /// Number of query attention heads.
    pub num_heads: u32,
    /// Number of key/value attention heads (GQA; equals `num_heads` for MHA).
    pub num_kv_heads: u32,
    /// Intermediate dimension of the FFN block.
    pub ffn_dim: u32,
    /// Number of transformer layers (blocks).
    pub num_layers: u32,
    /// Per-layer quantization bit depths from tpt-gpu-model-optimizer (2/4/6/8/16).
    /// Empty means all layers use f32. Indexed `[layer_idx]`.
    pub per_layer_bits: Vec<u8>,
    /// Neuron indices zeroed by the surgical pruner, one `Vec<u32>` per layer.
    /// `None` means no pruning was applied.
    pub pruning_mask: Option<Vec<Vec<u32>>>,
}

/// The on-disk format of a model file.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ModelFormat {
    Gguf,
    Tptf,
    Unknown,
}

/// Detect the on-disk format by reading the 4-byte magic.
pub fn detect_format(path: &Path) -> ModelFormat {
    use std::fs::File;
    use std::io::Read;
    let Ok(mut f) = File::open(path) else {
        return ModelFormat::Unknown;
    };
    let mut magic = [0u8; 4];
    if f.read_exact(&mut magic).is_err() {
        return ModelFormat::Unknown;
    }
    match &magic {
        b"GGUF" => ModelFormat::Gguf,
        b"TPTF" => ModelFormat::Tptf,
        _ => ModelFormat::Unknown,
    }
}

// ---------------------------------------------------------------------------
// GGUF header parser
// ---------------------------------------------------------------------------

/// GGUF KV-metadata value types (from the GGUF spec v2/v3).
#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq)]
enum GgufType {
    Uint8 = 0,
    Int8 = 1,
    Uint16 = 2,
    Int16 = 3,
    Uint32 = 4,
    Int32 = 5,
    Float32 = 6,
    Bool = 7,
    String = 8,
    Array = 9,
    Uint64 = 10,
    Int64 = 11,
    Float64 = 12,
}

impl GgufType {
    fn from_u32(v: u32) -> Option<Self> {
        match v {
            0 => Some(Self::Uint8),
            1 => Some(Self::Int8),
            2 => Some(Self::Uint16),
            3 => Some(Self::Int16),
            4 => Some(Self::Uint32),
            5 => Some(Self::Int32),
            6 => Some(Self::Float32),
            7 => Some(Self::Bool),
            8 => Some(Self::String),
            9 => Some(Self::Array),
            10 => Some(Self::Uint64),
            11 => Some(Self::Int64),
            12 => Some(Self::Float64),
            _ => None,
        }
    }

    /// Byte width for scalar types (None for String and Array).
    fn scalar_bytes(self) -> Option<usize> {
        match self {
            Self::Bool | Self::Uint8 | Self::Int8 => Some(1),
            Self::Uint16 | Self::Int16 => Some(2),
            Self::Uint32 | Self::Int32 | Self::Float32 => Some(4),
            Self::Uint64 | Self::Int64 | Self::Float64 => Some(8),
            Self::String | Self::Array => None,
        }
    }
}

/// Minimal reader over a byte buffer with LE integer helpers.
struct BufReader<'a> {
    data: &'a [u8],
    pos: usize,
}

impl<'a> BufReader<'a> {
    fn new(data: &'a [u8]) -> Self {
        Self { data, pos: 0 }
    }

    fn remaining(&self) -> usize {
        self.data.len().saturating_sub(self.pos)
    }

    fn read_bytes(&mut self, n: usize) -> io::Result<&'a [u8]> {
        if self.pos + n > self.data.len() {
            return Err(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "GGUF truncated",
            ));
        }
        let slice = &self.data[self.pos..self.pos + n];
        self.pos += n;
        Ok(slice)
    }

    fn read_u8(&mut self) -> io::Result<u8> {
        Ok(self.read_bytes(1)?[0])
    }
    #[allow(dead_code)]
    fn read_u16(&mut self) -> io::Result<u16> {
        Ok(u16::from_le_bytes(self.read_bytes(2)?.try_into().unwrap()))
    }
    fn read_u32(&mut self) -> io::Result<u32> {
        Ok(u32::from_le_bytes(self.read_bytes(4)?.try_into().unwrap()))
    }
    #[allow(dead_code)]
    fn read_i32(&mut self) -> io::Result<i32> {
        Ok(i32::from_le_bytes(self.read_bytes(4)?.try_into().unwrap()))
    }
    fn read_u64(&mut self) -> io::Result<u64> {
        Ok(u64::from_le_bytes(self.read_bytes(8)?.try_into().unwrap()))
    }
    #[allow(dead_code)]
    fn read_f32(&mut self) -> io::Result<f32> {
        Ok(f32::from_le_bytes(self.read_bytes(4)?.try_into().unwrap()))
    }
    #[allow(dead_code)]
    fn read_bool(&mut self) -> io::Result<bool> {
        Ok(self.read_u8()? != 0)
    }

    fn read_gguf_string(&mut self) -> io::Result<String> {
        let len = self.read_u64()? as usize;
        let bytes = self.read_bytes(len)?;
        String::from_utf8(bytes.to_vec()).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
    }

    /// Skip one GGUF value of the given type without parsing it into Rust.
    fn skip_value(&mut self, vtype: GgufType) -> io::Result<()> {
        match vtype {
            GgufType::String => {
                self.read_gguf_string()?;
            }
            GgufType::Array => {
                let elem_type = GgufType::from_u32(self.read_u32()?).ok_or_else(|| {
                    io::Error::new(io::ErrorKind::InvalidData, "unknown array elem type")
                })?;
                let count = self.read_u64()? as usize;
                for _ in 0..count {
                    self.skip_value(elem_type)?;
                }
            }
            scalar => {
                let n = scalar.scalar_bytes().ok_or_else(|| {
                    io::Error::new(io::ErrorKind::InvalidData, "scalar_bytes unset")
                })?;
                self.read_bytes(n)?;
            }
        }
        Ok(())
    }
}

/// Parse the GGUF v2/v3 binary header and extract fields needed for `ModelInfo`.
///
/// Only reads the KV-metadata section; the tensor index and weight data are not
/// loaded here (that is the next increment — weight loading from GGUF).
pub fn parse_gguf_header(path: &Path) -> TptrResult<ModelInfo> {
    use std::fs;

    if !path.exists() {
        return Err(TptrError::new(
            ErrorCode::InvalidKernel,
            format!("model file not found: {}", path.display()),
        ));
    }

    let data = fs::read(path).map_err(|e| {
        TptrError::new(
            ErrorCode::InternalError,
            format!("cannot read {}: {}", path.display(), e),
        )
    })?;

    let mut r = BufReader::new(&data);

    // Magic
    let magic = r.read_bytes(4).map_err(|e| {
        TptrError::new(
            ErrorCode::InvalidKernel,
            format!("cannot read GGUF magic: {}", e),
        )
    })?;
    if magic != b"GGUF" {
        return Err(TptrError::new(
            ErrorCode::InvalidKernel,
            format!("not a GGUF file (magic = {:?})", magic),
        ));
    }

    // Version
    let version = r.read_u32().map_err(|e| {
        TptrError::new(
            ErrorCode::InvalidKernel,
            format!("cannot read GGUF version: {}", e),
        )
    })?;
    if version == 0 || version > 3 {
        return Err(TptrError::new(
            ErrorCode::InvalidKernel,
            format!("unsupported GGUF version {} (supported: 1, 2, 3)", version),
        ));
    }

    // tensor_count and kv_count (u64 in v2/v3, u32 in v1)
    let (_tensor_count, kv_count) = if version >= 2 {
        (r.read_u64().unwrap_or(0), r.read_u64().unwrap_or(0))
    } else {
        (
            r.read_u32().unwrap_or(0) as u64,
            r.read_u32().unwrap_or(0) as u64,
        )
    };

    // Collect the KV keys we care about
    let mut arch = String::new();
    let mut context_len: u32 = 2048;
    let mut hidden_dim: u32 = 0;
    let mut num_heads: u32 = 0;
    let mut num_kv_heads: u32 = 0;
    let mut ffn_dim: u32 = 0;
    let mut num_layers: u32 = 0;
    let mut vocab_size: u32 = 0;

    for _ in 0..kv_count {
        let key = match r.read_gguf_string() {
            Ok(k) => k,
            Err(_) => break,
        };
        let vtype_raw = match r.read_u32() {
            Ok(v) => v,
            Err(_) => break,
        };
        let vtype = match GgufType::from_u32(vtype_raw) {
            Some(t) => t,
            None => break,
        };

        match key.as_str() {
            "general.architecture" if vtype == GgufType::String => {
                arch = r.read_gguf_string().unwrap_or_default();
            }
            "llm.context_length" if vtype == GgufType::Uint32 => {
                context_len = r.read_u32().unwrap_or(2048);
            }
            "llm.embedding_length" if vtype == GgufType::Uint32 => {
                hidden_dim = r.read_u32().unwrap_or(0);
            }
            "llm.attention.head_count" if vtype == GgufType::Uint32 => {
                num_heads = r.read_u32().unwrap_or(0);
            }
            "llm.attention.head_count_kv" if vtype == GgufType::Uint32 => {
                num_kv_heads = r.read_u32().unwrap_or(0);
            }
            "llm.feed_forward_length" if vtype == GgufType::Uint32 => {
                ffn_dim = r.read_u32().unwrap_or(0);
            }
            "llm.block_count" if vtype == GgufType::Uint32 => {
                num_layers = r.read_u32().unwrap_or(0);
            }
            "tokenizer.ggml.tokens" if vtype == GgufType::Array => {
                // Array: u32 elem_type + u64 count + elements
                let _elem_type = r.read_u32().unwrap_or(0);
                let count = r.read_u64().unwrap_or(0);
                vocab_size = count as u32;
                // Skip the array contents
                let elem_t = GgufType::String; // tokens are strings
                for _ in 0..count {
                    let _ = r.skip_value(elem_t);
                }
            }
            _ => {
                if r.skip_value(vtype).is_err() {
                    break;
                }
            }
        }
    }

    // Apply safe defaults for missing fields
    if hidden_dim == 0 {
        hidden_dim = 4096;
    }
    if num_heads == 0 {
        num_heads = 32;
    }
    if num_layers == 0 {
        num_layers = 32;
    }
    if vocab_size == 0 {
        vocab_size = 32000;
    }
    if ffn_dim == 0 {
        ffn_dim = hidden_dim * 8 / 3;
    } // typical Llama ratio

    Ok(ModelInfo {
        path: path.to_owned(),
        arch,
        context_len,
        vocab_size,
        hidden_dim,
        num_heads,
        num_kv_heads,
        ffn_dim,
        num_layers,
        per_layer_bits: Vec::new(),
        pruning_mask: None,
    })
}

// ---------------------------------------------------------------------------
// TPTF header parser
// ---------------------------------------------------------------------------

/// Parse the TPTF v1 binary header and extract `ModelInfo`.
///
/// TPTF layout (first 512 bytes):
/// - [0..4]   magic "TPTF"
/// - [4..8]   version u32
/// - [8..12]  flags u32 (bit 0 = has_pruning_mask, bit 1 = has_chat_template)
/// - [12..76] arch string: u8 length prefix + UTF-8 bytes (max 63 chars)
/// - [76..80] context_len u32
/// - [80..84] vocab_size u32
/// - [84..88] hidden_dim u32
/// - [88..92] num_heads u32
/// - [92..96] num_kv_heads u32
/// - [96..100] ffn_dim u32
/// - [100..104] num_layers u32
/// - [104..232] per_layer_bits[u8; 128]
pub fn parse_tptf_header(path: &Path) -> TptrResult<ModelInfo> {
    use std::fs;

    if !path.exists() {
        return Err(TptrError::new(
            ErrorCode::InvalidKernel,
            format!("model file not found: {}", path.display()),
        ));
    }

    let data = fs::read(path).map_err(|e| {
        TptrError::new(
            ErrorCode::InternalError,
            format!("cannot read {}: {}", path.display(), e),
        )
    })?;

    if data.len() < 512 {
        return Err(TptrError::new(
            ErrorCode::InvalidKernel,
            format!("TPTF file too short ({} bytes, need ≥ 512)", data.len()),
        ));
    }

    let mut r = BufReader::new(&data);

    let magic = r.read_bytes(4).map_err(|e| {
        TptrError::new(
            ErrorCode::InvalidKernel,
            format!("cannot read TPTF magic: {}", e),
        )
    })?;
    if magic != b"TPTF" {
        return Err(TptrError::new(
            ErrorCode::InvalidKernel,
            format!("not a TPTF file (magic = {:?})", magic),
        ));
    }

    let version = r.read_u32().map_err(|e| {
        TptrError::new(
            ErrorCode::InvalidKernel,
            format!("cannot read TPTF version: {}", e),
        )
    })?;
    if version != 1 {
        return Err(TptrError::new(
            ErrorCode::InvalidKernel,
            format!("unsupported TPTF version {} (supported: 1)", version),
        ));
    }

    let flags = r.read_u32().unwrap_or(0);
    let has_pruning_mask = (flags & 1) != 0;

    // Arch string: 1-byte length prefix + bytes (packed into [12..76])
    let arch_len = r.read_u8().unwrap_or(0) as usize;
    let arch = if arch_len > 0 && arch_len <= 63 {
        let bytes = r.read_bytes(arch_len).unwrap_or_default();
        String::from_utf8_lossy(bytes).to_string()
    } else {
        r.read_bytes(63.min(r.remaining())).ok(); // skip padding
        String::new()
    };
    // Seek to byte 76 (skip any remaining arch padding)
    let consumed = 4 + 4 + 4 + 1 + arch_len;
    if consumed < 76 {
        let _ = r.read_bytes(76 - consumed);
    }

    let context_len = r.read_u32().unwrap_or(2048);
    let vocab_size = r.read_u32().unwrap_or(32000);
    let hidden_dim = r.read_u32().unwrap_or(4096);
    let num_heads = r.read_u32().unwrap_or(32);
    let num_kv_heads = r.read_u32().unwrap_or(8);
    let ffn_dim = r.read_u32().unwrap_or(0);
    let num_layers = r.read_u32().unwrap_or(32);

    // Per-layer bits array [104..232]
    let bits_bytes = r.read_bytes(128).unwrap_or_default();
    let per_layer_bits: Vec<u8> = bits_bytes[..num_layers.min(128) as usize]
        .iter()
        .copied()
        .filter(|&b| b > 0)
        .collect();

    let pruning_mask = if has_pruning_mask {
        Some(vec![Vec::new(); num_layers as usize])
    } else {
        None
    };

    let ffn_dim = if ffn_dim == 0 {
        hidden_dim * 8 / 3
    } else {
        ffn_dim
    };

    Ok(ModelInfo {
        path: path.to_owned(),
        arch,
        context_len,
        vocab_size,
        hidden_dim,
        num_heads,
        num_kv_heads,
        ffn_dim,
        num_layers,
        per_layer_bits,
        pruning_mask,
    })
}

// ---------------------------------------------------------------------------
// Model weights (zero-initialised)
// ---------------------------------------------------------------------------

/// Per-layer weight buffers for a standard transformer block.
struct LayerWeights {
    q_proj: GpuBuffer<f32>,    // [hidden_dim, num_heads * head_dim]
    k_proj: GpuBuffer<f32>,    // [hidden_dim, num_kv_heads * head_dim]
    v_proj: GpuBuffer<f32>,    // [hidden_dim, num_kv_heads * head_dim]
    o_proj: GpuBuffer<f32>,    // [num_heads * head_dim, hidden_dim]
    gate_proj: GpuBuffer<f32>, // [hidden_dim, ffn_dim]
    up_proj: GpuBuffer<f32>,   // [hidden_dim, ffn_dim]
    down_proj: GpuBuffer<f32>, // [ffn_dim, hidden_dim]
    norm1: GpuBuffer<f32>,     // [hidden_dim]
    norm2: GpuBuffer<f32>,     // [hidden_dim]
}

/// Full model weight set (zero-initialised; populated from GGUF tensors in the
/// next increment when the tensor section is parsed).
struct ModelWeights {
    embed_table: GpuBuffer<f32>, // [vocab_size, hidden_dim]
    layers: Vec<LayerWeights>,
    final_norm: GpuBuffer<f32>, // [hidden_dim]
    lm_head: GpuBuffer<f32>,    // [hidden_dim, vocab_size] — or tied to embed_table
    lm_head_tied: bool,
}

fn alloc_f32(rows: usize, cols: usize) -> TptrResult<GpuBuffer<f32>> {
    GpuBuffer::new(Shape::dim2(rows, cols), DType::F32, BufferFlags::STORAGE)
        .map_err(|e| TptrError::new(ErrorCode::AllocationFailure, e.to_string()))
}

fn alloc_f32_1d(n: usize) -> TptrResult<GpuBuffer<f32>> {
    GpuBuffer::new(Shape::new(&[n]), DType::F32, BufferFlags::STORAGE)
        .map_err(|e| TptrError::new(ErrorCode::AllocationFailure, e.to_string()))
}

impl ModelWeights {
    /// Load model weights from a TPTF v1 file.
    ///
    /// Parses the TPTF header via [`parse_tptf_header`], allocates all weight
    /// buffers (zero-initialised), then reads each quantized tensor block from
    /// the tensor data section, dequantizes it to `f32`, and copies the result
    /// into the matching [`GpuBuffer`] field (gate_proj, up_proj, down_proj,
    /// q_proj, k_proj, v_proj, o_proj, norm1, norm2).  Tensors absent from the
    /// file remain zero-initialised (e.g. attention projections when the TPTF
    /// was produced by a FFN-only quantizer pass).
    fn load_tptf(path: &Path, info: &ModelInfo, tied: bool) -> TptrResult<Self> {
        use std::fs;

        let data = fs::read(path).map_err(|e| {
            TptrError::new(
                ErrorCode::InternalError,
                format!("load_tptf: cannot read {}: {}", path.display(), e),
            )
        })?;

        // Tensor section offset is stored as a u64 at byte 460 in the TPTF header.
        // Fall back to the fixed HEADER_SIZE (512) when the field is absent or zero.
        const TPTF_TENSOR_OFFSET_FIELD: usize = 460;
        const TPTF_HEADER_SIZE: usize = 512;
        let tensor_start: usize = if data.len() >= TPTF_TENSOR_OFFSET_FIELD + 8 {
            let raw = u64::from_le_bytes(
                data[TPTF_TENSOR_OFFSET_FIELD..TPTF_TENSOR_OFFSET_FIELD + 8]
                    .try_into()
                    .unwrap(),
            ) as usize;
            if raw >= TPTF_HEADER_SIZE {
                raw
            } else {
                TPTF_HEADER_SIZE
            }
        } else {
            TPTF_HEADER_SIZE
        };

        // Tokenizer section offset (field immediately after tensor_offset).
        let tokenizer_start: usize = if data.len() >= TPTF_TENSOR_OFFSET_FIELD + 16 {
            u64::from_le_bytes(
                data[TPTF_TENSOR_OFFSET_FIELD + 8..TPTF_TENSOR_OFFSET_FIELD + 16]
                    .try_into()
                    .unwrap(),
            ) as usize
        } else {
            0
        };

        let tensor_end = if tokenizer_start > tensor_start {
            tokenizer_start
        } else {
            data.len()
        };

        let mut weights = Self::allocate(info, tied)?;
        let num_layers = info.num_layers as usize;

        // Parse tensor blocks sequentially.  Each block's binary layout:
        //   u32  layer_idx
        //   u8   name_len (max 31)
        //   [u8; name_len]  name
        //   u8   bits
        //   u32  group_size
        //   u32  rows
        //   u32  cols
        //   u32  weights_len
        //   [u8; weights_len]  packed weights
        //   u32  scales_len
        //   [f32; scales_len]  scales
        //   u32  zp_len
        //   [i8; zp_len]  zero_points
        //   <padding to next 128-byte boundary (absolute file position)>
        let mut pos = tensor_start;
        while pos + 14 < tensor_end.min(data.len()) {
            let block_start = pos;

            // layer_idx
            if pos + 4 > data.len() {
                break;
            }
            let layer_idx = u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap()) as usize;
            pos += 4;

            // name
            if pos >= data.len() {
                break;
            }
            let name_len = data[pos] as usize;
            pos += 1;
            if name_len > 31 || pos + name_len > data.len() {
                break;
            }
            let name = String::from_utf8_lossy(&data[pos..pos + name_len]).to_string();
            pos += name_len;

            // bits, group_size, rows, cols
            if pos + 13 > data.len() {
                break;
            }
            let bits = data[pos];
            pos += 1;
            let group_size = u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap()) as usize;
            pos += 4;
            let rows = u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap()) as usize;
            pos += 4;
            let cols = u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap()) as usize;
            pos += 4;

            // packed weights
            if pos + 4 > data.len() {
                break;
            }
            let weights_len = u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap()) as usize;
            pos += 4;
            if pos + weights_len > data.len() {
                break;
            }
            let packed = data[pos..pos + weights_len].to_vec();
            pos += weights_len;

            // scales
            if pos + 4 > data.len() {
                break;
            }
            let scales_len = u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap()) as usize;
            pos += 4;
            if pos + scales_len * 4 > data.len() {
                break;
            }
            let mut scales = vec![1.0f32; scales_len];
            for s in scales.iter_mut() {
                *s = f32::from_le_bytes(data[pos..pos + 4].try_into().unwrap());
                pos += 4;
            }

            // zero_points
            if pos + 4 > data.len() {
                break;
            }
            let zp_len = u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap()) as usize;
            pos += 4;
            if pos + zp_len > data.len() {
                break;
            }
            let zero_points: Vec<i8> = data[pos..pos + zp_len].iter().map(|&b| b as i8).collect();
            pos += zp_len;

            // Advance to the next 128-byte boundary (absolute file position).
            let _ = block_start; // suppress unused warning
            pos = (pos + 127) & !127_usize;

            // Dequantize.
            let num_elements = rows * cols;
            let group_sz = if group_size > 0 {
                group_size
            } else {
                num_elements.max(1)
            };
            let f32_data =
                tptf_dequantize(&packed, &scales, &zero_points, bits, group_sz, num_elements);

            // Copy into the matching GpuBuffer field.
            if layer_idx < num_layers {
                let layer = &mut weights.layers[layer_idx];
                let target: Option<&mut GpuBuffer<f32>> = match name.as_str() {
                    "gate_proj" => Some(&mut layer.gate_proj),
                    "up_proj" => Some(&mut layer.up_proj),
                    "down_proj" => Some(&mut layer.down_proj),
                    "q_proj" => Some(&mut layer.q_proj),
                    "k_proj" => Some(&mut layer.k_proj),
                    "v_proj" => Some(&mut layer.v_proj),
                    "o_proj" => Some(&mut layer.o_proj),
                    "norm1" => Some(&mut layer.norm1),
                    "norm2" => Some(&mut layer.norm2),
                    _ => None,
                };
                if let Some(buf) = target {
                    let n = f32_data.len().min(buf.num_elements());
                    if n > 0 {
                        let _ = buf.copy_from_host(&f32_data[..n]);
                    }
                }
            } else if name == "embed_table" || name == "embedding" {
                let n = f32_data.len().min(weights.embed_table.num_elements());
                if n > 0 {
                    let _ = weights.embed_table.copy_from_host(&f32_data[..n]);
                }
            } else if name == "final_norm" {
                let n = f32_data.len().min(weights.final_norm.num_elements());
                if n > 0 {
                    let _ = weights.final_norm.copy_from_host(&f32_data[..n]);
                }
            } else if name == "lm_head" && !weights.lm_head_tied {
                let n = f32_data.len().min(weights.lm_head.num_elements());
                if n > 0 {
                    let _ = weights.lm_head.copy_from_host(&f32_data[..n]);
                }
            }
        }

        Ok(weights)
    }

    fn allocate(info: &ModelInfo, tied: bool) -> TptrResult<Self> {
        let h = info.hidden_dim as usize;
        let v = info.vocab_size as usize;
        let nh = info.num_heads.max(1) as usize;
        let nk = info.num_kv_heads.max(1) as usize;
        let hd = h / nh; // head_dim
        let f = info.ffn_dim as usize;

        let embed_table = alloc_f32(v, h)?;
        let final_norm = alloc_f32_1d(h)?;
        let lm_head = if tied {
            alloc_f32(1, 1)?
        } else {
            alloc_f32(h, v)?
        }; // placeholder when tied

        let mut layers = Vec::with_capacity(info.num_layers as usize);
        for _ in 0..info.num_layers {
            layers.push(LayerWeights {
                q_proj: alloc_f32(h, nh * hd)?,
                k_proj: alloc_f32(h, nk * hd)?,
                v_proj: alloc_f32(h, nk * hd)?,
                o_proj: alloc_f32(nh * hd, h)?,
                gate_proj: alloc_f32(h, f)?,
                up_proj: alloc_f32(h, f)?,
                down_proj: alloc_f32(f, h)?,
                norm1: alloc_f32_1d(h)?,
                norm2: alloc_f32_1d(h)?,
            });
        }

        Ok(Self {
            embed_table,
            layers,
            final_norm,
            lm_head,
            lm_head_tied: tied,
        })
    }
}

// ---------------------------------------------------------------------------
// RoPE config helpers
// ---------------------------------------------------------------------------

/// Build the `RopeConfig` for a given model, deriving `head_dim` from
/// `hidden_dim / num_heads` and `max_seq_len` from `context_len`.
fn rope_config_for_arch(arch: &str, info: &ModelInfo) -> Option<RopeConfig> {
    let num_heads = info.num_heads.max(1) as usize;
    let head_dim = info.hidden_dim as usize / num_heads;
    let max_seq_len = info.context_len as usize;
    match arch {
        "llama3" => Some(RopeConfig {
            head_dim,
            base: 500_000.0,
            max_seq_len,
        }),
        "llama" => Some(RopeConfig {
            head_dim,
            base: 10_000.0,
            max_seq_len,
        }),
        "mistral" => Some(RopeConfig {
            head_dim,
            base: 10_000.0,
            max_seq_len,
        }),
        "qwen2" | "qwen" => Some(RopeConfig {
            head_dim,
            base: 1_000_000.0,
            max_seq_len,
        }),
        "phi3" => Some(RopeConfig {
            head_dim,
            base: 10_000.0,
            max_seq_len,
        }),
        "gemma2" | "gemma" => Some(RopeConfig {
            head_dim,
            base: 10_000.0,
            max_seq_len,
        }),
        _ => None,
    }
}

// ---------------------------------------------------------------------------
// LlmInference trait
// ---------------------------------------------------------------------------

/// Core trait for LLM token-level inference via the TPT runtime.
///
/// # Contract
/// - `load` is called once; subsequent `infer` calls reuse the loaded weights.
/// - `callback` is invoked for each generated token in order.
/// - `cancel` signals the engine to stop at the next safe preemption point.
pub trait LlmInference: Send + Sync {
    fn load(model_path: &Path) -> TptrResult<Self>
    where
        Self: Sized;
    fn model_info(&self) -> &ModelInfo;
    fn infer(
        &mut self,
        tokens: &[u32],
        max_new_tokens: u32,
        callback: impl FnMut(u32) + Send,
    ) -> TptrResult<()>;
    fn cancel(&mut self);
}

// ---------------------------------------------------------------------------
// GpuInferenceEngine
// ---------------------------------------------------------------------------

/// GPU-backed inference engine.
///
/// Routes through layer5 kernel handles with automatic hardware detection:
/// `VendorBackend::detect()` selects CUDA → ROCm → Metal → TPTIR fallback.
pub struct GpuInferenceEngine {
    info: ModelInfo,
    template: ArchTemplate,
    weights: ModelWeights,
    embed_k: EmbeddingKernel,
    rmsnorm_k: RmsNormKernel,
    attn_k: AttentionKernel,
    gemm_k: GemmKernel,
    quant_gemm_k: QuantGemmKernel,
    softmax_k: SoftmaxKernel,
    kv_cache: KvCache,
    cancelled: Arc<Mutex<bool>>,
    /// xorshift64 PRNG state for temperature sampling (never zero).
    rng_state: u64,
    /// RoPE configuration derived from the model architecture.
    /// `None` only for architectures that do not use RoPE (none currently supported).
    rope_config: Option<RopeConfig>,
}

impl std::fmt::Debug for GpuInferenceEngine {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GpuInferenceEngine")
            .field("arch", &self.info.arch)
            .field("num_layers", &self.info.num_layers)
            .finish()
    }
}

impl LlmInference for GpuInferenceEngine {
    fn load(model_path: &Path) -> TptrResult<Self> {
        let fmt = detect_format(model_path);
        let info = match fmt {
            ModelFormat::Gguf => parse_gguf_header(model_path)?,
            ModelFormat::Tptf => parse_tptf_header(model_path)?,
            ModelFormat::Unknown => {
                // Fall back to GGUF parser which will give a descriptive error.
                parse_gguf_header(model_path)?
            }
        };
        let template = template_for_arch(&info.arch, &info)?;

        // Determine if this arch uses tied embeddings.
        let tied = template
            .post_ops
            .iter()
            .any(|op| matches!(op, ForwardOp::LinearOut { tied: true, .. }));

        // For TPTF files load the quantized tensor blocks from the tensor data
        // section rather than returning a zero-initialised weight set.
        let weights = if fmt == ModelFormat::Tptf {
            ModelWeights::load_tptf(model_path, &info, tied)?
        } else {
            ModelWeights::allocate(&info, tied)?
        };

        // All kernel handles share a single VendorBackend::detect() result.
        let vendor = VendorBackend::detect();
        let embed_k = EmbeddingKernel::with_vendor(vendor.clone());
        let rmsnorm_k = RmsNormKernel::with_vendor(vendor.clone());
        let attn_k = AttentionKernel::with_vendor(vendor.clone());
        let gemm_k = GemmKernel::with_vendor(vendor.clone());
        let quant_gemm_k = QuantGemmKernel::with_vendor(vendor.clone());
        let softmax_k = SoftmaxKernel::with_vendor(vendor);

        let head_dim = info.hidden_dim / info.num_heads.max(1);
        let kv_cache = KvCache::new(
            info.num_layers,
            info.context_len,
            info.num_kv_heads.max(1),
            head_dim,
        );

        let rope_config = rope_config_for_arch(&info.arch, &info);

        Ok(Self {
            info,
            template,
            weights,
            embed_k,
            rmsnorm_k,
            attn_k,
            gemm_k,
            quant_gemm_k,
            softmax_k,
            kv_cache,
            cancelled: Arc::new(Mutex::new(false)),
            rng_state: 0x853c49e6748fea9b,
            rope_config,
        })
    }

    fn model_info(&self) -> &ModelInfo {
        &self.info
    }

    fn infer(
        &mut self,
        tokens: &[u32],
        max_new_tokens: u32,
        mut callback: impl FnMut(u32) + Send,
    ) -> TptrResult<()> {
        if tokens.is_empty() {
            return Err(TptrError::new(
                ErrorCode::ArgumentMismatch,
                "token list is empty",
            ));
        }

        self.kv_cache.reset();

        // Decode mode: process one token at a time starting from the last prompt token.
        // Prefill (processing all prompt tokens at once) is a future optimisation.
        let mut current_token = *tokens.last().unwrap();

        for _ in 0..max_new_tokens {
            if *self.cancelled.lock().unwrap() {
                break;
            }

            let next = self.forward_step(current_token)?;
            callback(next);
            current_token = next;
        }

        Ok(())
    }

    fn cancel(&mut self) {
        *self.cancelled.lock().unwrap() = true;
    }
}

impl GpuInferenceEngine {
    /// Run one autoregressive decode step for a single token.
    ///
    /// Returns the sampled next token ID.
    fn forward_step(&mut self, token: u32) -> TptrResult<u32> {
        let hidden_dim = self.info.hidden_dim as usize;
        let vocab_size = self.info.vocab_size as usize;
        let num_heads = self.info.num_heads.max(1) as usize;
        let num_kv = self.info.num_kv_heads.max(1) as usize;
        let head_dim = hidden_dim / num_heads;
        let ffn_dim = self.info.ffn_dim as usize;

        // --- Pre-ops: Embedding ---
        let idx_buf = token_to_index_buffer(token)?;
        let mut hidden = self
            .embed_k
            .execute(&self.weights.embed_table, &idx_buf)
            .map_err(|e| TptrError::new(ErrorCode::LaunchFailure, e.to_string()))?;
        // Reshape to [1, hidden_dim] for GEMM compatibility
        hidden = reshape_to_2d(hidden, 1, hidden_dim)?;

        // --- Per-layer ops ---
        for layer_idx in 0..self.info.num_layers as usize {
            if *self.cancelled.lock().unwrap() {
                return Ok(0);
            }

            // Quantization bit depth for this layer (0 = f32).
            let layer_bits = self
                .info
                .per_layer_bits
                .get(layer_idx)
                .copied()
                .unwrap_or(0);

            let layer = &self.weights.layers[layer_idx];

            // Pre-attention RmsNorm
            let normed = self.rmsnorm_k.execute(&hidden, &layer.norm1).map_err(|e| {
                TptrError::new(
                    ErrorCode::LaunchFailure,
                    format!("rmsnorm1 layer {}: {}", layer_idx, e),
                )
            })?;
            let normed = reshape_to_2d(normed, 1, hidden_dim)?;

            // Q, K, V projections — dispatch through QuantGemm for quantized layers.
            macro_rules! proj_gemm {
                ($input:expr, $weight:expr, $name:literal) => {
                    if layer_bits > 0 {
                        quant_layer_gemm(&self.quant_gemm_k, $input, $weight, layer_bits).map_err(
                            |e| {
                                TptrError::new(
                                    ErrorCode::LaunchFailure,
                                    format!("{} layer {}: {}", $name, layer_idx, e),
                                )
                            },
                        )
                    } else {
                        self.gemm_k
                            .execute($input, $weight, None, 1.0, 0.0)
                            .map_err(|e| {
                                TptrError::new(
                                    ErrorCode::LaunchFailure,
                                    format!("{} layer {}: {}", $name, layer_idx, e),
                                )
                            })
                    }
                };
            }

            let q = proj_gemm!(&normed, &layer.q_proj, "q_proj")?;
            let k = proj_gemm!(&normed, &layer.k_proj, "k_proj")?;
            let v = proj_gemm!(&normed, &layer.v_proj, "v_proj")?;

            // Apply RoPE to Q and K before caching so stored K values carry
            // positional information.  The decode position is the current
            // KV-cache length (0-indexed: first token is position 0).
            let rope_pos = self.kv_cache.seq_len;
            let (q, k) = if let Some(ref rope_cfg) = self.rope_config {
                let mut q_data = buf_to_vec(&q);
                let mut k_data = buf_to_vec(&k);
                crate::rope::apply_rope(&mut q_data, &mut k_data, rope_pos, rope_cfg);
                let q_rotated = vec_to_buf(q_data, 1, num_heads * head_dim)?;
                let k_rotated = vec_to_buf(k_data, 1, num_kv * head_dim)?;
                (q_rotated, k_rotated)
            } else {
                (q, k)
            };

            // KV cache: append current step's K and V.
            // After append, the token data is at position `kv_step - 1` but
            // seq_len only increments once the last layer has appended.
            // We use get_k_at / get_v_at with `kv_step` to read all positions
            // including the just-written one regardless of seq_len's state.
            let kv_step = self.kv_cache.seq_len + 1;
            let k_data = buf_to_vec(&k);
            let v_data = buf_to_vec(&v);
            self.kv_cache.append(layer_idx, &k_data, &v_data);

            let qk_dim = num_heads * head_dim;
            let kv_row = num_kv * head_dim;
            // Expand GQA/MQA KV heads to full query-head dimension.
            let k_full = expand_kv_heads(
                self.kv_cache.get_k_at(layer_idx, kv_step),
                kv_step,
                kv_row,
                qk_dim,
            );
            let v_full = expand_kv_heads(
                self.kv_cache.get_v_at(layer_idx, kv_step),
                kv_step,
                kv_row,
                qk_dim,
            );
            let k_cache = vec_to_buf(k_full, kv_step, qk_dim)?;
            let v_cache = vec_to_buf(v_full, kv_step, qk_dim)?;

            let scale = Some(1.0 / (head_dim as f32).sqrt());
            // Q is the current token [1, qk_dim]; K/V are the full history
            // [kv_step, qk_dim]. The AttentionKernel now supports cross-attention
            // (q_len != kv_len) so this routes through the host fallback.
            let q2d = reshape_to_2d(q, 1, qk_dim)?;
            let attn_out = self
                .attn_k
                .execute(&q2d, &k_cache, &v_cache, scale, None)
                .map_err(|e| {
                    TptrError::new(
                        ErrorCode::LaunchFailure,
                        format!("attention layer {}: {}", layer_idx, e),
                    )
                })?;
            let attn_dim = attn_out_dim(&attn_out);
            let attn_out = reshape_to_2d(attn_out, 1, attn_dim)?;

            // Output projection + residual
            let o = proj_gemm!(&attn_out, &layer.o_proj, "o_proj")?;
            let o = reshape_to_2d(o, 1, hidden_dim)?;
            hidden = elementwise_add_2d(&hidden, &o, hidden_dim)?;

            // Pre-FFN RmsNorm
            let normed2 = self.rmsnorm_k.execute(&hidden, &layer.norm2).map_err(|e| {
                TptrError::new(
                    ErrorCode::LaunchFailure,
                    format!("rmsnorm2 layer {}: {}", layer_idx, e),
                )
            })?;
            let normed2 = reshape_to_2d(normed2, 1, hidden_dim)?;

            // SwiGLU FFN: gate, up, silu(gate)*up, down
            let gate = proj_gemm!(&normed2, &layer.gate_proj, "gate_proj")?;
            let up = proj_gemm!(&normed2, &layer.up_proj, "up_proj")?;

            let ffn_mid = swiglu_host(&gate, &up, ffn_dim)?;
            let ffn_mid = reshape_to_2d(ffn_mid, 1, ffn_dim)?;

            let ffn_out = proj_gemm!(&ffn_mid, &layer.down_proj, "down_proj")?;
            let ffn_out = reshape_to_2d(ffn_out, 1, hidden_dim)?;

            hidden = elementwise_add_2d(&hidden, &ffn_out, hidden_dim)?;
        }

        // --- Post-ops: final norm, lm_head, softmax, sample ---
        let normed_final = self
            .rmsnorm_k
            .execute(&hidden, &self.weights.final_norm)
            .map_err(|e| {
                TptrError::new(ErrorCode::LaunchFailure, format!("final rmsnorm: {}", e))
            })?;
        let normed_final = reshape_to_2d(normed_final, 1, hidden_dim)?;

        let lm_weight = if self.weights.lm_head_tied {
            &self.weights.embed_table
        } else {
            &self.weights.lm_head
        };
        // lm_head: [1, hidden_dim] × [hidden_dim, vocab_size] → [1, vocab_size]
        // For tied embeddings the embed_table is [vocab_size, hidden_dim]; we transpose by
        // swapping arguments: GEMM(hidden, W^T) where W^T is [hidden_dim, vocab_size].
        // We approximate by treating the embed_table as already transposed here.
        let logits_raw = if self.weights.lm_head_tied {
            // Tied: embed_table is [vocab_size, hidden_dim]; compute host-side dot products
            tied_lm_head_host(
                &normed_final,
                &self.weights.embed_table,
                hidden_dim,
                vocab_size,
            )?
        } else {
            self.gemm_k
                .execute(&normed_final, lm_weight, None, 1.0, 0.0)
                .map_err(|e| TptrError::new(ErrorCode::LaunchFailure, format!("lm_head: {}", e)))?
        };

        let logits = reshape_to_2d(logits_raw, 1, vocab_size)?;

        // Extract temperature and top_k from the arch template's Sampling post-op.
        let (temperature, top_k) = self
            .template
            .post_ops
            .iter()
            .find_map(|op| {
                if let ForwardOp::Sampling { temperature, top_k } = op {
                    Some((*temperature, *top_k))
                } else {
                    None
                }
            })
            .unwrap_or((1.0, 1));

        if temperature <= 0.0 || top_k <= 1 {
            // Greedy: softmax then argmax.
            let probs = self
                .softmax_k
                .execute(&logits)
                .map_err(|e| TptrError::new(ErrorCode::LaunchFailure, format!("softmax: {}", e)))?;
            return Ok(sample_argmax(&probs, vocab_size));
        }

        // Temperature scaling + top-k sampling.
        let next = self.sample_with_temperature(&logits, vocab_size, temperature, top_k)?;
        Ok(next)
    }

    /// Temperature-scaled top-k categorical sampling.
    ///
    /// Divides logits by `temperature`, masks all but the top-k entries,
    /// applies softmax over those k entries, then draws a sample using a
    /// xorshift64 PRNG embedded in `self.rng_state`.
    fn sample_with_temperature(
        &mut self,
        logits: &GpuBuffer<f32>,
        vocab_size: usize,
        temperature: f32,
        top_k: u32,
    ) -> TptrResult<u32> {
        let mut raw = vec![0.0f32; vocab_size];
        let n = raw.len().min(logits.num_elements());
        let _ = logits.copy_to_host(&mut raw[..n]);

        // Apply temperature.
        for x in raw.iter_mut() {
            *x /= temperature;
        }

        // Find the top-k indices by partial sort (selection).
        let k = (top_k as usize).min(vocab_size).max(1);
        let mut indexed: Vec<(usize, f32)> = raw.iter().cloned().enumerate().collect();
        indexed.sort_unstable_by(|(_, a), (_, b)| {
            b.partial_cmp(a).unwrap_or(std::cmp::Ordering::Equal)
        });
        indexed.truncate(k);

        // Numerically-stable softmax over top-k.
        let max_val = indexed
            .iter()
            .map(|(_, v)| *v)
            .fold(f32::NEG_INFINITY, f32::max);
        let mut expd: Vec<f32> = indexed.iter().map(|(_, v)| (*v - max_val).exp()).collect();
        let sum: f32 = expd.iter().sum();
        if sum > 0.0 {
            for e in expd.iter_mut() {
                *e /= sum;
            }
        }

        // Categorical sample via xorshift64.
        let u = xorshift64(&mut self.rng_state);
        let mut cumsum = 0.0f32;
        for (i, p) in expd.iter().enumerate() {
            cumsum += p;
            if u <= cumsum || i + 1 == k {
                return Ok(indexed[i].0 as u32);
            }
        }
        Ok(indexed[0].0 as u32)
    }
}

// ---------------------------------------------------------------------------
// Helper functions
// ---------------------------------------------------------------------------

/// Wrap a single token ID as a `GpuBuffer<i32>` of shape `[1]`.
fn token_to_index_buffer(token: u32) -> TptrResult<GpuBuffer<i32>> {
    let mut buf = GpuBuffer::<i32>::new(Shape::new(&[1]), DType::I32, BufferFlags::STORAGE)
        .map_err(|e| TptrError::new(ErrorCode::AllocationFailure, e.to_string()))?;
    buf.copy_from_host(&[token as i32])
        .map_err(|e| TptrError::new(ErrorCode::AllocationFailure, e.to_string()))?;
    Ok(buf)
}

/// Re-interpret a `GpuBuffer` as `[rows, cols]` — creates a new buffer with
/// the same data and the target shape.
fn reshape_to_2d(buf: GpuBuffer<f32>, rows: usize, cols: usize) -> TptrResult<GpuBuffer<f32>> {
    let n = rows * cols;
    let mut src = vec![0.0f32; buf.num_elements().max(1)];
    let copy_len = src.len().min(buf.num_elements());
    let _ = buf.copy_to_host(&mut src[..copy_len]);
    let mut out = GpuBuffer::<f32>::new(Shape::dim2(rows, cols), DType::F32, BufferFlags::STORAGE)
        .map_err(|e| TptrError::new(ErrorCode::AllocationFailure, e.to_string()))?;
    let mut dst = vec![0.0f32; n];
    let fill_len = dst.len().min(src.len());
    dst[..fill_len].copy_from_slice(&src[..fill_len]);
    out.copy_from_host(&dst)
        .map_err(|e| TptrError::new(ErrorCode::AllocationFailure, e.to_string()))?;
    Ok(out)
}

/// Infer the output dimension of an attention result buffer.
fn attn_out_dim(buf: &GpuBuffer<f32>) -> usize {
    buf.dim(1).unwrap_or(buf.num_elements())
}

/// Quantize a float weight matrix and run QuantGemmKernel.
///
/// Computes `activation @ weight` by packing `weight^T` as `i8` with per-group
/// scales and dispatching through `QuantGemmKernel`.  The result has shape
/// `[1, out_dim]`, identical to the f32 GEMM path.
///
/// This establishes the full quantized GEMM code path. When real GGUF tensor
/// loading lands, weights should be stored pre-packed instead of quantized here.
fn quant_layer_gemm(
    quant_k: &QuantGemmKernel,
    activation: &GpuBuffer<f32>,
    weight: &GpuBuffer<f32>,
    bits: u8,
) -> TptrResult<GpuBuffer<f32>> {
    let in_dim = weight.dim(0).unwrap_or(0);
    let out_dim = weight.dim(1).unwrap_or(0);
    if in_dim == 0 || out_dim == 0 {
        return Err(TptrError::new(
            ErrorCode::ArgumentMismatch,
            "quant_layer_gemm: weight has zero dimension",
        ));
    }

    // Read weight [in_dim, out_dim] and activation [1, in_dim].
    let mut w = vec![0.0f32; in_dim * out_dim];
    let wn = w.len().min(weight.num_elements());
    let _ = weight.copy_to_host(&mut w[..wn]);

    let mut act = vec![0.0f32; in_dim];
    let an = act.len().min(activation.num_elements());
    let _ = activation.copy_to_host(&mut act[..an]);

    // Transpose weight to W^T [out_dim, in_dim] for QuantGemmKernel's row-major layout.
    let mut wt = vec![0.0f32; out_dim * in_dim];
    for r in 0..in_dim {
        for c in 0..out_dim {
            wt[c * in_dim + r] = w[r * out_dim + c];
        }
    }

    // Compute per-group scales for W^T rows (= W columns = output neurons).
    let bits_u = bits.max(1) as usize;
    let pack_factor = (8usize / bits_u).max(1);
    let packed_k = in_dim.div_ceil(pack_factor);
    let group_size = tpt_gpu_primitives::DEFAULT_GROUP_SIZE as usize;
    let groups_per_row = in_dim.div_ceil(group_size);
    let max_int = ((1u32 << bits) - 1) as f32 / 2.0;

    let mut scales = vec![1.0f32; out_dim * groups_per_row];
    for row in 0..out_dim {
        for g in 0..groups_per_row {
            let start = row * in_dim + g * group_size;
            let end = (start + group_size).min(row * in_dim + in_dim);
            let max_abs = wt[start..end]
                .iter()
                .map(|x| x.abs())
                .fold(0.0f32, f32::max);
            scales[row * groups_per_row + g] = if max_abs > 0.0 {
                max_abs / max_int
            } else {
                1.0
            };
        }
    }

    // Pack W^T rows into i8.
    let mut packed = vec![0i8; out_dim * packed_k];
    for row in 0..out_dim {
        for col in 0..in_dim {
            let g = col / group_size;
            let scale = scales[row * groups_per_row + g];
            let val = (wt[row * in_dim + col] / scale)
                .round()
                .clamp(-max_int, max_int) as i8;
            let packed_col = col / pack_factor;
            let shift = (col % pack_factor) * bits_u;
            packed[row * packed_k + packed_col] |= ((val as u8) << shift) as i8;
        }
    }

    // Build GpuBuffers.
    let mut a_buf = GpuBuffer::<i8>::new(
        Shape::dim2(out_dim, packed_k),
        DType::I8,
        BufferFlags::STORAGE,
    )
    .map_err(|e| TptrError::new(ErrorCode::AllocationFailure, e.to_string()))?;
    a_buf
        .copy_from_host(&packed)
        .map_err(|e| TptrError::new(ErrorCode::AllocationFailure, e.to_string()))?;

    // b_f32 = activation^T [in_dim, 1].
    let mut b_buf = GpuBuffer::<f32>::new(Shape::dim2(in_dim, 1), DType::F32, BufferFlags::STORAGE)
        .map_err(|e| TptrError::new(ErrorCode::AllocationFailure, e.to_string()))?;
    b_buf
        .copy_from_host(&act)
        .map_err(|e| TptrError::new(ErrorCode::AllocationFailure, e.to_string()))?;

    let mut sc_buf = GpuBuffer::<f32>::new(
        Shape::dim2(out_dim, groups_per_row),
        DType::F32,
        BufferFlags::STORAGE,
    )
    .map_err(|e| TptrError::new(ErrorCode::AllocationFailure, e.to_string()))?;
    sc_buf
        .copy_from_host(&scales)
        .map_err(|e| TptrError::new(ErrorCode::AllocationFailure, e.to_string()))?;

    let zp_buf = GpuBuffer::<i8>::new(
        Shape::dim2(out_dim, groups_per_row),
        DType::I8,
        BufferFlags::STORAGE,
    )
    .map_err(|e| TptrError::new(ErrorCode::AllocationFailure, e.to_string()))?;

    // dequant(W^T) @ act^T → [out_dim, 1]; reshape to [1, out_dim].
    let result = quant_k
        .execute(&a_buf, &b_buf, &sc_buf, &zp_buf)
        .map_err(|e| TptrError::new(ErrorCode::LaunchFailure, e.to_string()))?;

    // Transpose [out_dim, 1] → [1, out_dim].
    let mut out_raw = vec![0.0f32; out_dim];
    let rn = out_raw.len().min(result.num_elements());
    let _ = result.copy_to_host(&mut out_raw[..rn]);
    vec_to_buf(out_raw, 1, out_dim)
}

/// Expand GQA/MQA KV head layout to match the full query-head count.
///
/// `src` is a flat slice of `[seq_len × kv_row]` floats where `kv_row =
/// num_kv_heads × head_dim`.  Returns a `Vec` of `[seq_len × qk_dim]` floats
/// where `qk_dim = num_heads × head_dim`, repeating KV heads cyclically to
/// fill all query heads (standard GQA broadcasting).
fn expand_kv_heads(src: &[f32], seq_len: usize, kv_row: usize, qk_dim: usize) -> Vec<f32> {
    if seq_len == 0 || qk_dim == 0 {
        return vec![];
    }
    if kv_row >= qk_dim {
        // MHA or already full width — just copy / pad each row.
        let mut out = vec![0.0f32; seq_len * qk_dim];
        for t in 0..seq_len {
            let src_start = t * kv_row;
            let dst_start = t * qk_dim;
            let copy = qk_dim.min(kv_row).min(src.len().saturating_sub(src_start));
            if copy > 0 {
                out[dst_start..dst_start + copy].copy_from_slice(&src[src_start..src_start + copy]);
            }
        }
        return out;
    }
    // GQA: broadcast kv_row → qk_dim by cycling.
    let mut out = vec![0.0f32; seq_len * qk_dim];
    for t in 0..seq_len {
        let src_start = t * kv_row;
        let dst_start = t * qk_dim;
        for i in 0..qk_dim {
            let src_i = src_start + (i % kv_row);
            if src_i < src.len() {
                out[dst_start + i] = src[src_i];
            }
        }
    }
    out
}

/// Dequantize a packed tensor block (matching the `quantize_tensor` format used
/// by `tpt-gpu-model-optimizer`) back to `f32`.
///
/// For `bits >= 16` the weight bytes are interpreted directly as little-endian
/// `f32` values (no quantization was applied during storage).  For sub-byte
/// depths the values are extracted LSB-first, then dequantized:
/// `result[i] = (q + zero_point) * scale`
/// where `q` is the per-element quantized integer and scale/zp are per-group.
fn tptf_dequantize(
    quantized: &[u8],
    scales: &[f32],
    zero_points: &[i8],
    bits: u8,
    group_size: usize,
    num_elements: usize,
) -> Vec<f32> {
    if bits >= 16 {
        // Raw f32 LE bytes (bits == 16 → no quantization path in quantize_tensor).
        let float_count = num_elements.min(quantized.len() / 4);
        let mut result = vec![0.0f32; num_elements];
        for i in 0..float_count {
            let b = &quantized[i * 4..(i + 1) * 4];
            result[i] = f32::from_le_bytes([b[0], b[1], b[2], b[3]]);
        }
        return result;
    }

    let pack_factor = (8usize / bits as usize).max(1);
    let mask = (1u16 << bits) - 1;
    let mut result = vec![0.0f32; num_elements];

    for (elem_idx, out) in result.iter_mut().enumerate() {
        let packed_byte_idx = elem_idx / pack_factor;
        let bit_offset = (elem_idx % pack_factor) * bits as usize;

        if packed_byte_idx < quantized.len() {
            let byte = quantized[packed_byte_idx] as u16;
            let q = (byte >> bit_offset) & mask;

            let group_idx = elem_idx / group_size;
            let scale = scales.get(group_idx).copied().unwrap_or(1.0);
            let zp = zero_points.get(group_idx).copied().unwrap_or(0) as f32;

            *out = (q as f32 + zp) * scale;
        }
    }

    result
}

/// Host-side token sampling from raw logit scores.
///
/// Deterministic (greedy) when `temperature == 0.0` or `top_k <= 1` — returns
/// the argmax index.  Otherwise applies temperature scaling, selects the top-k
/// candidates, runs softmax over those k values, and draws a categorical sample
/// using an internal xorshift64 PRNG (no external crate required).
pub fn execute_sampling(logits: &[f32], temperature: f32, top_k: usize) -> usize {
    if logits.is_empty() {
        return 0;
    }

    // Greedy (deterministic) fast path.
    if temperature == 0.0 || top_k <= 1 {
        return logits
            .iter()
            .enumerate()
            .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
            .map(|(i, _)| i)
            .unwrap_or(0);
    }

    // Temperature scaling.
    let mut scaled: Vec<(usize, f32)> = logits
        .iter()
        .enumerate()
        .map(|(i, &v)| (i, v / temperature))
        .collect();

    // Partial sort: keep only the top-k entries (descending by score).
    let k = top_k.min(logits.len()).max(1);
    scaled.sort_unstable_by(|(_, a), (_, b)| b.partial_cmp(a).unwrap_or(std::cmp::Ordering::Equal));
    scaled.truncate(k);

    // Numerically-stable softmax over the top-k scores.
    let max_val = scaled
        .iter()
        .map(|(_, v)| *v)
        .fold(f32::NEG_INFINITY, f32::max);
    let mut expd: Vec<f32> = scaled.iter().map(|(_, v)| (*v - max_val).exp()).collect();
    let sum: f32 = expd.iter().sum();
    if sum > 0.0 {
        for e in expd.iter_mut() {
            *e /= sum;
        }
    }

    // Categorical sample via a module-level xorshift64 PRNG (no external dep).
    use std::sync::atomic::{AtomicU64, Ordering};
    static PRNG: AtomicU64 = AtomicU64::new(0x853c49e6748fea9b);
    let u = {
        let mut x = PRNG.load(Ordering::Relaxed);
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        PRNG.store(x, Ordering::Relaxed);
        (x as f64 / u64::MAX as f64) as f32
    };

    let mut cumsum = 0.0f32;
    for (i, p) in expd.iter().enumerate() {
        cumsum += p;
        if u <= cumsum || i + 1 == k {
            return scaled[i].0;
        }
    }
    scaled[0].0
}

/// xorshift64 PRNG — returns a uniform float in (0, 1].
fn xorshift64(state: &mut u64) -> f32 {
    let mut x = *state;
    x ^= x << 13;
    x ^= x >> 7;
    x ^= x << 17;
    *state = x;
    // Map to (0, 1] by dividing by 2^64.
    (x as f64 / u64::MAX as f64) as f32
}

/// Return a new `Vec<f32>` of exactly `target_len` elements from `src`,
/// padding with zeros if `src` is shorter.
#[allow(dead_code)]
fn pad_to_len(src: &[f32], target_len: usize) -> Vec<f32> {
    let mut out = vec![0.0f32; target_len];
    let copy = src.len().min(target_len);
    out[..copy].copy_from_slice(&src[..copy]);
    out
}

/// Copy GpuBuffer contents to a `Vec<f32>`.
fn buf_to_vec(buf: &GpuBuffer<f32>) -> Vec<f32> {
    let n = buf.num_elements();
    let mut v = vec![0.0f32; n];
    let _ = buf.copy_to_host(&mut v);
    v
}

/// Create a `GpuBuffer<f32>` of shape `[rows, cols]` from a `Vec<f32>`.
fn vec_to_buf(data: Vec<f32>, rows: usize, cols: usize) -> TptrResult<GpuBuffer<f32>> {
    let mut buf = GpuBuffer::<f32>::new(Shape::dim2(rows, cols), DType::F32, BufferFlags::STORAGE)
        .map_err(|e| TptrError::new(ErrorCode::AllocationFailure, e.to_string()))?;
    let n = (rows * cols).min(data.len());
    let mut padded = vec![0.0f32; rows * cols];
    padded[..n].copy_from_slice(&data[..n]);
    buf.copy_from_host(&padded)
        .map_err(|e| TptrError::new(ErrorCode::AllocationFailure, e.to_string()))?;
    Ok(buf)
}

/// Elementwise addition of two `[1, dim]` buffers, host-side.
fn elementwise_add_2d(
    a: &GpuBuffer<f32>,
    b: &GpuBuffer<f32>,
    dim: usize,
) -> TptrResult<GpuBuffer<f32>> {
    let mut va = vec![0.0f32; dim];
    let mut vb = vec![0.0f32; dim];
    let _ = a.copy_to_host(&mut va);
    let bn = vb.len().min(b.num_elements());
    let _ = b.copy_to_host(&mut vb[..bn]);
    for (x, y) in va.iter_mut().zip(vb.iter()) {
        *x += y;
    }
    vec_to_buf(va, 1, dim)
}

/// SwiGLU activation: result[i] = silu(gate[i]) * up[i].
/// Both `gate` and `up` are `[1, ffn_dim]` buffers.
fn swiglu_host(
    gate: &GpuBuffer<f32>,
    up: &GpuBuffer<f32>,
    ffn_dim: usize,
) -> TptrResult<GpuBuffer<f32>> {
    let mut g = vec![0.0f32; ffn_dim];
    let mut u = vec![0.0f32; ffn_dim];
    let gn = g.len().min(gate.num_elements());
    let _ = gate.copy_to_host(&mut g[..gn]);
    let un = u.len().min(up.num_elements());
    let _ = up.copy_to_host(&mut u[..un]);
    for (gi, ui) in g.iter_mut().zip(u.iter()) {
        let silu = *gi / (1.0 + (-*gi).exp()); // silu(x) = x * sigmoid(x)
        *gi = silu * ui;
    }
    vec_to_buf(g, 1, ffn_dim)
}

/// Tied lm_head: compute logits as hidden @ embed_table^T (host-side).
/// `hidden` is [1, hidden_dim]; `embed_table` is [vocab_size, hidden_dim].
/// Result is [1, vocab_size].
fn tied_lm_head_host(
    hidden: &GpuBuffer<f32>,
    embed_table: &GpuBuffer<f32>,
    hidden_dim: usize,
    vocab_size: usize,
) -> TptrResult<GpuBuffer<f32>> {
    let mut h = vec![0.0f32; hidden_dim];
    let mut e = vec![0.0f32; vocab_size * hidden_dim];
    let hn = h.len().min(hidden.num_elements());
    let _ = hidden.copy_to_host(&mut h[..hn]);
    let en = e.len().min(embed_table.num_elements());
    let _ = embed_table.copy_to_host(&mut e[..en]);

    let mut logits = vec![0.0f32; vocab_size];
    for v in 0..vocab_size {
        let row = &e[v * hidden_dim..(v + 1) * hidden_dim];
        logits[v] = h.iter().zip(row.iter()).map(|(a, b)| a * b).sum();
    }
    vec_to_buf(logits, 1, vocab_size)
}

/// Greedy sampling: returns the index of the maximum probability.
fn sample_argmax(probs: &GpuBuffer<f32>, vocab_size: usize) -> u32 {
    let mut p = vec![0.0f32; vocab_size];
    let pn = p.len().min(probs.num_elements());
    let _ = probs.copy_to_host(&mut p[..pn]);
    p.iter()
        .enumerate()
        .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
        .map(|(i, _)| i as u32)
        .unwrap_or(0)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    /// Write a minimal valid GGUF v2 file with the given KV metadata.
    fn write_gguf(path: &Path, kv: &[(&str, GgufKvVal)]) {
        let mut buf: Vec<u8> = Vec::new();
        buf.extend_from_slice(b"GGUF"); // magic
        buf.extend_from_slice(&2u32.to_le_bytes()); // version 2
        buf.extend_from_slice(&0u64.to_le_bytes()); // tensor_count
        buf.extend_from_slice(&(kv.len() as u64).to_le_bytes()); // kv_count
        for (key, val) in kv {
            let kb = key.as_bytes();
            buf.extend_from_slice(&(kb.len() as u64).to_le_bytes());
            buf.extend_from_slice(kb);
            match val {
                GgufKvVal::Str(s) => {
                    buf.extend_from_slice(&8u32.to_le_bytes()); // STRING
                    let sb = s.as_bytes();
                    buf.extend_from_slice(&(sb.len() as u64).to_le_bytes());
                    buf.extend_from_slice(sb);
                }
                GgufKvVal::U32(v) => {
                    buf.extend_from_slice(&4u32.to_le_bytes()); // UINT32
                    buf.extend_from_slice(&v.to_le_bytes());
                }
            }
        }
        fs::write(path, &buf).unwrap();
    }

    enum GgufKvVal {
        Str(String),
        U32(u32),
    }

    fn tmp(name: &str) -> PathBuf {
        let mut p = std::env::temp_dir();
        p.push(format!("tptr_infer_{}_{}", std::process::id(), name));
        p
    }

    // ----- GGUF parser tests -----

    // ----- TPTF parser tests -----

    fn write_tptf(path: &Path, arch: &str, num_layers: u32, per_layer_bits: &[u8]) {
        let mut buf = vec![0u8; 512];
        buf[0..4].copy_from_slice(b"TPTF");
        buf[4..8].copy_from_slice(&1u32.to_le_bytes()); // version
        buf[8..12].copy_from_slice(&0u32.to_le_bytes()); // flags
        let ab = arch.as_bytes();
        buf[12] = ab.len().min(63) as u8;
        buf[13..13 + ab.len().min(63)].copy_from_slice(&ab[..ab.len().min(63)]);
        buf[76..80].copy_from_slice(&64u32.to_le_bytes()); // context_len
        buf[80..84].copy_from_slice(&32000u32.to_le_bytes()); // vocab_size
        buf[84..88].copy_from_slice(&64u32.to_le_bytes()); // hidden_dim
        buf[88..92].copy_from_slice(&4u32.to_le_bytes()); // num_heads
        buf[92..96].copy_from_slice(&2u32.to_le_bytes()); // num_kv_heads
        buf[96..100].copy_from_slice(&128u32.to_le_bytes()); // ffn_dim
        buf[100..104].copy_from_slice(&num_layers.to_le_bytes());
        for (i, &b) in per_layer_bits.iter().enumerate().take(128) {
            buf[104 + i] = b;
        }
        fs::write(path, &buf).unwrap();
    }

    #[test]
    fn parse_tptf_header_basic() {
        let p = tmp("basic.tptf");
        write_tptf(&p, "llama3", 4, &[4, 4, 6, 8]);
        let info = parse_tptf_header(&p).unwrap();
        assert_eq!(info.arch, "llama3");
        assert_eq!(info.num_layers, 4);
        assert_eq!(info.per_layer_bits, vec![4, 4, 6, 8]);
        let _ = fs::remove_file(&p);
    }

    #[test]
    fn detect_format_tptf() {
        let p = tmp("detect.tptf");
        write_tptf(&p, "llama3", 2, &[]);
        assert_eq!(detect_format(&p), ModelFormat::Tptf);
        let _ = fs::remove_file(&p);
    }

    #[test]
    fn load_tptf_via_engine() {
        let p = tmp("engine.tptf");
        write_tptf(&p, "llama3", 2, &[4, 4]);
        let engine = GpuInferenceEngine::load(&p).unwrap();
        assert_eq!(engine.model_info().arch, "llama3");
        assert_eq!(engine.model_info().per_layer_bits, vec![4, 4]);
        let _ = fs::remove_file(&p);
    }

    #[test]
    fn parse_bad_magic_errors() {
        let p = tmp("bad_magic.gguf");
        fs::write(
            &p,
            b"NOTG\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
        )
        .unwrap();
        let err = parse_gguf_header(&p).unwrap_err();
        assert_eq!(err.code, ErrorCode::InvalidKernel);
        let _ = fs::remove_file(&p);
    }

    #[test]
    fn parse_missing_file_errors() {
        let err = parse_gguf_header(Path::new("/nonexistent/model.gguf")).unwrap_err();
        assert_eq!(err.code, ErrorCode::InvalidKernel);
    }

    #[test]
    fn parse_extracts_arch_and_dims() {
        let p = tmp("parse_arch.gguf");
        write_gguf(
            &p,
            &[
                ("general.architecture", GgufKvVal::Str("llama3".into())),
                ("llm.context_length", GgufKvVal::U32(8192)),
                ("llm.embedding_length", GgufKvVal::U32(4096)),
                ("llm.attention.head_count", GgufKvVal::U32(32)),
                ("llm.attention.head_count_kv", GgufKvVal::U32(8)),
                ("llm.feed_forward_length", GgufKvVal::U32(11008)),
                ("llm.block_count", GgufKvVal::U32(32)),
            ],
        );
        let info = parse_gguf_header(&p).unwrap();
        assert_eq!(info.arch, "llama3");
        assert_eq!(info.context_len, 8192);
        assert_eq!(info.hidden_dim, 4096);
        assert_eq!(info.num_heads, 32);
        assert_eq!(info.num_kv_heads, 8);
        assert_eq!(info.num_layers, 32);
        let _ = fs::remove_file(&p);
    }

    #[test]
    fn parse_qwen2_arch() {
        let p = tmp("qwen2.gguf");
        write_gguf(
            &p,
            &[
                ("general.architecture", GgufKvVal::Str("qwen2".into())),
                ("llm.context_length", GgufKvVal::U32(32768)),
                ("llm.embedding_length", GgufKvVal::U32(3584)),
                ("llm.attention.head_count", GgufKvVal::U32(28)),
                ("llm.attention.head_count_kv", GgufKvVal::U32(4)),
                ("llm.feed_forward_length", GgufKvVal::U32(18944)),
                ("llm.block_count", GgufKvVal::U32(28)),
            ],
        );
        let info = parse_gguf_header(&p).unwrap();
        assert_eq!(info.arch, "qwen2");
        assert_eq!(info.hidden_dim, 3584);
        assert_eq!(info.num_kv_heads, 4);
        let _ = fs::remove_file(&p);
    }

    // ----- Engine load + infer tests -----

    fn write_minimal_gguf(path: &Path, arch: &str) {
        write_gguf(
            path,
            &[
                ("general.architecture", GgufKvVal::Str(arch.into())),
                ("llm.context_length", GgufKvVal::U32(64)),
                ("llm.embedding_length", GgufKvVal::U32(64)),
                ("llm.attention.head_count", GgufKvVal::U32(4)),
                ("llm.attention.head_count_kv", GgufKvVal::U32(2)),
                ("llm.feed_forward_length", GgufKvVal::U32(128)),
                ("llm.block_count", GgufKvVal::U32(2)),
            ],
        );
    }

    #[test]
    fn load_llama3_succeeds() {
        let p = tmp("llama3_load.gguf");
        write_minimal_gguf(&p, "llama3");
        let engine = GpuInferenceEngine::load(&p).unwrap();
        assert_eq!(engine.model_info().arch, "llama3");
        let _ = fs::remove_file(&p);
    }

    #[test]
    fn load_qwen2_succeeds() {
        let p = tmp("qwen2_load.gguf");
        write_minimal_gguf(&p, "qwen2");
        let engine = GpuInferenceEngine::load(&p).unwrap();
        assert_eq!(engine.model_info().arch, "qwen2");
        let _ = fs::remove_file(&p);
    }

    #[test]
    fn load_unknown_arch_errors() {
        let p = tmp("gpt2_load.gguf");
        write_minimal_gguf(&p, "gpt2");
        let err = GpuInferenceEngine::load(&p).unwrap_err();
        assert_eq!(err.code, ErrorCode::UnsupportedFeature);
        let _ = fs::remove_file(&p);
    }

    #[test]
    fn infer_produces_max_new_tokens() {
        let p = tmp("infer_count.gguf");
        write_minimal_gguf(&p, "llama3");
        let mut engine = GpuInferenceEngine::load(&p).unwrap();
        let mut generated = Vec::new();
        engine
            .infer(&[1, 2, 3], 4, |tok| generated.push(tok))
            .unwrap();
        assert_eq!(generated.len(), 4);
        let _ = fs::remove_file(&p);
    }

    #[test]
    fn infer_empty_tokens_errors() {
        let p = tmp("infer_empty.gguf");
        write_minimal_gguf(&p, "llama3");
        let mut engine = GpuInferenceEngine::load(&p).unwrap();
        let err = engine.infer(&[], 4, |_| {}).unwrap_err();
        assert_eq!(err.code, ErrorCode::ArgumentMismatch);
        let _ = fs::remove_file(&p);
    }

    #[test]
    fn cancel_stops_generation() {
        let p = tmp("cancel_gen.gguf");
        write_minimal_gguf(&p, "llama3");
        let mut engine = GpuInferenceEngine::load(&p).unwrap();
        engine.cancel();
        let mut generated = Vec::new();
        engine
            .infer(&[1, 2, 3], 100, |tok| generated.push(tok))
            .unwrap();
        assert!(
            generated.is_empty(),
            "cancel before infer should produce no tokens"
        );
        let _ = fs::remove_file(&p);
    }

    #[test]
    fn infer_gemma2_succeeds() {
        let p = tmp("gemma2_infer.gguf");
        write_minimal_gguf(&p, "gemma2");
        let mut engine = GpuInferenceEngine::load(&p).unwrap();
        let mut generated = Vec::new();
        engine.infer(&[1], 2, |tok| generated.push(tok)).unwrap();
        assert_eq!(generated.len(), 2);
        let _ = fs::remove_file(&p);
    }

    // ----- TPTF tensor-loading roundtrip -----

    /// Write a TPTF block binary (matching TensorBlock::write_to from tpt-gpu-model-optimizer).
    #[allow(clippy::too_many_arguments)]
    fn append_tptf_tensor_block(
        data: &mut Vec<u8>,
        layer_idx: u32,
        name: &str,
        bits: u8,
        group_size: u32,
        rows: u32,
        cols: u32,
        weight_bytes: &[u8],
    ) {
        data.extend_from_slice(&layer_idx.to_le_bytes());
        let nb = name.as_bytes();
        data.push(nb.len().min(31) as u8);
        data.extend_from_slice(&nb[..nb.len().min(31)]);
        data.push(bits);
        data.extend_from_slice(&group_size.to_le_bytes());
        data.extend_from_slice(&rows.to_le_bytes());
        data.extend_from_slice(&cols.to_le_bytes());
        // weights
        data.extend_from_slice(&(weight_bytes.len() as u32).to_le_bytes());
        data.extend_from_slice(weight_bytes);
        // scales: 1 group, scale = 1.0
        data.extend_from_slice(&1u32.to_le_bytes());
        data.extend_from_slice(&1.0f32.to_le_bytes());
        // zero_points: 1 group, zp = 0
        data.extend_from_slice(&1u32.to_le_bytes());
        data.push(0u8);
        // pad absolute position to next 128-byte boundary
        while !data.len().is_multiple_of(128) {
            data.push(0u8);
        }
    }

    /// Build a minimal TPTF file containing 2 f32 tensor blocks of known values
    /// (bits=16 → raw f32 bytes, no quantization).
    fn write_tptf_with_tensors(path: &Path) {
        // Header: arch=llama3, hidden=4, ffn=8, heads=2, kv=1, layers=1, vocab=8
        let mut buf = vec![0u8; 512];
        buf[0..4].copy_from_slice(b"TPTF");
        buf[4..8].copy_from_slice(&1u32.to_le_bytes()); // version
        buf[8..12].copy_from_slice(&0u32.to_le_bytes()); // flags
        let ab = b"llama3";
        buf[12] = ab.len() as u8;
        buf[13..13 + ab.len()].copy_from_slice(ab);
        buf[76..80].copy_from_slice(&64u32.to_le_bytes()); // context_len
        buf[80..84].copy_from_slice(&8u32.to_le_bytes()); // vocab_size
        buf[84..88].copy_from_slice(&4u32.to_le_bytes()); // hidden_dim
        buf[88..92].copy_from_slice(&2u32.to_le_bytes()); // num_heads
        buf[92..96].copy_from_slice(&1u32.to_le_bytes()); // num_kv_heads
        buf[96..100].copy_from_slice(&8u32.to_le_bytes()); // ffn_dim
        buf[100..104].copy_from_slice(&1u32.to_le_bytes()); // num_layers = 1
                                                            // tensor_offset at byte 460 = 512 (start of tensor section)
        buf[460..468].copy_from_slice(&512u64.to_le_bytes());
        // tokenizer_offset = 0 (no tokenizer → read tensors until EOF)

        let mut data = buf;

        // Tensor 1: gate_proj for layer 0 — 32 elements (4 × 8), bits=16
        let gate_vals: Vec<f32> = (1u32..=32).map(|i| i as f32 * 0.1).collect();
        let gate_bytes: Vec<u8> = gate_vals.iter().flat_map(|v| v.to_le_bytes()).collect();
        append_tptf_tensor_block(&mut data, 0, "gate_proj", 16, 32, 4, 8, &gate_bytes);

        // Tensor 2: up_proj for layer 0 — 32 elements (4 × 8), bits=16
        let up_vals: Vec<f32> = (1u32..=32).map(|i| i as f32 * 0.2).collect();
        let up_bytes: Vec<u8> = up_vals.iter().flat_map(|v| v.to_le_bytes()).collect();
        append_tptf_tensor_block(&mut data, 0, "up_proj", 16, 32, 4, 8, &up_bytes);

        fs::write(path, &data).unwrap();
    }

    #[test]
    fn test_load_tptf_roundtrip() {
        let p = tmp("tptf_roundtrip.tptf");
        write_tptf_with_tensors(&p);

        let info = parse_tptf_header(&p).unwrap();
        assert_eq!(info.arch, "llama3");
        assert_eq!(info.num_layers, 1);
        assert_eq!(info.hidden_dim, 4);
        assert_eq!(info.ffn_dim, 8);

        // llama3 does not tie lm_head
        let weights = ModelWeights::load_tptf(&p, &info, /*tied=*/ false).unwrap();

        // gate_proj[layer=0] should be (0.1, 0.2, ..., 3.2)
        let gate = buf_to_vec(&weights.layers[0].gate_proj);
        assert_eq!(gate.len(), 4 * 8, "gate_proj shape mismatch");
        for (i, &v) in gate.iter().enumerate() {
            let expected = (i + 1) as f32 * 0.1;
            assert!(
                (v - expected).abs() < 1e-5,
                "gate_proj[{}]: expected {:.4}, got {:.4}",
                i,
                expected,
                v
            );
        }

        // up_proj[layer=0] should be (0.2, 0.4, ..., 6.4)
        let up = buf_to_vec(&weights.layers[0].up_proj);
        assert_eq!(up.len(), 4 * 8, "up_proj shape mismatch");
        for (i, &v) in up.iter().enumerate() {
            let expected = (i + 1) as f32 * 0.2;
            assert!(
                (v - expected).abs() < 1e-5,
                "up_proj[{}]: expected {:.4}, got {:.4}",
                i,
                expected,
                v
            );
        }

        let _ = fs::remove_file(&p);
    }

    // ----- execute_sampling tests -----

    #[test]
    fn test_sampling_temperature_zero_is_argmax() {
        // With temperature=0, execute_sampling must return the argmax index
        // regardless of the values of the other logits.
        let logits = vec![0.1f32, 0.5, 0.9, 0.3, 0.2];
        let idx = execute_sampling(&logits, 0.0, 5);
        assert_eq!(
            idx, 2,
            "argmax of [0.1,0.5,0.9,0.3,0.2] should be 2, got {}",
            idx
        );

        // Also verify with a negative max-at-zero case.
        let logits2 = vec![10.0f32, 1.0, 2.0];
        let idx2 = execute_sampling(&logits2, 0.0, 3);
        assert_eq!(idx2, 0, "argmax of [10,1,2] should be 0, got {}", idx2);
    }

    #[test]
    fn test_sampling_topk_one_is_argmax() {
        // With top_k=1, only the highest-logit token can be sampled — the result
        // is always the argmax regardless of the temperature value.
        let logits = vec![0.1f32, 0.8, 0.3, 0.6];
        let idx = execute_sampling(&logits, 1.0, 1);
        assert_eq!(idx, 1, "top_k=1 should return argmax (1), got {}", idx);

        let logits2 = vec![3.0f32, 1.0, 2.0, 5.0, 4.0];
        let idx2 = execute_sampling(&logits2, 2.0, 1);
        assert_eq!(idx2, 3, "top_k=1 should return argmax (3), got {}", idx2);
    }
}