llama-cpp-sys-4 0.8.0

Low Level Bindings to llama.cpp
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
#include "llama.h"
#include "../src/llama-ext.h"

#include "arg.h"
#include "common.h"
#include "gguf.h"
#include "imatrix-loader.h"
#include "log.h"
#include "speculative.h"

#include <chrono>
#include <climits>
#include <clocale>
#include <cmath>
#include <cstring>
#include <fstream>
#include <mutex>
#include <set>
#include <thread>
#include <unordered_map>

#if defined(_MSC_VER)
#pragma warning(disable: 4244 4267) // possible loss of data
#endif

static void print_usage(int, char ** argv) {
    LOG("\nexample usage:\n");
    LOG("\n    %s \\\n"
            "       -m model.gguf -f some-text.txt [-o imatrix.gguf] [--output-format {gguf,dat}] [--no-ppl] \\\n"
            "       [--process-output] [--nextn] [--model-draft draft.gguf] [--chunk 123] [--save-frequency 0] \\\n"
            "       [--output-frequency 10] [--in-file imatrix-prev-0.gguf --in-file imatrix-prev-1.gguf ...] \\\n"
            "       [--parse-special] [--show-statistics] [...]\n" , argv[0]);
    LOG("\n");
}

struct Stats {
    std::vector<float>   activations;
    std::vector<float>   values;
    std::vector<int64_t> counts;
};

struct tensor_statistics {
    std::string tensor;
    bool legacy = true;
    double sum = 0.0f;
    float mean = 0.0f;
    int64_t elements = 0;
    float std_deviation = 0.0f;
    float skewness = 0.0f;
    float kurtosis = 0.0f;
    float gain = std::numeric_limits<float>::quiet_NaN();
    float entropy = 0.0f;
    float l2_dist = std::numeric_limits<float>::quiet_NaN();
    float cossim = std::numeric_limits<float>::quiet_NaN();
    float pearson = std::numeric_limits<float>::quiet_NaN();
    float covariance = std::numeric_limits<float>::quiet_NaN();
    double cov_sum = 0.0;
    double var_c_sum = 0.0;
    double var_p_sum = 0.0;
    double dot_prod = 0.0;
    double norm1_sq = 0.0;
    double norm2_sq = 0.0;
    double l2_dist_sq = 0.0;
    double sum_prev = 0.0;
    int64_t elements_prev = 0;
    int64_t n_features = 0;
};

class IMatrixCollector {
public:
    IMatrixCollector() = default;
    void set_params(common_params params) { m_params = std::move(params); }
    bool collect_imatrix(struct ggml_tensor * t, bool ask, void * user_data);
    void save_imatrix_legacy(int32_t ncall = -1) const;
    void save_imatrix(int32_t n_chunk = -1) const;
    bool load_imatrix(const char * file_name);
    const std::unordered_map<std::string, Stats> & get_mstats() const { return m_stats; }
    void set_n_layer_nextn(int32_t n_layer_nextn) { m_n_layer_nextn = n_layer_nextn; }
    int32_t get_n_layer_nextn() const { return m_n_layer_nextn; }
private:
    std::unordered_map<std::string, Stats>  m_stats;
    common_params                           m_params;
    std::mutex                              m_mutex;
    std::vector<std::string>                m_datasets;
    int32_t                                 m_last_chunk = 0;
    int32_t                                 m_chunk_size = 0;
    int32_t                                 m_n_layer_nextn = 0;
    std::vector<char>                       m_src1_data;
    std::vector<char>                       m_ids; // the expert ids from ggml_mul_mat_id
    int32_t e_chunk_size() const {
        return m_chunk_size > 0 ? m_chunk_size : m_params.n_ctx / m_params.n_parallel;
    }
};

// remove any prefix and suffixes from the name
// CUDA0#blk.0.attn_k.weight#0 => blk.0.attn_k.weight
static std::string filter_tensor_name(const char * name) {
    std::string wname;
    const char * p = strchr(name, '#');
    if (p != NULL) {
        p = p + 1;
        const char * q = strchr(p, '#');
        if (q != NULL) {
            wname = std::string(p, q - p);
        } else {
            wname = p;
        }
    } else {
        wname = name;
    }
    return wname;
}

static void process_tensor_name(const std::string & input, std::string & layer, std::string & tensor) {
    layer.clear();
    tensor.clear();

    std::vector<std::string> name;
    std::istringstream stream(input);
    std::string item;

    while (std::getline(stream, item, '.')) {
        name.push_back(item);
    }
    for (size_t i = 0; i < name.size(); ++i) {
        if (name[i] == "blk" && i + 1 < name.size()) {
            layer = name[i + 1];
            break;
        }
    }
    for (size_t i = 0; i < name.size(); ++i) {
        if (name[i] == "weight" && i > 0) {
            for (size_t j = 0; j < name.size(); ++j) {
                if (name[j] == "blk") {
                    j += name.size() > 4 ? 1 : 2;
                    continue;
                }
                if (j == i) { break; }
                if (!tensor.empty()) { tensor += "."; }
                tensor += name[j];
            }
            break;
        }
    }

    if (tensor.empty()) { tensor = input; }
    if (layer.empty()) { layer = "-"; }
}

static std::vector<float> compute_tensor_averages(const Stats & tstats, bool use_activations) {
    if (tstats.counts.empty()) { return {}; }

    const size_t n_mat = tstats.counts.size();
    const size_t len = use_activations ? tstats.activations.size() : tstats.values.size();
    if (len == 0 || n_mat == 0 || len % n_mat != 0) { return {}; }

    const size_t row = len / n_mat;
    std::vector<float> vec(len, std::numeric_limits<float>::quiet_NaN());

    bool has_valid = false;
    for (size_t m = 0; m < n_mat; ++m) {
        const auto c = (float) tstats.counts[m];
        const size_t off = m * row;

        if (c <= 0.0f) { continue; }

        has_valid = true;
        const float scale = 1.0f / c;
        const float * src = use_activations ? &tstats.activations[off] : &tstats.values[off];
        float * dst = & vec[off];

        for (size_t j = 0; j < row; ++j) { dst[j] = src[j] * scale; }
    }

    if (!has_valid) { return {}; }

    return vec;
}

static bool compute_vector_statistics(std::vector<tensor_statistics> & tstats, const std::string & name, const Stats & e) {
    constexpr auto fnan = std::numeric_limits<float>::quiet_NaN();
    const bool legacy = e.activations.empty();
    const size_t n_mat = e.counts.size();
    const size_t len = legacy ? e.values.size() : e.activations.size();

    if (n_mat == 0 || len == 0 || len % n_mat != 0) {
        LOG_ERR("%s: data size mismatch or empty for tensor %s\n", __func__, name.c_str());
        return false;
    }
    if (!legacy && e.values.size() != len) {
        LOG_ERR("%s: activations/values size mismatch for %s\n", __func__, name.c_str());
        return false;
    }

    const size_t row_size = len / n_mat;
    double sum = 0.0;
    double mean = 0.0;
    double sum_sq_diff = 0.0;
    double sum_cu_diff = 0.0;
    double sum_qd_diff = 0.0;
    double sum_energy = 0.0;
    size_t valid_n = 0;

    // Mean
    for (size_t i = 0; i < n_mat; ++i) {
        const auto c = (float)e.counts[i];
        if (c <= 0.0f) { continue; }

        const double inv_c = 1.0 / (double)c;
        const size_t off = i * row_size;

        for (size_t j = 0; j < row_size; ++j) {
            const double v_act = legacy ? 0.0 : (double)e.activations[off + j] * inv_c;
            const double v_val = (double)e.values[off + j] * inv_c;
            const double v = legacy ? v_val : v_act; // Use activation average for non-legacy
            if (!std::isfinite(v) || !std::isfinite(v_val)) { continue; }

            sum += v_val;
            valid_n++;
            const double delta = v - mean;
            mean += delta / (double)valid_n;

            if (v_val > 0.0) { sum_energy += v_val; }
        }
    }

    if (valid_n == 0) { return false; }

    float std_deviation = 0.0f;
    double entropy = 0.0;

    // Std Dev, Skew, Kurtosis, Entropy
    const double inv_sum_energy = sum_energy > 0.0 ? 1.0 / sum_energy : 0.0;
    const double log2_inv = 1.0 / std::log(2.0);

    for (size_t i = 0; i < n_mat; ++i) {
        const auto c = (float)e.counts[i];
        if (c <= 0.0f) { continue; }
        const double inv_c = 1.0 / (double)c;
        const size_t off = i * row_size;

        for (size_t j = 0; j < row_size; ++j) {
            const double v_act = legacy ? 0.0 : (double)e.activations[off + j] * inv_c;
            const double v_val = (double)e.values[off + j] * inv_c;
            const double v = legacy ? v_val : v_act;
            if (!std::isfinite(v) || !std::isfinite(v_val)) { continue; }
            const double diff = v - mean;

            sum_sq_diff += diff * diff;
            sum_cu_diff += diff * diff * diff;
            sum_qd_diff += diff * diff * diff * diff;

            // Entropy (Distribution of Energy)
            if (inv_sum_energy > 0.0) {
                const double v_energy = (double)e.values[off + j] * inv_c;
                const double p = std::max(0.0, v_energy) * inv_sum_energy;
                if (p > 1e-10) { entropy -= p * std::log(p) * log2_inv; }
            }
        }
    }

    const double variance = valid_n > 1 ? sum_sq_diff / (double)valid_n : 0.0;
    std_deviation = std::sqrt((float)std::max(variance, 0.0));
    float skewness = 0.0f;
    float kurtosis = 0.0f;
    if (std_deviation > 1e-10f) {
        const double m2 = sum_sq_diff / (double)valid_n;
        skewness = (float)(sum_cu_diff / (double)valid_n / (m2 * std::sqrt(m2)));
        kurtosis = (float)(sum_qd_diff / (double)valid_n / (m2 * m2) - 3.0);
    }

    auto & ts = tstats.emplace_back();
    ts.tensor = name;
    ts.legacy = legacy;
    ts.sum = sum;
    ts.mean = (float)mean;
    ts.elements = (int64_t)valid_n;
    ts.std_deviation = std_deviation;
    ts.skewness = skewness;
    ts.kurtosis = kurtosis;
    ts.gain = fnan;
    ts.entropy = (float)entropy;
    ts.l2_dist = fnan;
    ts.cossim = fnan;
    ts.pearson = fnan;
    ts.covariance = fnan;

    return true;
}

static int nextn_layer_start(const std::vector<tensor_statistics> & tstats, int32_t n_layer_nextn) {
    int max_blk = -1;
    int first   = INT_MAX;

    for (const auto & ts : tstats) {
        std::string layer_str;
        std::string name;
        process_tensor_name(ts.tensor, layer_str, name);

        int blk = -1;
        try { blk = std::stoi(layer_str); } catch (...) { continue; }

        max_blk = std::max(max_blk, blk);
        if (name.rfind("nextn.", 0) == 0) { first = std::min(first, blk); }
    }

    if (n_layer_nextn > 0 && max_blk >= 0) { return std::max(0, max_blk + 1 - n_layer_nextn); }

    return first;
}

static std::string layer_label(int blk, int nextn_start) {
    if (blk < 0 || blk == INT_MAX) { return "-"; }
    if (blk >= nextn_start) { return "mtp" + std::to_string(blk - nextn_start); }

    return std::to_string(blk);
}

static void compute_tensor_statistics(std::vector<tensor_statistics> & tstats, const std::unordered_map<std::string, Stats> & mstats, int nextn_start) {
    constexpr auto fnan = std::numeric_limits<float>::quiet_NaN();
    std::unordered_map<std::string, size_t> tensor_map;
    tensor_map.reserve(tstats.size());
    for (size_t i = 0; i < tstats.size(); ++i) { tensor_map[tstats[i].tensor] = i; }

    for (auto & ts : tstats) {
        std::string layer_str;
        std::string dummy_tensor;
        process_tensor_name(ts.tensor, layer_str, dummy_tensor);

        int blk = -1;
        try { blk = std::stoi(layer_str); } catch (...) { continue; }
        if (blk <= 0) { continue; }
        if (blk == nextn_start) { continue; }

        const int blk_first = blk > nextn_start ? nextn_start : 0;
        const size_t blk_start_pos = ts.tensor.find("blk." + layer_str);
        if (blk_start_pos == std::string::npos) { continue; }

        std::string tname = ts.tensor;
        auto it = tensor_map.end();
        for (int prev = blk - 1; prev >= blk_first && it == tensor_map.end(); --prev) {
            tname = ts.tensor;
            tname.replace(blk_start_pos, layer_str.length() + 4, "blk." + std::to_string(prev));
            it = tensor_map.find(tname);
        }

        if (it == tensor_map.end()) {
            LOG_WRN("%s: no preceding-layer tensor for '%s'\n", __func__, ts.tensor.c_str());
            continue;
        }

        const auto & prev_ts = tstats[it->second];
        const auto curr_e = mstats.find(ts.tensor);
        const auto prev_e = mstats.find(prev_ts.tensor);
        if (curr_e == mstats.end() || prev_e == mstats.end()) { continue; }

        // one side may not have no activation sums so compare both on the energy
        const bool use_activations = !ts.legacy && !prev_ts.legacy;
        const auto curr_avg = compute_tensor_averages(curr_e->second, use_activations);
        const auto prev_avg = compute_tensor_averages(prev_e->second, use_activations);

        if (curr_avg.empty() || curr_avg.size() != prev_avg.size()) { continue; }

        double dot_prod = 0.0;
        double norm1_sq = 0.0;
        double norm2_sq = 0.0;
        double l2_dist_sq = 0.0;
        double sum_c = 0.0;
        double sum_p = 0.0;
        const size_t n = curr_avg.size();
        size_t valid_n = 0;

        // Sums for Means
        for (size_t i = 0; i < n; ++i) {
            const double c_val = curr_avg[i];
            const double p_val = prev_avg[i];
            if (std::isfinite(c_val) && std::isfinite(p_val)) {
                sum_c += c_val;
                sum_p += p_val;
                valid_n++;
            }
        }

        if (valid_n == 0) { continue; }
        const double mean_c = sum_c / valid_n;
        const double mean_p = sum_p / valid_n;

        double cov_sum = 0.0;
        double var_c_sum = 0.0;
        double var_p_sum = 0.0;

        // Metrics
        for (size_t i = 0; i < n; ++i) {
            const double c_val = curr_avg[i];
            const double p_val = prev_avg[i];
            if (!std::isfinite(c_val) || !std::isfinite(p_val)) { continue; }

            // Cosine Similarity & L2 Distance
            dot_prod += c_val * p_val;
            norm1_sq += c_val * c_val;
            norm2_sq += p_val * p_val;
            const double diff = c_val - p_val;
            l2_dist_sq += diff * diff;

            // Pearson (Centered stats)
            const double dc = c_val - mean_c;
            const double dp = p_val - mean_p;
            cov_sum += dc * dp;
            var_c_sum += dc * dc;
            var_p_sum += dp * dp;
        }

        ts.n_features = (int64_t)valid_n;
        ts.dot_prod = dot_prod;
        ts.norm1_sq = norm1_sq;
        ts.norm2_sq = norm2_sq;
        ts.cov_sum = cov_sum;
        ts.var_c_sum = var_c_sum;
        ts.var_p_sum = var_p_sum;
        ts.l2_dist_sq = l2_dist_sq;
        ts.l2_dist = (float)std::sqrt(l2_dist_sq);

        if (valid_n > 1) {
            ts.covariance = (float)(cov_sum / (double)valid_n);
        }

        if (norm1_sq > 0.0 && norm2_sq > 0.0) {
            ts.cossim = (float)(dot_prod / (std::sqrt(norm1_sq) * std::sqrt(norm2_sq)));
            ts.cossim = std::clamp(ts.cossim, -1.0f, 1.0f);
        } else {
            ts.cossim = (norm1_sq == 0.0 && norm2_sq == 0.0) ? fnan : 0.0f;
        }

        if (var_c_sum > 0.0 && var_p_sum > 0.0) {
            ts.pearson = (float)(cov_sum / (std::sqrt(var_c_sum) * std::sqrt(var_p_sum)));
            ts.pearson = std::clamp(ts.pearson, -1.0f, 1.0f);
        } else {
            ts.pearson = (var_c_sum == 0.0 && var_p_sum == 0.0) ? fnan : 0.0f;
        }

        if (prev_ts.sum > 1e-10f) {
            ts.gain = std::sqrt(ts.sum / ts.elements) / std::sqrt(prev_ts.sum / prev_ts.elements);
            ts.sum_prev = prev_ts.sum;
            ts.elements_prev = prev_ts.elements;
        } else {
            ts.gain = ts.sum <= 1e-10f ? 1.0f : fnan;
        }
    }
}

static void compute_layer_statistics(const std::vector<tensor_statistics> & tstats,
    std::map<int, float> & layer_cossim,
    std::map<int, float> & layer_l2_dist,
    std::map<int, float> & layer_pearson,
    std::map<int, float> & layer_covariance,
    std::map<int, float> & layer_gain
)
{
    struct layer_aggregation {
        double sum_dot_prod = 0.0;
        double sum_norm1_sq = 0.0;
        double sum_norm2_sq = 0.0;
        double sum_l2_dist_sq = 0.0;
        double sum_cov = 0.0;
        double sum_var_c = 0.0;
        double sum_var_p = 0.0;
        double sum_energy_curr = 0.0;
        double sum_energy_prev = 0.0;
        int64_t sum_elements_curr = 0;
        int64_t sum_elements_prev = 0;
        int64_t sum_n_features = 0;
        int n_tensors = 0;
    };

    constexpr auto fnan = std::numeric_limits<float>::quiet_NaN();
    std::map<int, layer_aggregation> laggr;

    for (const auto & ts : tstats) {
        std::string layer_str;
        std::string dummy;
        process_tensor_name(ts.tensor, layer_str, dummy);
        int blk = -1;
        try {
            blk = std::stoi(layer_str);
        } catch(...) {
            if (layer_str == "-") { blk = -1; }
        }

        if (blk <= 0) { continue; }

        if (ts.norm1_sq == 0.0 && ts.norm2_sq == 0.0 && ts.l2_dist_sq == 0.0) { continue; }
        auto & entry = laggr[blk];
        entry.sum_dot_prod += ts.dot_prod;
        entry.sum_norm1_sq += ts.norm1_sq;
        entry.sum_norm2_sq += ts.norm2_sq;
        entry.sum_l2_dist_sq += ts.l2_dist_sq;
        entry.sum_cov += ts.cov_sum;
        entry.sum_var_c += ts.var_c_sum;
        entry.sum_var_p += ts.var_p_sum;
        entry.n_tensors++;
        if (ts.n_features > 0) { entry.sum_n_features += ts.n_features; }

        // skip tensors with no match in a previous layer
        if (ts.elements_prev > 0) {
            entry.sum_energy_curr += ts.sum;
            entry.sum_energy_prev += ts.sum_prev;
            entry.sum_elements_curr += ts.elements;
            entry.sum_elements_prev += ts.elements_prev;
        }
    }

    for (const auto & [layer, agg] : laggr) {
        if (agg.n_tensors == 0) { continue; }

        float cossim = 0.0f;
        if (agg.sum_norm1_sq > 0.0 && agg.sum_norm2_sq > 0.0) {
            cossim = (float)(agg.sum_dot_prod / (std::sqrt(agg.sum_norm1_sq) * std::sqrt(agg.sum_norm2_sq)));
            cossim = std::clamp(cossim, -1.0f, 1.0f);
        } else if (agg.sum_norm1_sq == 0.0 && agg.sum_norm2_sq == 0.0) {
            cossim = fnan;
        }

        float gain = fnan;
        if (agg.sum_elements_curr > 0 && agg.sum_elements_prev > 0 && agg.sum_energy_prev > 0.0) {
            const double rms_curr = std::sqrt(agg.sum_energy_curr / (double)agg.sum_elements_curr);
            const double rms_prev = std::sqrt(agg.sum_energy_prev / (double)agg.sum_elements_prev);
            gain = (float)(rms_curr / rms_prev);
        }

        layer_cossim[layer] = cossim;
        layer_l2_dist[layer] = (float)std::sqrt(agg.sum_l2_dist_sq);
        layer_gain[layer] = gain;

        if (agg.sum_n_features > 0) { layer_covariance[layer] = (float)(agg.sum_cov / (double)agg.sum_n_features); }
        else { layer_covariance[layer] = fnan; }

        if (agg.sum_var_c > 0.0 && agg.sum_var_p > 0.0) {
            auto pearson = (float)(agg.sum_cov / (std::sqrt(agg.sum_var_c) * std::sqrt(agg.sum_var_p)));
            layer_pearson[layer] = std::clamp(pearson, -1.0f, 1.0f);
        } else if (agg.sum_var_c == 0.0 && agg.sum_var_p == 0.0) {
            layer_pearson[layer] = fnan;
        } else {
            layer_pearson[layer] = 0.0f;
        }
    }
}

static bool all_finite(const float * v, size_t n) {
    for (size_t i = 0; i < n; ++i) {
        if (!std::isfinite(v[i])) { return false; }
    }

    return true;
}

// Round to nearest instead of truncating
static int32_t rows_to_chunks(int64_t n_rows, int32_t chunk_size) {
    return (int32_t) ((n_rows + chunk_size / 2) / chunk_size);
}

bool IMatrixCollector::collect_imatrix(struct ggml_tensor * t, bool ask, void * user_data) {
    GGML_UNUSED(user_data);

    const struct ggml_tensor * src0 = t->src[0];
    const struct ggml_tensor * src1 = t->src[1];
    std::string wname = filter_tensor_name(src0->name);

    const int32_t chunk_size = m_params.n_ctx / m_params.n_parallel;

    // when ask is true, the scheduler wants to know if we are interested in data from this tensor
    // if we return true, a follow-up call will be made with ask=false in which we can do the actual collection
    if (ask) {
        if (t->op == GGML_OP_MUL_MAT_ID) { return true; } // collect all indirect matrix multiplications
        if (t->op != GGML_OP_MUL_MAT) { return false; }
        // why are small batches ignored (<16 tokens)?
        if (src1->ne[1] < 16 || src1->type != GGML_TYPE_F32) { return false; }
        const bool is_output = wname == "output.weight" || wname == "token_embd.weight" || wname == "nextn.post_projection.weight";
        const bool is_nextn  = wname == "nextn.pre_projection.weight";
        if (!(wname.substr(0, 4) == "blk." || (m_params.process_output && is_output) || (m_params.load_mtp && is_nextn))) { return false; }

        return true;
    }

    std::lock_guard<std::mutex> lock(m_mutex);

    // copy the data from the GPU memory if needed
    const bool is_host = ggml_backend_buffer_is_host(src1->buffer);

    if (!is_host) {
        const size_t src1_nbytes = ggml_nbytes(src1);
        m_src1_data.resize(src1_nbytes);
        ggml_backend_tensor_get(src1, m_src1_data.data(), 0, src1_nbytes);
    }

    const char * data = is_host ? (const char *) src1->data : m_src1_data.data();
    GGML_ASSERT(src1->nb[0] == ggml_element_size(src1));

    // this has been adapted to the new format of storing merged experts in a single 3d tensor
    // ref: https://github.com/ggml-org/llama.cpp/pull/6387
    if (t->op == GGML_OP_MUL_MAT_ID) {
        //   ids  -> [n_experts_used, n_tokens]
        //   src1 -> [cols, n_expert_used, n_tokens]
        const ggml_tensor * ids = t->src[2];
        const int64_t n_as = src0->ne[2];
        const int64_t n_ids = ids->ne[0];

        // the top-k selected expert ids are stored in the ids tensor
        // for simplicity, always copy ids to host, because it is small
        // take into account that ids is not contiguous!

        GGML_ASSERT(ids->ne[1] == src1->ne[2]);

        // the extra dimension would need to be stored somewhere to be reflected in the imatrix file
        if (ggml_nrows(src1) != src1->ne[1] * src1->ne[2]) {
            LOG_ERR("%s: tensor has more than 3 dimensions: %s", __func__, wname.c_str());
            GGML_ASSERT(false);
        }

        m_ids.resize(ggml_nbytes(ids));
        ggml_backend_tensor_get(ids, m_ids.data(), 0, ggml_nbytes(ids));

        auto & e = m_stats[wname];

        if (e.counts.size() == 1 && n_as > 1) {
            // broadcast, when loading an old imatrix
            e.counts.resize(n_as, e.counts[0]);
        }
        if (e.values.empty()) {
            e.activations.resize(src1->ne[0]*n_as, 0);
            e.values.resize(src1->ne[0]*n_as, 0);
            e.counts.resize(n_as, 0);
        }
        else if (e.values.size() != (size_t)src1->ne[0]*n_as) {
            LOG_ERR("%s: inconsistent size for %s (%d vs %d)\n", __func__, wname.c_str(), (int)e.values.size(), (int)(src1->ne[0]*n_as));
            exit(1); //GGML_ABORT("fatal error");
        }
        else if (e.counts.size() != (size_t)n_as) {
            LOG_ERR("%s: inconsistent expert count for %s (%d vs %d)\n", __func__, wname.c_str(), (int)e.counts.size(), (int)n_as);
            exit(1); //GGML_ABORT("fatal error");
        }
        LOG_DBGV(2, "%s[%d]: %32s, %s, %5d x %5d, %d\n", __func__, m_last_chunk, wname.c_str(), ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[2], (int)src1->type);

        const int64_t ne0 = src1->ne[0];
        const int64_t n_tokens = src1->ne[2];
        const bool has_act = !e.activations.empty();

        // single pass over the routing ids
        std::vector<uint8_t> touched(n_as, 0);
        for (int64_t idx = 0; idx < n_ids; ++idx) {
            for (int64_t row = 0; row < n_tokens; ++row) {
                const int32_t ex = *(const int32_t *) (m_ids.data() + row * ids->nb[1] + idx * ids->nb[0]);
                GGML_ASSERT(ex >= 0 && ex < n_as);  // sanity check
                const int64_t i11 = idx % src1->ne[1];
                const float * x = (const float *) (data + i11 * src1->nb[1] + row * src1->nb[2]);
                float * acc = e.values.data() + ex * ne0;
                float * act = has_act ? e.activations.data() + ex * ne0 : nullptr; // legacy imatrix tensors do not have activation sums

                e.counts[ex]++;
                touched[ex] = 1;
                for (int64_t j = 0; j < ne0; ++j) { acc[j] += x[j] * x[j]; }
                if (act) {
                    for (int64_t j = 0; j < ne0; ++j) { act[j] += x[j]; }
                }
            }
        }

        // check for non-finite values, only checking experts that were routed to and touched
        for (int64_t ex = 0; ex < n_as; ++ex) {
            if (touched[ex] && !all_finite(e.values.data() + ex * ne0, ne0)) {
                LOG_ERR("%s: non-finite values detected in %s\n", __func__, wname.c_str());
                exit(1);
            }
        }

        for (int64_t ex = 0; ex < n_as; ++ex) {
            const int32_t n_chunk = rows_to_chunks(e.counts[ex], chunk_size);
            if (n_chunk > m_last_chunk) {
                const int32_t chunk_step = n_chunk - m_last_chunk;
                m_last_chunk = n_chunk;
                if ((m_last_chunk % m_params.n_out_freq) / chunk_step == 0) {
                    save_imatrix();
                }
                if (m_params.n_save_freq > 0 && (m_last_chunk % m_params.n_save_freq) / chunk_step == 0) {
                    save_imatrix(m_last_chunk);
                }
            }
        }
    } else {
        auto & e = m_stats[wname];
        const int64_t n_mat = src0->ne[2] * src0->ne[3];

        // use a single count per dense tensor
        // (necessary when merging older GGUF-imatrix files with 3d tensors)
        if (e.counts.size() > 1) {
            bool all_equal = true;
            for (size_t i = 1; i < e.counts.size(); ++i) {
                if (e.counts[0] != e.counts[i]) {
                    all_equal = false;
                    break;
                }
            }
            if (all_equal) {
                e.counts.resize(1);
            }
        }
        if (e.values.empty()) {
            e.activations.resize(src1->ne[0] * n_mat, 0);
            e.values.resize(src1->ne[0] * n_mat, 0);
            e.counts.resize(1, 0);
        }
        else if (e.values.size() != (size_t)(src1->ne[0] * n_mat)) {
            LOG_ERR("%s: inconsistent size for %s (%d vs %d)\n",
                __func__, wname.c_str(), (int)e.values.size(), (int)(src1->ne[0] * n_mat));
            exit(1); //GGML_ABORT("fatal error");
        }
        LOG_DBGV(2, "%s[%d]: %32s, %s, %5d x %5d x %5d, %d\n",
            __func__, m_last_chunk, wname.c_str(), ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[1], (int)src1->ne[2], (int)src1->type);

        const int64_t ne0 = src1->ne[0];
        const bool has_act = !e.activations.empty();
        for (int64_t i3 = 0; i3 < src1->ne[3]; ++i3) {
            for (int64_t i2 = 0; i2 < src1->ne[2]; ++i2) {
                // handle 3D+ tensors, but flatten 3D+ activations when model tensor is 2D
                const int64_t mat_id = (i3 % src0->ne[3]) * src0->ne[2] + (i2 % src0->ne[2]);
                float * acc = e.values.data() + mat_id * ne0;
                float * act = has_act ? e.activations.data() + mat_id * ne0 : nullptr;
                for (int64_t row = 0; row < src1->ne[1]; ++row) {
                    const float * x = (const float *) (data + row * src1->nb[1] + i2 * src1->nb[2] + i3 * src1->nb[3]);
                    for (int64_t j = 0; j < ne0; ++j) { acc[j] += x[j] * x[j]; }
                    if (act) {
                        for (int64_t j = 0; j < ne0; ++j) { act[j] += x[j]; }
                    }
                }
            }
        }

        // check for non-finite values
        if (!all_finite(e.values.data(), e.values.size())) {
            LOG_ERR("%s: non-finite values detected in %s\n", __func__, wname.c_str());
            exit(1);
        }
        // only 1 count in practice, except when a tensor is used for both MUL_MAT_ID and MUL_MAT
        for (size_t i = 0; i < e.counts.size(); ++i) {
            e.counts[i] += ggml_nrows(src1) / n_mat;
            const int32_t n_chunk = rows_to_chunks(e.counts[i], chunk_size);
            if (n_chunk > m_last_chunk) {
                const int32_t chunk_step = n_chunk - m_last_chunk;
                m_last_chunk = n_chunk;
                if ((m_last_chunk % m_params.n_out_freq) / chunk_step == 0) {
                    save_imatrix();
                }
                if (m_params.n_save_freq > 0 && (m_last_chunk % m_params.n_save_freq) / chunk_step == 0) {
                    save_imatrix(m_last_chunk);
                }
            }
        }
    }

    return true;
}

void IMatrixCollector::save_imatrix_legacy(int32_t ncall) const {
    auto fname = m_params.out_file;

    if (ncall > 0) {
        fname += ".at_";
        fname += std::to_string(ncall);
    }

    // warn when writing imatrix entries that do not have full data
    // this can happen with MoE models where some of the experts end up not being exercised by the provided training data

    int n_entries = 0;
    std::vector<std::string> to_store;

    bool is_first = true; // for printing
    for (const auto & kv : m_stats) {
        const int n_all = kv.second.counts.size();

        if (n_all == 0) {
            continue;
        }

        int n_zeros = 0;
        for (const int c : kv.second.counts) {
            if (c == 0) {
                n_zeros++;
            }
        }

        if (n_zeros != 0 && is_first) {
            LOG_INF("\n");
            is_first = false;
        }

        if (n_zeros == n_all) {
            LOG_WRN("%s: entry '%40s' has no data - skipping\n", __func__, kv.first.c_str());
            continue;
        }

        if (n_zeros > 0) {
            LOG_WRN("%s: entry '%40s' has partial data (%.2f%%)\n", __func__, kv.first.c_str(), 100.0f * (n_all - n_zeros) / n_all);
        }

        n_entries++;
        to_store.push_back(kv.first);
    }

    if (to_store.size() < m_stats.size()) {
        LOG_WRN("%s: storing only %zu out of %zu entries\n", __func__, to_store.size(), m_stats.size());
    }

    // deterministic tensor name order
    std::sort(to_store.begin(), to_store.end());

    const int32_t chunk_size = e_chunk_size();
    std::ofstream out(fname, std::ios::binary);
    out.write((const char *) &n_entries, sizeof(n_entries));
    for (const auto & name : to_store) {
        const auto & stat = m_stats.at(name);
        const int32_t len = name.size();
        out.write((const char *) &len, sizeof(len));
        out.write(name.c_str(), len);
        // ceiling division to avoid accidental zeros
        const int32_t ncall = (*std::max_element(stat.counts.begin(), stat.counts.end()) + (chunk_size - 1)) / chunk_size;
        out.write((const char *) &ncall, sizeof(ncall));
        const int32_t nval = stat.values.size();
        const int32_t nmat = stat.counts.size();
        out.write((const char *) &nval, sizeof(nval));
        if (nval > 0 && nmat > 0) {
            std::vector<float> tmp(nval);
            for (int32_t i = 0; i < nval; i++) {
                float count = static_cast<float>(stat.counts[i / (nval / nmat)]);
                float value = stat.values[i];
                if (count == 0.0f) {
                    // store 1 for partial data
                    value = 1.0f;
                    count = 1.0f;
                }
                tmp[i] = (value / count) * static_cast<float>(ncall);
            }
            out.write((const char *) tmp.data(), nval * sizeof(float));
        }
    }

    // Write the number of call the matrix was computed with
    out.write((const char *) &m_last_chunk, sizeof(m_last_chunk));

    // Write the input filename at the end of the file to later on specify it in quantize
    {
        const char * dataset_file = m_params.prompt_file.c_str();
        int32_t len = m_params.prompt_file.size();
        // When there is no prompt but there were other imatrix files loaded, use the last dataset
        if (m_params.prompt_file.empty() && !m_datasets.empty()) {
            const std::string & dataset_str = m_datasets[m_datasets.size() - 1];
            dataset_file = dataset_str.c_str();
            len = dataset_str.size();
        }
        out.write((const char *) &len, sizeof(len));
        out.write(dataset_file, len);
    }

    LOGV(1, "\n");
    LOG_DBGV(1, "%s: stored collected data after %d chunks in %s\n", __func__, m_last_chunk, fname.c_str());
}

void IMatrixCollector::save_imatrix(int32_t n_chunk) const {
    auto fname = m_params.out_file;
    int8_t use_legacy_format = m_params.imat_dat;

    if (use_legacy_format > 0) {
        this->save_imatrix_legacy(n_chunk);
        return;
    }
    // only warn when `--output-format gguf` is not specified
    if (use_legacy_format == 0 && !string_ends_with(fname, ".gguf")) {
        LOG_WRN("\n%s: saving imatrix using GGUF format with a different suffix than .gguf\n", __func__);
        LOG_WRN("%s: if you want the previous imatrix format, use --output-format dat\n", __func__);
    }

    if (n_chunk > 0) {
        fname += ".at_";
        fname += std::to_string(n_chunk);
    }

    // write imatrix entries even if they don't have full data. (can be corrected when reading)
    // this can happen with MoE models where some of the experts end up not being exercised by the provided training data

    std::vector<std::string> to_store;
    size_t data_size = 0;

    bool is_first = true; // for printing
    for (const auto & kv : m_stats) {
        const int n_all = kv.second.counts.size();

        int n_zeros = 0;
        for (const auto c : kv.second.counts) {
            if (c == 0) {
                n_zeros++;
            }
        }

        if (n_zeros != 0 && is_first) {
            LOG_INF("\n");
            is_first = false;
        }

        if (n_zeros > 0) {
            LOG_WRN("%s: entry '%40s' has partial data (%.2f%%)\n", __func__, kv.first.c_str(), 100.0f * (n_all - n_zeros) / n_all);
        }

        to_store.push_back(kv.first);
        data_size += GGML_PAD(ggml_tensor_overhead() + sizeof(float) * kv.second.activations.size(), GGML_MEM_ALIGN);
        data_size += GGML_PAD(ggml_tensor_overhead() + sizeof(float) * kv.second.values.size(), GGML_MEM_ALIGN);
        data_size += GGML_PAD(ggml_tensor_overhead() + sizeof(float) * kv.second.counts.size(), GGML_MEM_ALIGN);
        data_size += GGML_PAD(ggml_tensor_overhead() + sizeof(float) * 10, GGML_MEM_ALIGN);
    }

    // deterministic tensor name order
    std::sort(to_store.begin(), to_store.end());

    // Compute per-tensor statistics
    std::vector<tensor_statistics> tstats;
    tstats.reserve(m_stats.size());
    for (const auto & kv : m_stats) { compute_vector_statistics(tstats, kv.first, kv.second); }
    if (!tstats.empty()) { compute_tensor_statistics(tstats, m_stats, nextn_layer_start(tstats, m_n_layer_nextn)); }

    // index by tensor name
    std::unordered_map<std::string, const tensor_statistics *> tstat_index;
    tstat_index.reserve(tstats.size());
    for (const auto & ts : tstats) { tstat_index[ts.tensor] = &ts; }

    struct ggml_init_params params = {
        /* .mem_size   = */ data_size,
        /* .mem_buffer = */ NULL,
        /* .no_alloc   = */ false,
    };
    struct ggml_context * ctx = ggml_init(params);
    struct gguf_context * ctx_gguf = gguf_init_empty();

    {
        std::vector<const char *> datasets;
        datasets.reserve(m_datasets.size() + 1);
        for (size_t i = 0; i < m_datasets.size(); ++i) {
            datasets.push_back(m_datasets[i].c_str());
        }
        if (!m_params.prompt_file.empty()) {
            datasets.push_back(m_params.prompt_file.c_str());
        }

        gguf_set_val_str(ctx_gguf, "general.type", "imatrix");
        // Write the dataset paths
        gguf_set_arr_str(ctx_gguf, LLM_KV_IMATRIX_DATASETS, datasets.data(), datasets.size());
        // Write the number of chunks the matrix was computed with
        gguf_set_val_u32(ctx_gguf, LLM_KV_IMATRIX_CHUNK_COUNT, m_last_chunk);
        gguf_set_val_u32(ctx_gguf, LLM_KV_IMATRIX_CHUNK_SIZE, e_chunk_size());
        // Write how many of the top layers are NextN layers, so statistics can tell them apart
        if (m_n_layer_nextn > 0) { gguf_set_val_u32(ctx_gguf, LLM_KV_IMATRIX_N_LAYER_NEXTN, m_n_layer_nextn); }
        // Define the schema for the tensor statistics (for use in quantize.cpp)
        const char * stats_schema[] = {
            "sum_sq", "mean", "elements", "std_deviation", "skewness", "kurtosis", "gain", "h_norm", "l2_dist", "cossim", "pearson", "covariance"
        };
        gguf_set_arr_str(ctx_gguf, LLM_KV_IMATRIX_STATS_SCHEMA, stats_schema, 12);
    }

    for (const auto & name : to_store) {
        const auto & stat = m_stats.at(name);
        const int32_t nval = (int32_t) stat.values.size();
        const int32_t nmat = (int32_t) stat.counts.size();
        if (nval > 0 && nmat > 0) {
            struct ggml_tensor * in_sum2 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, nval / nmat, nmat);
            struct ggml_tensor * counts  = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 1, nmat);
            ggml_format_name(in_sum2, "%s.in_sum2", name.c_str());
            ggml_format_name(counts, "%s.counts", name.c_str());

            for (int32_t j = 0; j < nval; ++j) {
                ((float *) in_sum2->data)[j] = (float) stat.values[j];
            }
            for (int32_t j = 0; j < nmat; ++j) {
                ((float *) counts->data)[j] = (float) stat.counts[j];
            }

            gguf_add_tensor(ctx_gguf, in_sum2);
            gguf_add_tensor(ctx_gguf, counts);

            if (!stat.activations.empty()) {
                const int32_t nact = (int32_t) stat.activations.size();
                struct ggml_tensor * in_sum  = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, nact / nmat, nmat);
                ggml_format_name(in_sum, "%s.in_sum", name.c_str());
                for (int32_t j = 0; j < nact; ++j) {
                    ((float *) in_sum->data)[j] = (float) stat.activations[j];
                }
                gguf_add_tensor(ctx_gguf, in_sum);
            }
        } else {
            LOG_WRN("%s: no data for tensor %s\n", __func__, name.c_str());
        }

        // Store per-tensor statistics as a small 1D tensor
        {
            float fnan = std::numeric_limits<float>::quiet_NaN();
            double sum_sq = 0.0f;
            float mean = 0.0f;
            float elements = 0.0f;
            float std_deviation = 0.0f;
            float skewness = 0.0f;
            float kurtosis = 0.0f;
            float gain = 0.0f;
            float h_norm = 0.0f;
            float l2_dist = 0.0f;
            float cossim = 0.0f;
            float pearson = 0.0f;
            float covariance = 0.0f;
            auto ts = tstat_index.find(name);
            if (ts != tstat_index.end() && ts->second != nullptr) {
                sum_sq = ts->second->sum;
                mean = ts->second->mean;
                elements = (float)ts->second->elements;
                std_deviation = ts->second->std_deviation;
                skewness = ts->second->skewness;
                kurtosis = ts->second->kurtosis;
                gain = ts->second->gain;
                h_norm = ts->second->elements > 1 ? 100.0f * (ts->second->entropy / std::log2f((float)ts->second->elements)) : fnan;
                l2_dist = ts->second->l2_dist;
                cossim = ts->second->cossim;
                pearson = ts->second->pearson;
                covariance = ts->second->covariance;
            }

            struct ggml_tensor * stats = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 12);
            ggml_format_name(stats, "%s.stats", name.c_str());
            // Store the statistics in the same order as defined in stats_schema[]
            ((float *)stats->data)[0] = (float)sum_sq;
            ((float *)stats->data)[1] = mean;
            ((float *)stats->data)[2] = elements;
            ((float *)stats->data)[3] = std_deviation;
            ((float *)stats->data)[4] = skewness;
            ((float *)stats->data)[5] = kurtosis;
            ((float *)stats->data)[6] = gain;
            ((float *)stats->data)[7] = h_norm;
            ((float *)stats->data)[8] = l2_dist;
            ((float *)stats->data)[9] = cossim;
            ((float *)stats->data)[10] = pearson;
            ((float *)stats->data)[11] = covariance;
            gguf_add_tensor(ctx_gguf, stats);
        }
    }

    gguf_write_to_file(ctx_gguf, fname.c_str(), false);

    LOGV(1, "\n");
    LOG_DBGV(1, "%s: stored collected data after %d chunks in %s\n", __func__, m_last_chunk, fname.c_str());

    gguf_free(ctx_gguf);
    ggml_free(ctx);
}

bool IMatrixCollector::load_imatrix(const char * file_name) {
    common_imatrix loaded;
    if (!common_imatrix_load(file_name, loaded)) {
        return false;
    }

    const bool is_legacy = loaded.is_legacy;
    if (loaded.n_layer_nextn > 0) {
        if (m_n_layer_nextn == 0) { m_n_layer_nextn = loaded.n_layer_nextn; }
        else if (m_n_layer_nextn != loaded.n_layer_nextn) {
            LOG_WRN("%s: NextN layer count mismatch in %s: %d != %d, using %d\n",
                __func__, file_name, loaded.n_layer_nextn, m_n_layer_nextn, m_n_layer_nextn);
        }
    }

    if (!is_legacy && loaded.chunk_size > 0) {
        if (m_chunk_size == 0) { m_chunk_size = loaded.chunk_size; }
        else if (m_chunk_size != loaded.chunk_size) {
            LOG_WRN("%s: chunk size mismatch in %s: %d != %d, using %d\n",
                __func__, file_name, loaded.chunk_size, m_chunk_size, m_chunk_size);
        }
    }

    const int32_t chunk_size = e_chunk_size();

    for (auto & [name, entry] : loaded.entries) {
        auto & e = m_stats[name];

        if (is_legacy) {
            if (e.values.empty()) {
                e.values.resize(entry.sums.size(), 0.0f);
                e.counts.resize(1, 0);
            }

            for (size_t j = 0; j < entry.sums.size(); ++j) { e.values[j] += entry.sums[j] * chunk_size; }
            for (size_t j = 0; j < e.counts.size(); ++j) { e.counts[j] += entry.counts[0] * chunk_size; }
            e.activations.clear();
        } else {
            // GGUF format: raw sums and counts, accumulate directly
            const int64_t nval    = entry.sums.size();
            const int64_t ncounts = entry.counts.size();
            const int64_t nact    = entry.activations.size();
            const bool first_contribution = e.values.empty();

            if (e.values.empty()) { e.values.resize(nval, 0.0f); }
            else if ((size_t)nval != e.values.size()) {
                LOG_ERR("%s: mismatched sums size for %s: %zu != %zu\n",
                    __func__, name.c_str(), (size_t) nval, e.values.size());

                return false;
            }

            if (e.counts.empty()) { e.counts.resize(ncounts, 0); }
            else if (e.counts.size() == 1 && ncounts > 1) { e.counts.resize(ncounts, e.counts[0]); }
            else if ((size_t) ncounts != e.counts.size()) {
                LOG_ERR("%s: mismatched counts size for %s: %zu != %zu\n",
                    __func__, name.c_str(), (size_t) ncounts, e.counts.size());

                return false;
            }

            for (int64_t j = 0; j < nval; ++j) { e.values[j] += entry.sums[j]; }
            for (int64_t j = 0; j < ncounts; ++j) { e.counts[j] += entry.counts[j]; }

            if (nact > 0 && (first_contribution || !e.activations.empty())) {
                if (nact != nval) {
                    LOG_ERR("%s: mismatched activations size for %s: %zu != %zu\n",
                        __func__, name.c_str(), (size_t) nact, (size_t) nval);

                    return false;
                }

                if (e.activations.empty()) { e.activations.resize(nact, 0.0f); }
                else if ((size_t) nact != e.activations.size()) {
                    LOG_ERR("%s: mismatched activations size for %s: %zu != %zu\n",
                        __func__, name.c_str(), (size_t) nact, e.activations.size());

                    return false;
                }

                for (int64_t j = 0; j < nact; ++j) { e.activations[j] += entry.activations[j]; }
            } else { e.activations.clear(); }
        }
    }

    m_datasets.insert(m_datasets.end(), loaded.datasets.begin(), loaded.datasets.end());

    // Calculate the last chunk count
    int64_t max_count = 0;
    for (const auto & stats : m_stats) {
        for (int64_t count : stats.second.counts) {
            if (count > max_count) {
                max_count = count;
            }
        }
    }

    m_last_chunk = rows_to_chunks(max_count, chunk_size);

    return true;
}

static IMatrixCollector g_collector;

static bool ik_collect_imatrix(struct ggml_tensor * t, bool ask, void * user_data) {
    return g_collector.collect_imatrix(t, ask, user_data);
}

struct results_log_softmax {
    double log_softmax;
    float  logit;
    float  prob;
};

static std::vector<float> softmax(const std::vector<float> & logits) {
    std::vector<float> probs(logits.size());
    float max_logit = logits[0];
    for (float v : logits) {
        max_logit = std::max(max_logit, v);
    }
    double sum_exp = 0.0;
    for (size_t i = 0; i < logits.size(); i++) {
        // Subtract the maximum logit value from the current logit value for numerical stability
        const float logit = logits[i] - max_logit;
        const float exp_logit = expf(logit);
        sum_exp += exp_logit;
        probs[i] = exp_logit;
    }
    for (size_t i = 0; i < probs.size(); i++) {
        probs[i] /= sum_exp;
    }
    return probs;
}

static results_log_softmax log_softmax(int n_vocab, const float * logits, int tok) {
    float max_logit = logits[0];
    for (int i = 1; i < n_vocab; ++i) {
        max_logit = std::max(max_logit, logits[i]);
    }
    double sum_exp = 0.0;
    for (int i = 0; i < n_vocab; ++i) {
        sum_exp += expf(logits[i] - max_logit);
    }
    return {logits[tok] - max_logit - log(sum_exp), logits[tok], expf(logits[tok] - max_logit) / (float) sum_exp};
}

static void process_logits(
    int n_vocab, const float * logits, const int * tokens, int n_token, std::vector<std::thread> & workers,
    double & nll, double & nll2, float * logit_history, float * prob_history) {
    std::mutex mutex;
    int counter = 0;
    auto compute = [&mutex, &counter, &nll, &nll2, logit_history, prob_history, n_vocab, logits, tokens, n_token] () {
        double local_nll  = 0;
        double local_nll2 = 0;
        while (true) {
            std::unique_lock<std::mutex> lock(mutex);
            int i = counter++;
            if (i >= n_token) {
                nll += local_nll; nll2 += local_nll2;
                break;
            }
            lock.unlock();
            const results_log_softmax results = log_softmax(n_vocab, logits + i*n_vocab, tokens[i+1]);
            const double v = -results.log_softmax;
            local_nll += v;
            local_nll2 += v*v;

            logit_history[i] = results.logit;
            prob_history[i]  = results.prob;
        }
    };
    for (auto & w : workers) {
        w = std::thread(compute);
    }
    compute();
    for (auto & w : workers) {
        w.join();
    }
}

struct nextn_collector {
    llama_context_ptr  ctx;
    common_batch       batch;
    int32_t            n_embd = 0;
    bool               own_lm_head = false;
    std::vector<float> pending_h;
    void clear_memory() {
        llama_memory_clear(llama_get_memory(ctx.get()), true);
        pending_h.clear(); // a chunk's last h-row has no next token, the trunk restarts at position 0
    }
    bool decode(llama_context * ctx_trunk, const common_batch & batch_trunk);
};

struct nextn_model_info {
    bool has_layers = false;
    std::vector<bool> own_lm_head;
};

static nextn_model_info nextn_read_model_info(const std::string & model_path, int32_t n_layer, int32_t n_heads) {
    nextn_model_info info;
    info.own_lm_head.assign(n_heads, false);

    struct gguf_init_params gguf_params = { /*.no_alloc =*/ true, /*.ctx =*/ nullptr };
    struct gguf_context * ctx_gguf = gguf_init_from_file(model_path.c_str(), gguf_params);
    if (!ctx_gguf) {
        LOG_WRN("%s: cannot read '%s'\n", __func__, model_path.c_str());
        return info;
    }

    const int64_t n_tensors = gguf_get_n_tensors(ctx_gguf);

    for (int32_t head = 0; head < n_heads; ++head) {
        const std::string prefix  = "blk." + std::to_string(n_layer + head) + ".nextn.";
        const std::string lm_head = prefix + "shared_head_head.weight";
        for (int64_t i = 0; i < n_tensors; ++i) {
            const std::string name = gguf_get_tensor_name(ctx_gguf, i);
            if (name.rfind(prefix, 0) != 0) { continue; }

            info.has_layers = true;
            if (name == lm_head) { info.own_lm_head[head] = true; }
        }
    }

    gguf_free(ctx_gguf);

    return info;
}

struct model_file_shape {
    bool valid = false;
    bool is_split = false;
    std::string arch;
    uint32_t n_layer_all = 0;
    uint32_t n_embd_out = 0;
    std::set<uint32_t> nextn_idx;
    bool has_trunk = false;
    bool has_nextn = false;
    uint32_t n_nextn_layers = 0;
    std::string first_nextn;

    uint32_t n_trunk() const { return n_layer_all >= n_nextn_layers ? n_layer_all - n_nextn_layers : 0; }
};

static model_file_shape model_read_file_shape(const std::string & model_path) {
    model_file_shape shape;

    struct gguf_init_params gguf_params = { /*.no_alloc =*/ true, /*.ctx =*/ nullptr };
    struct gguf_context * ctx_gguf = gguf_init_from_file(model_path.c_str(), gguf_params);
    if (!ctx_gguf) { return shape; }
    shape.valid = true;

    const int64_t arch_key = gguf_find_key(ctx_gguf, "general.architecture");
    if (arch_key >= 0 && gguf_get_kv_type(ctx_gguf, arch_key) == GGUF_TYPE_STRING) {
        shape.arch = gguf_get_val_str(ctx_gguf, arch_key);
        const std::string prefix = shape.arch + ".";

        const int64_t block_key = gguf_find_key(ctx_gguf, (prefix + "block_count").c_str());
        if (block_key >= 0 && gguf_get_kv_type(ctx_gguf, block_key) == GGUF_TYPE_UINT32) {
            shape.n_layer_all = gguf_get_val_u32(ctx_gguf, block_key);
        }

        const int64_t nextn_key = gguf_find_key(ctx_gguf, (prefix + "nextn_predict_layers").c_str());
        if (nextn_key >= 0 && gguf_get_kv_type(ctx_gguf, nextn_key) == GGUF_TYPE_UINT32) {
            shape.n_nextn_layers = gguf_get_val_u32(ctx_gguf, nextn_key);
        }

        const int64_t embd_out_key = gguf_find_key(ctx_gguf, (prefix + "embedding_length_out").c_str());
        const int64_t embd_key     = gguf_find_key(ctx_gguf, (prefix + "embedding_length").c_str());
        if (embd_out_key >= 0 && gguf_get_kv_type(ctx_gguf, embd_out_key) == GGUF_TYPE_UINT32) {
            shape.n_embd_out = gguf_get_val_u32(ctx_gguf, embd_out_key);
        } else if (embd_key >= 0 && gguf_get_kv_type(ctx_gguf, embd_key) == GGUF_TYPE_UINT32) {
            shape.n_embd_out = gguf_get_val_u32(ctx_gguf, embd_key);
        }
    }

    const int64_t split_key = gguf_find_key(ctx_gguf, "split.count");
    if (split_key >= 0 && gguf_get_kv_type(ctx_gguf, split_key) == GGUF_TYPE_UINT16) {
        shape.is_split = gguf_get_val_u16(ctx_gguf, split_key) > 1;
    }

    const int64_t n_tensors = gguf_get_n_tensors(ctx_gguf);
    for (int64_t i = 0; i < n_tensors; ++i) {
        const std::string name = gguf_get_tensor_name(ctx_gguf, i);
        if (name.find(".nextn.") != std::string::npos) {
            shape.has_nextn = true;
            if (shape.first_nextn.empty()) { shape.first_nextn = name; }

            if (name.rfind("blk.", 0) == 0) {
                const size_t dot = name.find('.', 4);
                if (dot != std::string::npos && name.compare(dot + 1, 6, "nextn.") == 0) {
                    uint32_t idx = 0;
                    bool ok = dot > 4;
                    for (size_t j = 4; j < dot && ok; ++j) {
                        ok  = name[j] >= '0' && name[j] <= '9';
                        idx = 10*idx + (name[j] - '0');
                    }

                    if (ok) { shape.nextn_idx.insert(idx); }
                }
            }
        } else if (name.rfind("blk.0.", 0) == 0) {
            shape.has_trunk = true;
        }
    }

    gguf_free(ctx_gguf);

    return shape;
}

static std::unique_ptr<nextn_collector> nextn_collector_init(llama_model * model, const common_params & params, bool own_lm_head) {
    auto cparams = common_context_params_to_llama(params);
    cparams.ctx_type = LLAMA_CONTEXT_TYPE_MTP;
    cparams.n_rs_seq = 0;
    llama_context * ctx = llama_init_from_model(model, cparams);
    if (ctx == nullptr) {
        LOG_ERR("%s: failed to create the NextN context\n", __func__);
        return nullptr;
    }

    auto res = std::make_unique<nextn_collector>();
    res->ctx.reset(ctx);
    res->n_embd = llama_model_n_embd_out(model);
    res->own_lm_head = own_lm_head;
    res->batch = common_batch(ctx);

    return res;
}

bool nextn_collector::decode(llama_context * ctx_trunk, const common_batch & batch_trunk) {
    const int32_t n_last = batch_trunk.size() - 1;
    batch.clear();
    if (!pending_h.empty()) {
        const int32_t idx = batch.add(batch_trunk.tokens[0].id, batch_trunk.tokens[0].pos[0], 0, own_lm_head);
        batch.set_embd(idx, { pending_h.data(), 1, (size_t) n_embd });
    }

    const float * h_last = nullptr;
    for (int32_t i = 0; i <= n_last; ++i) {
        const float * h = llama_get_embeddings_nextn_ith(ctx_trunk, i);
        if (h == nullptr) {
            LOG_ERR("%s: no NextN hidden state for row %d\n", __func__, i);

            return false;
        }

        if (i == n_last) { h_last = h; break; }

        const int32_t idx = batch.add(batch_trunk.tokens[i + 1].id, batch_trunk.tokens[i + 1].pos[0], 0, own_lm_head);
        batch.set_embd(idx, { h, 1, (size_t) n_embd });
    }

    if (batch.size() > 0) {
        if (llama_process(ctx.get(), LLAMA_PROCESS_TYPE_DECODE, batch.get()) != 0) {
            LOG_ERR("%s: failed to decode the NextN layer\n", __func__);

            return false;
        }
    }

    if (h_last != nullptr) { pending_h.assign(h_last, h_last + n_embd); }

    return true;
}

static bool compute_imatrix(llama_context * ctx, const common_params & params, const int32_t n_ctx, nextn_collector * nextn) {
    const llama_model * model = llama_get_model(ctx);
    const llama_vocab * vocab = llama_model_get_vocab(model);

    const bool add_bos = llama_vocab_get_add_bos(vocab);

    if (llama_pooling_type(ctx) != LLAMA_POOLING_TYPE_LAST) {
        GGML_ASSERT(!llama_vocab_get_add_eos(vocab));
    }

    auto tim1 = std::chrono::high_resolution_clock::now();
    LOG_INF("%s: tokenizing the input ..\n", __func__);

    std::vector<llama_token> tokens = common_tokenize(ctx, params.prompt, true, params.parse_special);

    auto tim2 = std::chrono::high_resolution_clock::now();
    LOG_INF("%s: tokenization took %g ms\n",__func__,1e-3*std::chrono::duration_cast<std::chrono::microseconds>(tim2-tim1).count());

    if (params.i_chunk > 0) {
        if (size_t((params.i_chunk + 2)*n_ctx) >= tokens.size()) {
            LOG_ERR("%s: there will be not enough tokens left after removing %d chunks\n", __func__, params.i_chunk);
            return false;
        }
        LOG_INF("%s: removing initial %d chunks (%d tokens)\n", __func__, params.i_chunk, params.i_chunk*n_ctx);
        tokens.erase(tokens.begin(), tokens.begin() + params.i_chunk*n_ctx);
    }

    if (int(tokens.size()) < 2*n_ctx) {
        LOG_ERR("%s: you need at least %d tokens for a context of %d tokens\n", __func__, 2*n_ctx, n_ctx);
        LOG_ERR("%s: the data file you provided tokenizes to only %zu tokens\n", __func__, tokens.size());
        return false;
    }

    std::vector<float> logit_history;
    std::vector<float> prob_history;

    if (params.compute_ppl) {
        logit_history.resize(tokens.size());
        prob_history.resize(tokens.size());
    }

    const int n_chunk_max = tokens.size() / n_ctx;

    const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max);
    const int n_vocab = llama_vocab_n_tokens(vocab);
    const int n_batch = params.n_batch;

    int count = 0;
    double nll = 0.0;
    double nll2 = 0.0;

    const int num_batches = (n_ctx + n_batch - 1) / n_batch;
    const int n_seq = std::max(1, n_batch / n_ctx);

    GGML_ASSERT(n_batch < n_ctx || n_batch % n_ctx == 0);
    GGML_ASSERT(params.n_ctx == n_seq * n_ctx);

    common_batch batch(ctx);

    std::vector<float> logits;
    if (params.compute_ppl && num_batches > 1) {
        logits.reserve((size_t)n_ctx * n_vocab);
    }

    LOG_INF("%s: computing over %d chunks, n_ctx=%d, batch_size=%d, n_seq=%d\n", __func__, n_chunk, n_ctx, n_batch, n_seq);

    std::vector<std::thread> workers(std::thread::hardware_concurrency() - 1);

    for (int i = 0; i < n_chunk; i += n_seq) {
        const int start =     i * n_ctx;
        const int end   = start + n_ctx;

        const int n_seq_batch = std::min(n_seq, n_chunk - i);

        const auto t_start = std::chrono::high_resolution_clock::now();

        // clear the KV cache
        llama_memory_clear(llama_get_memory(ctx), true);
        if (nextn) { nextn->clear_memory(); }

        for (int j = 0; j < num_batches; ++j) {
            const int batch_start = start + j * n_batch;
            const int batch_size  = std::min(end - batch_start, n_batch);

            // clear the batch
            batch.clear();

            for (int seq = 0; seq < n_seq_batch; seq++) {
                int seq_start = batch_start + seq*n_ctx;

                // save original token and restore it after eval
                const auto token_org = tokens[seq_start];

                // add BOS token for the first batch of each chunk
                if (add_bos && j == 0) {
                    tokens[seq_start] = llama_vocab_bos(vocab);
                }
                for (int k = 0; k < batch_size; ++k) {
                    // NOTE: specifying all logits to get activations for the output.weight tensor
                    //       and also for the perplexity calculation.
                    // TODO: only get outputs when (params.process_output || params.compute_ppl)
                    //       (not possible when this skips FFN computation of the last layer)
                    batch.add(tokens[seq_start + k], j*n_batch + k, seq, true);
                }

                // restore the original token in case it was set to BOS
                tokens[seq_start] = token_org;
            }

            if (llama_process(ctx, LLAMA_PROCESS_TYPE_DECODE, batch.get())) {
                LOG_ERR("%s : failed to eval\n", __func__);

                return false;
            }

            if (nextn && !nextn->decode(ctx, batch)) {
                return false;
            }

            if (params.compute_ppl && num_batches > 1) {
                const auto * batch_logits = llama_get_logits(ctx);
                logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
            }
        }


        if (i == 0) {
            llama_synchronize(ctx);
            const auto t_end = std::chrono::high_resolution_clock::now();
            const float t_total = std::chrono::duration<float>(t_end - t_start).count();
            LOG_INF("%s: %.2f seconds per pass - ETA ", __func__, t_total);
            int total_seconds = (int)(t_total * n_chunk / n_seq);
            if (total_seconds >= 60*60) {
                LOG("%d hours ", total_seconds / (60*60));
                total_seconds = total_seconds % (60*60);
            }
            LOG("%.2f minutes\n", total_seconds / 60.0);
        }

        if (params.compute_ppl) {
            const int first = n_ctx/2;
            for (int seq = 0; seq < n_seq_batch; seq++) {
                const float * all_logits = num_batches > 1 ? logits.data() : llama_get_logits_ith(ctx, seq*n_ctx);

                llama_token * tokens_data = tokens.data() + start + seq*n_ctx + first;

                process_logits(n_vocab, all_logits + first*n_vocab,
                        tokens_data, n_ctx - 1 - first,
                        workers, nll, nll2,
                        logit_history.data() + start + seq*n_ctx + first,
                        prob_history.data()  + start + seq*n_ctx + first);

                count += n_ctx - first - 1;

                LOG("[%d]%.4lf,", i + seq + 1, std::exp(nll / count));
            }
            fflush(stdout);

            logits.clear();
        }
    }

    LOG("\n");

    if (params.compute_ppl) {
        nll2 /= count;
        nll /= count;
        const double ppl = exp(nll);
        nll2 -= nll * nll;
        if (nll2 > 0) {
            nll2 = sqrt(nll2/(count-1));
            LOG("Final estimate: PPL = %.4lf +/- %.5lf\n", ppl, nll2*ppl);
        } else {
            LOG("Unexpected negative standard deviation of log(prob)\n");
        }
    }


    return true;
}

static bool show_statistics(const common_params & params) {
    constexpr auto fnan = std::numeric_limits<float>::quiet_NaN();
    g_collector.set_params(params);
    std::vector<tensor_statistics> ts;

    if (params.in_files.empty()) { return false; }

    // Load and process data
    if (g_collector.load_imatrix(params.in_files[0].c_str())) {
        ts.reserve(g_collector.get_mstats().size());
        for (const auto & [name, stats] : g_collector.get_mstats()) {
            compute_vector_statistics(ts, name, stats);
        }
    } else {
        return false;
    }

    if (ts.empty()) { return false; }

    const auto n_legacy = (size_t) std::count_if(ts.begin(), ts.end(), [](const tensor_statistics & t) { return t.legacy; });
    if (n_legacy > 0 && n_legacy < ts.size()) {
        LOG_WRN("%s: %zu of %zu tensors have no activation data, using the legacy layout\n", __func__, n_legacy, ts.size());
    }

    const bool legacy = n_legacy > 0;
    const int nextn_start = nextn_layer_start(ts, g_collector.get_n_layer_nextn());
    compute_tensor_statistics(ts, g_collector.get_mstats(), nextn_start);

    // Sorting logic (Layer index -> Tensor Name)
    struct tensor_comparer {
        bool operator()(const tensor_statistics & a, const tensor_statistics & b) const {
            std::string lay_a;
            std::string lay_b;
            std::string name_a;
            std::string name_b;
            process_tensor_name(a.tensor, lay_a, name_a);
            process_tensor_name(b.tensor, lay_b, name_b);

            // Handle non-numeric layers (e.g., "output")
            int blk_a = INT_MAX - 1;
            int blk_b = INT_MAX - 1;
            try {
                blk_a = std::stoi(lay_a);
            } catch(...) {
                if (a.tensor.find("output") != std::string::npos) { blk_a = INT_MAX; }
            }
            try {
                blk_b = std::stoi(lay_b);
            } catch(...) {
                if (b.tensor.find("output") != std::string::npos) { blk_b = INT_MAX; }
            }

            if (blk_a != blk_b) { return blk_a < blk_b; }
            return name_a < name_b;
        }
    };
    std::sort(ts.begin(), ts.end(), tensor_comparer());

    struct layer_stats {
        float layer_sum = 0.0f;
        int n = 0;
    };
    std::map<int, layer_stats> ls;

    // Shorten names for table formatting
    auto label_fmt = [](std::string s, size_t w) -> std::string {
        if (s.length() <= w) { return s; }
        return ".." + s.substr(s.length() - (w - 2));
    };

    constexpr int w_lay = 6;
    constexpr int w_nam = 40; // Should be wide enough for most tensor names
    const auto * sep = " | ";

    printf("\nComputing tensor statistics for %s (%d tensors)\n", params.in_files[0].c_str(), static_cast<int>(ts.size()));

    if (legacy) {
        printf("\n%*s%s%-*s%s%10s%10s%12s%12s%9s%s%17s%8s%s%10s%10s\n",
            w_lay, "Layer", sep,
            w_nam, "Tensor", sep,
            "Mean", "StdDev", "Skew", "Kurt", "H Norm", sep,
            "∑ E[A²]", "Gain", sep,
            "PCC", "Cov");
        printf("%s\n", std::string(153, '-').c_str());
    } else {
        printf("\n%*s%s%-*s%s%10s%10s%12s%12s%9s%s%17s%8s%s%12s%10s%10s\n",
            w_lay, "Layer", sep,
            w_nam, "Tensor", sep,
            "Mean", "StdDev", "Skew", "Kurt", "H Norm", sep,
            "∑ E[A²]", "Gain", sep,
            "L2 Dist", "PCC", "Cov");
        printf("%s\n", std::string(165, '-').c_str());
    }

    // Tensor Statistics
    for (const auto & tstat : ts) {
        std::string layer;
        std::string name;

        process_tensor_name(tstat.tensor, layer, name);
        const float h_norm = tstat.elements > 1 ? 100.0f * (tstat.entropy / std::log2f((float)tstat.elements)) : fnan;

        int blk;
        try {
            blk = std::stoi(layer);
        } catch (...) {
            if (tstat.tensor.find("output") != std::string::npos) { blk = INT_MAX; }
            else { blk = -1; }
        }

        layer = layer_label(blk, nextn_start);
        if (legacy) {
            printf("%*s%s%-*s%s%10.4f%10.4f%12.4f%12.4f%8.2f%%%s%14.4f%8.2f%s%10.4f%10.4f\n",
                w_lay, layer.c_str(), sep,
                w_nam, label_fmt(tstat.tensor, w_nam).c_str(), sep,
                tstat.mean, tstat.std_deviation, tstat.skewness, tstat.kurtosis, h_norm, sep,
                tstat.sum, tstat.gain, sep,
                tstat.pearson, tstat.covariance
            );
        } else {
            printf("%*s%s%-*s%s%10.4f%10.4f%12.4f%12.4f%8.2f%%%s%14.4f%8.2f%s%12.4f%10.4f%10.4f\n",
                w_lay, layer.c_str(), sep,
                w_nam, label_fmt(tstat.tensor, w_nam).c_str(), sep,
                tstat.mean, tstat.std_deviation, tstat.skewness, tstat.kurtosis, h_norm, sep,
                tstat.sum, tstat.gain, sep,
                tstat.l2_dist, tstat.pearson, tstat.covariance
            );
        }

        // Aggregate Layer Stats
        auto & l = ls[blk];
        l.layer_sum += tstat.sum;
        l.n += tstat.elements;
    }

    // Layer Statistics
    std::map<int, float> layer_cossim;
    std::map<int, float> layer_l2_dist;
    std::map<int, float> layer_pearson;
    std::map<int, float> layer_covariance;
    std::map<int, float> layer_gain;
    compute_layer_statistics(ts, layer_cossim, layer_l2_dist, layer_pearson, layer_covariance, layer_gain);

    size_t layers = 0;
    size_t trunk_layers = 0;
    int min = std::numeric_limits<int>::max();
    int max = -1;

    for (const auto & [layer, stats] : ls) {
        if (layer >= 0 && layer < 9999 && stats.n > 0) {
            layers++;
            if (layer < nextn_start) {
                trunk_layers++;
                min = std::min(layer, min);
                max = std::max(layer, max);
            }
        }
    }

    if (trunk_layers > 0) {
        const auto expected = (size_t)(max - min + 1);
        if (trunk_layers != expected) {
            LOG_WRN("\n%s: layer sequence gap detected (found %zu layers in range %d-%d, expected %zu); layer statistics will not be shown\n",
                __func__, trunk_layers, min, max, expected);
            return false;
        }
    }

    printf("\nComputing layer statistics for %s (%zu layers)\n\n", params.in_files[0].c_str(), layers);

    if (legacy) {
        printf("%*s%s%17s%8s%s%9s%9s%12s\n",
            w_lay, "Layer", sep,
            "∑ E[A²]", "Gain", sep,
            "CosSim", "PCC", "Cov");
        printf("%s\n", std::string(64, '-').c_str());
    } else {
        printf("%*s%s%17s%8s%s%12s%9s%9s%12s\n",
            w_lay, "Layer", sep,
            "∑ E[A²]", "Gain", sep,
            "L2 Dist", "CosSim", "PCC", "Cov");
        printf("%s\n", std::string(76, '-').c_str());
    }

    auto get_layer_stat = [&](const std::map<int, float>& map, const int layer) -> float {
        const auto it = map.find(layer);
        return it != map.end() ? it->second : fnan;
    };

    for (const auto & [layer, stats] : ls) {
        if (layer < 0 || stats.n == 0) { continue; }

        float lgn = layer == 0 || layer == INT_MAX ? fnan : get_layer_stat(layer_gain, layer);
        float ll2 = layer == 0 || layer == INT_MAX ? fnan : get_layer_stat(layer_l2_dist, layer);
        float lcs = layer == 0 || layer == INT_MAX ? fnan : get_layer_stat(layer_cossim, layer);
        float lpc = layer == 0 || layer == INT_MAX ? fnan : get_layer_stat(layer_pearson, layer);
        float lcv = layer == 0 || layer == INT_MAX ? fnan : get_layer_stat(layer_covariance, layer);
        const auto lyr = layer_label(layer, nextn_start);

        if (legacy) {
            printf("%*s%s%14.4f%8.2f%s%9.4f%9.4f%12.4f\n",
                w_lay, lyr.c_str(), sep,
                stats.layer_sum, lgn, sep,
                lcs, lpc, lcv);
        } else {
            printf("%*s%s%14.4f%8.2f%s%12.4f%9.4f%9.4f%12.4f\n",
                w_lay, lyr.c_str(), sep,
                stats.layer_sum, lgn, sep,
                ll2, lcs, lpc, lcv);
        }
    }

    printf("\n");
    return true;
}

int main(int argc, char ** argv) {
    std::setlocale(LC_NUMERIC, "C");

    common_params params;

    params.out_file = "imatrix.gguf";

    params.n_ctx = 512;
    params.escape = false;

    common_init();

    if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_IMATRIX, print_usage)) {
        return 1;
    }

    const bool use_draft = !params.speculative.draft.mparams.path.empty();
    if (use_draft) {
        params.load_mtp = true;
        params.speculative.draft.n_max = 0; // keep trunk's context identical to a plain run
    }

    // set_params before show_statistics so load_imatrix has valid n_ctx/n_parallel
    g_collector.set_params(params);

    if (params.show_statistics) {
        if (!show_statistics(params)) {
            return 1;
        }
        return 0;
    }

    const int32_t n_ctx = params.n_ctx;

    if (n_ctx <= 0) {
        LOG_ERR("%s: imatrix tool requires '--ctx-size' > 0\n", __func__);
        return 1;
    }

    {
        const int32_t n_seq = std::max(1, params.n_batch / n_ctx);
        const int32_t n_kv = n_seq * n_ctx;

        if (params.load_mtp && n_seq > 1) {
            LOG_ERR("%s: '--nextn' and '--model-draft' need a single sequence per batch, set '--batch-size' to at most '--ctx-size' (%d)\n", __func__, n_ctx);

            return 1;
        }

        params.n_parallel = n_seq;
        params.n_ctx      = n_kv;

        params.n_batch = std::min(params.n_batch, n_kv);
    }

    g_collector.set_params(params);

    for (const auto & in_file : params.in_files) {
        LOG_INF("%s : loading imatrix from '%s'\n", __func__, in_file.c_str());
        if (!g_collector.load_imatrix(in_file.c_str())) {
            LOG_ERR("%s : failed to load %s\n", __func__, in_file.c_str());
            return 1;
        }
    }

    if (params.prompt.empty()) {
        LOG_INF("No prompt provided; combining precomputed matrices only.\n");

        if (params.in_files.empty()) {
            LOG_ERR("Error: No prompt provided and no precomputed matrices (--in-file) to combine.\n");
            return 1;
        }

        if (params.in_files.size() == 1) {
            LOG_INF("%s : saving imatrix to '%s'\n", __func__, params.out_file.c_str());
        } else if (params.in_files.size() > 1) {
            LOG_INF("%s : saving combined imatrix to '%s'\n", __func__, params.out_file.c_str());
        }

        g_collector.save_imatrix();

        return 0;
    }

    {
        const model_file_shape shape = model_read_file_shape(params.model.path);
        if (use_draft && shape.n_nextn_layers > 0) {
            LOG_ERR("%s: model already includes NextN layers\n", __func__);
            return 1;
        }
        if (use_draft && shape.has_nextn) {
            LOG_ERR("%s: the model already includes NextN layers (NextN tensor '%s')\n", __func__, shape.first_nextn.c_str());
            return 1;
        }
        if (!use_draft && !shape.has_trunk && (shape.n_nextn_layers > 0 || shape.has_nextn)) {
            LOG_ERR("%s: '%s' is a NextN draft, use with --model-draft/-md\n", __func__, params.model.path.c_str());
            return 1;
        }
        if (use_draft) {
            const std::string & path_md = params.speculative.draft.mparams.path;
            const model_file_shape shape_md = model_read_file_shape(path_md);
            if (!shape_md.valid || shape_md.is_split) {
                LOG_ERR("%s: '%s' is not a readable single-shard GGUF\n", __func__, path_md.c_str());
                return 1;
            }
            if (shape.valid && shape_md.arch != shape.arch) {
                LOG_ERR("%s: the draft architecture '%s' does not match the target architecture '%s'\n", __func__, shape_md.arch.c_str(), shape.arch.c_str());
                return 1;
            }
            if (shape_md.n_nextn_layers == 0 || shape_md.has_trunk) {
                LOG_ERR("%s: '%s' is not a draft (no NextN layers or trunk tensors present)\n", __func__, path_md.c_str());
                return 1;
            }
            if (shape_md.n_nextn_layers > 1) {
                LOG_ERR("%s: multi-layer NextN drafts are not supported (found %u)\n", __func__, shape_md.n_nextn_layers);
                return 1;
            }
            if (shape_md.n_trunk() == 0) {
                LOG_ERR("%s: NextN layers sharing the trunk's KV cache are not supported\n", __func__);
                return 1;
            }
            if (shape.valid && shape_md.nextn_idx.count(shape.n_trunk()) == 0) {
                LOG_ERR("%s: no NextN tensors at layer index %u in '%s' found\n", __func__, shape.n_trunk(), path_md.c_str());
                return 1;
            }
            if (shape.valid && shape_md.n_embd_out != shape.n_embd_out) {
                LOG_ERR("%s: the draft output width %u does not match the target's %u\n", __func__, shape_md.n_embd_out, shape.n_embd_out);
                return 1;
            }
            for (const auto type : params.speculative.types) {
                if (type != COMMON_SPECULATIVE_TYPE_NONE && type != COMMON_SPECULATIVE_TYPE_DRAFT_MTP) {
                    LOG_ERR("%s: speculative type '%s' is not supported with --model-draft/-md (only 'draft-mtp')\n", __func__, common_speculative_type_to_str(type).c_str());
                    return 1;
                }
            }
        }
    }

    llama_backend_init();
    llama_numa_init(params.numa);

    // pass the callback to the backend scheduler
    // it will be executed for each node during the graph computation
    params.cb_eval = ik_collect_imatrix;
    params.cb_eval_user_data = NULL;
    params.warmup = false;

    // init
    auto llama_init = common_init_from_params(params);

    auto * model = llama_init->model();
    auto * ctx   = llama_init->context();

    if (model == nullptr || ctx == nullptr) {
        LOG_ERR("%s : failed to init\n", __func__);
        return 1;
    }

    const int n_ctx_train = llama_model_n_ctx_train(model);
    if (params.n_ctx > n_ctx_train) {
        LOG_WRN("%s: model was trained on only %d context tokens (%d specified)\n",
                __func__, n_ctx_train, params.n_ctx);
    }

    llama_model_ptr model_draft;
    if (use_draft) {
        auto mparams_sidecar = common_model_params_to_llama(params);
        mparams_sidecar.load_mtp = true;
        model_draft.reset(llama_model_load_from_file(params.speculative.draft.mparams.path.c_str(), mparams_sidecar));
        if (model_draft == nullptr) {
            LOG_ERR("%s: failed to load the draft model '%s'\n", __func__, params.speculative.draft.mparams.path.c_str());

            return 1;
        }
        if (!common_speculative_are_compatible(model, model_draft.get())) {
            LOG_ERR("%s: the target and draft vocab are not compatible\n", __func__);

            return 1;
        }
    }

    std::unique_ptr<nextn_collector> nextn;

    if (params.load_mtp) {
        llama_model * model_src = use_draft ? model_draft.get() : model;
        const std::string & path_src = use_draft ? params.speculative.draft.mparams.path : params.model.path;
        const char * flag_src = use_draft ? "'-md'" : "'--nextn'";

        const int32_t n_heads = llama_model_n_layer_nextn(model_src);
        const int32_t n_trunk_src = llama_model_n_layer(model_src);
        const int32_t n_trunk = llama_model_n_layer(model);
        const nextn_model_info info = n_heads > 0 ? nextn_read_model_info(path_src, n_trunk, n_heads) : nextn_model_info();

        if (n_heads == 0) {
            LOG_WRN("%s: the model has no NextN layers, %s has no effect\n", __func__, flag_src);
        } else if (n_trunk_src == 0) {
            LOG_ERR("%s: NextN layers sharing the trunk's KV cache are not supported\n", __func__);
            return 1;
        } else if (n_heads > 1) {
            LOG_ERR("%s: multi-layer NextN drafts are not supported (found %u)\n", __func__, n_heads);
            return 1;
        } else if (!info.has_layers) {
            LOG_WRN("%s: no NextN tensor in '%s', %s has no effect\n", __func__, path_src.c_str(), flag_src);
        } else {
            nextn = nextn_collector_init(model_src, params, info.own_lm_head[0]);
            if (nextn == nullptr) { return 1; }
            llama_set_embeddings_nextn(ctx, true, /*masked*/ false);
            g_collector.set_n_layer_nextn(n_heads);

            LOG_INF("%s: processing %d NextN layer(s) from block %d\n", __func__, n_heads, n_trunk);
        }
    }

    // print system information
    {
        LOG_INF("\n");
        LOG_INF("%s\n", common_params_get_system_info(params).c_str());
    }

    if (!compute_imatrix(ctx, params, n_ctx, nextn.get())) { return 1; }

    g_collector.save_imatrix();

    LOG("\n");
    llama_perf_context_print(ctx);

    llama_backend_free();

    return 0;
}