imatrix.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  1. #include "arg.h"
  2. #include "common.h"
  3. #include "log.h"
  4. #include "llama.h"
  5. #include "gguf.h"
  6. #include <algorithm>
  7. #include <chrono>
  8. #include <cmath>
  9. #include <cstdio>
  10. #include <cstring>
  11. #include <ctime>
  12. #include <thread>
  13. #include <mutex>
  14. #include <vector>
  15. #include <fstream>
  16. #include <unordered_map>
  17. #include <map>
  18. #include <regex>
  19. #include <numeric>
  20. #if defined(_MSC_VER)
  21. #pragma warning(disable: 4244 4267) // possible loss of data
  22. #endif
  23. static void print_usage(int, char ** argv) {
  24. LOG("\nexample usage:\n");
  25. LOG("\n %s \\\n"
  26. " -m model.gguf -f some-text.txt [-o imatrix.gguf] [--no-ppl] \\\n"
  27. " [--process-output] [--chunk 123] [--save-frequency 0] [--output-frequency 10] \\\n"
  28. " [--in-file imatrix-prev-0.gguf --in-file imatrix-prev-1.gguf ...] [--parse-special] \\\n"
  29. " [--show-statistics] [...]\n" , argv[0]);
  30. LOG("\n");
  31. }
  32. static const char * const LLM_KV_IMATRIX_DATASETS = "imatrix.datasets";
  33. static const char * const LLM_KV_IMATRIX_CHUNK_COUNT = "imatrix.chunk_count";
  34. static const char * const LLM_KV_IMATRIX_CHUNK_SIZE = "imatrix.chunk_size";
  35. struct Stats {
  36. std::vector<float> values;
  37. std::vector<int64_t> counts;
  38. };
  39. struct tensor_statistics {
  40. std::string tensor;
  41. Stats stats;
  42. float total_sqract = 0.0f;
  43. float mean_sqract = 0.0f;
  44. float max_sqract = 0.0f;
  45. float min_sqract = 0.0f;
  46. int elements = 0;
  47. float stddev = 0.0f;
  48. float active = 0.0f;
  49. float entropy = 0.0f;
  50. float zd = 0.0f;
  51. float cossim = 0.0f;
  52. };
  53. class IMatrixCollector {
  54. public:
  55. IMatrixCollector() = default;
  56. void set_params(common_params params) { m_params = std::move(params); }
  57. bool collect_imatrix(struct ggml_tensor * t, bool ask, void * user_data);
  58. void save_imatrix_legacy(int32_t ncall = -1) const;
  59. void save_imatrix(int32_t n_chunk = -1) const;
  60. bool load_imatrix_legacy(const char * fname);
  61. bool load_imatrix(const char * file_name);
  62. const std::unordered_map<std::string, Stats> & get_mstats() const { return m_stats; }
  63. private:
  64. std::unordered_map<std::string, Stats> m_stats;
  65. common_params m_params;
  66. std::mutex m_mutex;
  67. std::vector<std::string> m_datasets;
  68. int32_t m_last_chunk = 0;
  69. std::vector<char> m_src1_data;
  70. std::vector<char> m_ids; // the expert ids from ggml_mul_mat_id
  71. };
  72. // remove any prefix and suffixes from the name
  73. // CUDA0#blk.0.attn_k.weight#0 => blk.0.attn_k.weight
  74. static std::string filter_tensor_name(const char * name) {
  75. std::string wname;
  76. const char * p = strchr(name, '#');
  77. if (p != NULL) {
  78. p = p + 1;
  79. const char * q = strchr(p, '#');
  80. if (q != NULL) {
  81. wname = std::string(p, q - p);
  82. } else {
  83. wname = p;
  84. }
  85. } else {
  86. wname = name;
  87. }
  88. return wname;
  89. }
  90. static void process_tensor_name(const std::string & input, std::string & layer, std::string & tensor) {
  91. std::vector<std::string> name;
  92. std::istringstream stream(input);
  93. std::string item;
  94. while (std::getline(stream, item, '.')) {
  95. name.push_back(item);
  96. }
  97. for (size_t i = 0; i < name.size(); ++i) {
  98. if (name[i] == "blk" && i + 1 < name.size()) {
  99. layer = name[i + 1];
  100. break;
  101. }
  102. }
  103. for (size_t i = 0; i < name.size(); ++i) {
  104. if (name[i] == "weight" && i > 0) {
  105. tensor = name[i - 1];
  106. break;
  107. }
  108. }
  109. if (tensor.empty()) {
  110. tensor = input;
  111. }
  112. if (layer.empty()) {
  113. layer = "-";
  114. }
  115. }
  116. static void compute_statistics(std::vector<tensor_statistics> & tstats, const std::string & name, const Stats & e) {
  117. if (e.values.size() % e.counts.size() != 0) {
  118. LOG_ERR("%s: activation size mismatch for tensor %s (%zu vs %zu)\n", __func__, name.c_str(), e.counts.size(), e.values.size());
  119. return;
  120. }
  121. if (e.counts.empty()) {
  122. LOG_ERR("%s: there are no activations for tensor %s. The imatrix may be suboptimal\n", __func__, name.c_str());
  123. return;
  124. }
  125. const int n_mat = e.counts.size();
  126. const int row_size = e.values.size() / n_mat;
  127. std::vector<float> activations;
  128. activations.reserve(e.values.size());
  129. for (int i = 0; i < n_mat; ++i) {
  130. for (int j = 0; j < row_size; ++j) {
  131. activations.push_back(e.values[i*row_size + j] / e.counts[i]);
  132. }
  133. }
  134. const float act_total = std::accumulate(activations.begin(), activations.end(), 0.0f);
  135. const float act_max = *std::max_element(activations.begin(), activations.end());
  136. const float act_min = *std::min_element(activations.begin(), activations.end());
  137. const float act_mean = act_total / activations.size();
  138. const float act_sqr_total = std::inner_product(activations.begin(), activations.end(), activations.begin(), 0.0f);
  139. const float act_var = (act_sqr_total / activations.size()) - (act_mean * act_mean);
  140. const float act_dev = std::sqrt(std::max(0.0f, act_var));
  141. float threshold = 1e-5f;
  142. const int inactive_count = std::count_if(activations.begin(), activations.end(),
  143. [threshold](const float v) { return fabsf(v) <= threshold; });
  144. const float active_ratio = 1 - static_cast<float>(inactive_count) / activations.size();
  145. float entropy = 0;
  146. if (act_total > 0) {
  147. for (const auto act : activations) {
  148. if (const float p = act / act_total; p > 0) {
  149. entropy -= p * std::log2(p);
  150. }
  151. }
  152. }
  153. int z_score = 0;
  154. if (act_dev > 0.0f) {
  155. for (const auto act : activations) {
  156. if (const float p = (act - act_mean) / act_dev; p > 1) {
  157. z_score++;
  158. }
  159. }
  160. }
  161. auto & ts = tstats.emplace_back();
  162. ts.tensor = name;
  163. ts.stats = e;
  164. ts.total_sqract = act_total;
  165. ts.mean_sqract = act_mean;
  166. ts.max_sqract = act_max;
  167. ts.min_sqract = act_min;
  168. ts.elements = static_cast<int>(activations.size());
  169. ts.stddev = act_dev;
  170. ts.active = active_ratio;
  171. ts.entropy = entropy;
  172. ts.zd = static_cast<float>(z_score) / ts.elements;
  173. }
  174. static void compute_cossim(std::vector<tensor_statistics> & tstats) {
  175. static const std::regex pattern(R"(blk\.(\d+)\.)");
  176. for (auto & ts : tstats) {
  177. if (std::smatch match; std::regex_search(ts.tensor, match, pattern)) {
  178. const int blk = std::stoi(match[1]);
  179. std::string tname(ts.tensor);
  180. tname.replace(match.position(1), match.length(1), std::to_string(blk-1));
  181. auto prev = std::find_if(tstats.begin(), tstats.end(),
  182. [tname](const tensor_statistics & t) { return t.tensor == tname; });
  183. if (prev != tstats.end()) {
  184. const float dp = std::inner_product(ts.stats.values.begin(), ts.stats.values.end(),
  185. prev->stats.values.begin(), 0.0f);
  186. const float curr_mag = std::sqrt(std::inner_product(ts.stats.values.begin(), ts.stats.values.end(),
  187. ts.stats.values.begin(), 0.0f));
  188. const float prev_mag = std::sqrt(std::inner_product(prev->stats.values.begin(), prev->stats.values.end(),
  189. prev->stats.values.begin(), 0.0f));
  190. const float cs = dp / (curr_mag * prev_mag);
  191. ts.cossim = cs;
  192. }
  193. } else {
  194. ts.cossim = 0;
  195. }
  196. }
  197. }
  198. bool IMatrixCollector::collect_imatrix(struct ggml_tensor * t, bool ask, void * user_data) {
  199. GGML_UNUSED(user_data);
  200. const struct ggml_tensor * src0 = t->src[0];
  201. const struct ggml_tensor * src1 = t->src[1];
  202. std::string wname = filter_tensor_name(src0->name);
  203. const int32_t chunk_size = m_params.n_ctx / m_params.n_parallel;
  204. // when ask is true, the scheduler wants to know if we are interested in data from this tensor
  205. // if we return true, a follow-up call will be made with ask=false in which we can do the actual collection
  206. if (ask) {
  207. if (t->op == GGML_OP_MUL_MAT_ID) return true; // collect all indirect matrix multiplications
  208. if (t->op != GGML_OP_MUL_MAT) return false;
  209. // why are small batches ignored (<16 tokens)?
  210. if (src1->ne[1] < 16 || src1->type != GGML_TYPE_F32) return false;
  211. if (!(wname.substr(0, 4) == "blk." || (m_params.process_output && wname == "output.weight"))) return false;
  212. return true;
  213. }
  214. std::lock_guard<std::mutex> lock(m_mutex);
  215. // copy the data from the GPU memory if needed
  216. const bool is_host = ggml_backend_buffer_is_host(src1->buffer);
  217. if (!is_host) {
  218. const size_t src1_nbytes = ggml_nbytes(src1);
  219. m_src1_data.resize(src1_nbytes);
  220. ggml_backend_tensor_get(src1, m_src1_data.data(), 0, src1_nbytes);
  221. }
  222. const char * data = is_host ? (const char *) src1->data : m_src1_data.data();
  223. GGML_ASSERT(src1->nb[0] == ggml_element_size(src1));
  224. // TODO: 4d? (is that even used in practice?)
  225. // the extra dimension would need to be stored somewhere to be reflected in the imatrix file
  226. if (ggml_nrows(src1) != src1->ne[1] * src1->ne[2]) {
  227. LOG_ERR("%s: tensor has more than 3 dimensions: %s", __func__, wname.c_str());
  228. GGML_ASSERT(false);
  229. }
  230. // this has been adapted to the new format of storing merged experts in a single 3d tensor
  231. // ref: https://github.com/ggml-org/llama.cpp/pull/6387
  232. if (t->op == GGML_OP_MUL_MAT_ID) {
  233. // ids -> [n_experts_used, n_tokens]
  234. // src1 -> [cols, n_expert_used, n_tokens]
  235. const ggml_tensor * ids = t->src[2];
  236. const int64_t n_as = src0->ne[2];
  237. const int64_t n_ids = ids->ne[0];
  238. // the top-k selected expert ids are stored in the ids tensor
  239. // for simplicity, always copy ids to host, because it is small
  240. // take into account that ids is not contiguous!
  241. GGML_ASSERT(ids->ne[1] == src1->ne[2]);
  242. m_ids.resize(ggml_nbytes(ids));
  243. ggml_backend_tensor_get(ids, m_ids.data(), 0, ggml_nbytes(ids));
  244. auto & e = m_stats[wname];
  245. if (e.counts.size() == 1 && n_as > 1) {
  246. // broadcast, when loading an old imatrix
  247. e.counts.resize(n_as, e.counts[0]);
  248. }
  249. if (e.values.empty()) {
  250. e.values.resize(src1->ne[0]*n_as, 0);
  251. e.counts.resize(n_as, 0);
  252. }
  253. else if (e.values.size() != (size_t)src1->ne[0]*n_as) {
  254. 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));
  255. exit(1); //GGML_ABORT("fatal error");
  256. }
  257. else if (e.counts.size() != (size_t)n_as) {
  258. LOG_ERR("%s: inconsistent expert count for %s (%d vs %d)\n", __func__, wname.c_str(), (int)e.counts.size(), (int)n_as);
  259. exit(1); //GGML_ABORT("fatal error");
  260. }
  261. 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);
  262. // loop over all possible experts, regardless if they are used or not in the batch
  263. for (int64_t ex = 0; ex < n_as; ++ex) {
  264. size_t e_start = ex*src1->ne[0];
  265. for (int64_t idx = 0; idx < n_ids; ++idx) {
  266. for (int64_t row = 0; row < src1->ne[2]; ++row) {
  267. const int excur = *(const int32_t *) (m_ids.data() + row*ids->nb[1] + idx*ids->nb[0]);
  268. GGML_ASSERT(excur >= 0 && excur < n_as); // sanity check
  269. if (excur != ex) continue;
  270. const int64_t i11 = idx % src1->ne[1];
  271. const int64_t i12 = row;
  272. const float * x = (const float *)(data + i11*src1->nb[1] + i12*src1->nb[2]);
  273. e.counts[ex]++;
  274. for (int64_t j = 0; j < src1->ne[0]; ++j) {
  275. e.values[e_start + j] += x[j] * x[j];
  276. if (!std::isfinite((float)e.values[e_start + j])) {
  277. LOG_ERR("%f detected in %s\n", (float)e.values[e_start + j], wname.c_str());
  278. exit(1);
  279. }
  280. }
  281. }
  282. }
  283. const int32_t n_chunk = e.counts[ex] / chunk_size;
  284. if (n_chunk > m_last_chunk) {
  285. const int32_t chunk_step = n_chunk - m_last_chunk;
  286. m_last_chunk = n_chunk;
  287. if ((m_last_chunk % m_params.n_out_freq) / chunk_step == 0) {
  288. save_imatrix();
  289. }
  290. if (m_params.n_save_freq > 0 && (m_last_chunk % m_params.n_save_freq) / chunk_step == 0) {
  291. save_imatrix(m_last_chunk);
  292. }
  293. }
  294. }
  295. } else {
  296. auto & e = m_stats[wname];
  297. const int64_t n_mat = src1->ne[2] * src1->ne[3];
  298. if (e.values.empty()) {
  299. e.values.resize(src1->ne[0] * n_mat, 0);
  300. e.counts.resize(n_mat, 0);
  301. }
  302. else if (e.values.size() != (size_t)(src1->ne[0] * n_mat)) {
  303. 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));
  304. exit(1); //GGML_ABORT("fatal error");
  305. }
  306. else if (e.counts.size() != (size_t)n_mat) {
  307. LOG_ERR("%s: inconsistent expert count for %s (%d vs %d)\n", __func__, wname.c_str(), (int)e.counts.size(), (int)n_mat);
  308. exit(1); //GGML_ABORT("fatal error");
  309. }
  310. 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);
  311. for (int64_t i3 = 0; i3 < src1->ne[3]; ++i3) {
  312. for (int64_t i2 = 0; i2 < src1->ne[2]; ++i2) {
  313. const int64_t mat_id = i3 * src1->ne[2] + i2;
  314. const int64_t mat_start = mat_id * src1->ne[0];
  315. for (int64_t row = 0; row < src1->ne[1]; ++row) {
  316. const float * x = (const float *) (data + row * src1->nb[1] + i2 * src1->nb[2] + i3 * src1->ne[3]);
  317. e.counts[mat_id]++;
  318. for (int64_t j = 0; j < src1->ne[0]; ++j) {
  319. e.values[mat_start + j] += x[j] * x[j];
  320. if (!std::isfinite((float)e.values[j])) {
  321. LOG_ERR("%f detected in %s\n", (float)e.values[j], wname.c_str());
  322. exit(1);
  323. }
  324. }
  325. }
  326. const int32_t n_chunk = e.counts[mat_id] / chunk_size;
  327. if (n_chunk > m_last_chunk) {
  328. const int32_t chunk_step = n_chunk - m_last_chunk;
  329. m_last_chunk = n_chunk;
  330. if ((m_last_chunk % m_params.n_out_freq) / chunk_step == 0) {
  331. save_imatrix();
  332. }
  333. if (m_params.n_save_freq > 0 && (m_last_chunk % m_params.n_save_freq) / chunk_step == 0) {
  334. save_imatrix(m_last_chunk);
  335. }
  336. }
  337. }
  338. }
  339. }
  340. return true;
  341. }
  342. void IMatrixCollector::save_imatrix_legacy(int32_t ncall) const {
  343. auto fname = m_params.out_file;
  344. if (ncall > 0) {
  345. fname += ".at_";
  346. fname += std::to_string(ncall);
  347. }
  348. // warn when writing imatrix entries that do not have full data
  349. // this can happen with MoE models where some of the experts end up not being exercised by the provided training data
  350. int n_entries = 0;
  351. std::vector<std::string> to_store;
  352. bool is_first = true; // for printing
  353. for (const auto & kv : m_stats) {
  354. const int n_all = kv.second.counts.size();
  355. if (n_all == 0) {
  356. continue;
  357. }
  358. int n_zeros = 0;
  359. for (const int c : kv.second.counts) {
  360. if (c == 0) {
  361. n_zeros++;
  362. }
  363. }
  364. if (n_zeros != 0 && is_first) {
  365. LOG_INF("\n");
  366. is_first = false;
  367. }
  368. if (n_zeros == n_all) {
  369. LOG_WRN("%s: entry '%40s' has no data - skipping\n", __func__, kv.first.c_str());
  370. continue;
  371. }
  372. if (n_zeros > 0) {
  373. LOG_WRN("%s: entry '%40s' has partial data (%.2f%%)\n", __func__, kv.first.c_str(), 100.0f * (n_all - n_zeros) / n_all);
  374. }
  375. n_entries++;
  376. to_store.push_back(kv.first);
  377. }
  378. if (to_store.size() < m_stats.size()) {
  379. LOG_WRN("%s: storing only %zu out of %zu entries\n", __func__, to_store.size(), m_stats.size());
  380. }
  381. // deterministic tensor name order
  382. std::sort(to_store.begin(), to_store.end());
  383. const int32_t chunk_size = m_params.n_ctx / m_params.n_parallel;
  384. std::ofstream out(fname, std::ios::binary);
  385. out.write((const char *) &n_entries, sizeof(n_entries));
  386. for (const auto & name : to_store) {
  387. const auto & stat = m_stats.at(name);
  388. const int32_t len = name.size();
  389. out.write((const char *) &len, sizeof(len));
  390. out.write(name.c_str(), len);
  391. // ceiling division to avoid accidental zeros
  392. const int32_t ncall = (*std::max_element(stat.counts.begin(), stat.counts.end()) + (chunk_size - 1)) / chunk_size;
  393. out.write((const char *) &ncall, sizeof(ncall));
  394. const int32_t nval = stat.values.size();
  395. const int32_t nmat = stat.counts.size();
  396. out.write((const char *) &nval, sizeof(nval));
  397. if (nval > 0 && nmat > 0) {
  398. std::vector<float> tmp(nval);
  399. for (int32_t i = 0; i < nval; i++) {
  400. float count = static_cast<float>(stat.counts[i / (nval / nmat)]);
  401. float value = stat.values[i];
  402. if (count == 0.0f) {
  403. // store 1 for partial data
  404. value = 1.0f;
  405. count = 1.0f;
  406. }
  407. tmp[i] = (value / count) * static_cast<float>(ncall);
  408. }
  409. out.write((const char *) tmp.data(), nval * sizeof(float));
  410. }
  411. }
  412. // Write the number of call the matrix was computed with
  413. out.write((const char *) &m_last_chunk, sizeof(m_last_chunk));
  414. // Write the input filename at the end of the file to later on specify it in quantize
  415. {
  416. const char * dataset_file = m_params.prompt_file.c_str();
  417. int32_t len = m_params.prompt_file.size();
  418. // When there is no prompt but there were other imatrix files loaded, use the last dataset
  419. if (m_params.prompt_file.empty() && !m_datasets.empty()) {
  420. const std::string & dataset_str = m_datasets[m_datasets.size() - 1];
  421. dataset_file = dataset_str.c_str();
  422. len = dataset_str.size();
  423. }
  424. out.write((const char *) &len, sizeof(len));
  425. out.write(dataset_file, len);
  426. }
  427. LOGV(1, "\n");
  428. LOG_DBGV(1, "%s: stored collected data after %d chunks in %s\n", __func__, m_last_chunk, fname.c_str());
  429. }
  430. void IMatrixCollector::save_imatrix(int32_t n_chunk) const {
  431. auto fname = m_params.out_file;
  432. // TODO: use the new format in more cases
  433. if (!string_ends_with(fname, ".gguf")) {
  434. LOG_WRN("\n%s: saving to legacy imatrix format because output suffix is not .gguf\n", __func__);
  435. this->save_imatrix_legacy(n_chunk);
  436. return;
  437. }
  438. if (n_chunk > 0) {
  439. fname += ".at_";
  440. fname += std::to_string(n_chunk);
  441. }
  442. // write imatrix entries even if they don't have full data. (can be corrected when reading)
  443. // this can happen with MoE models where some of the experts end up not being exercised by the provided training data
  444. std::vector<std::string> to_store;
  445. size_t data_size = 0;
  446. bool is_first = true; // for printing
  447. for (const auto & kv : m_stats) {
  448. const int n_all = kv.second.counts.size();
  449. int n_zeros = 0;
  450. for (const auto c : kv.second.counts) {
  451. if (c == 0) {
  452. n_zeros++;
  453. }
  454. }
  455. if (n_zeros != 0 && is_first) {
  456. LOG_INF("\n");
  457. is_first = false;
  458. }
  459. if (n_zeros > 0) {
  460. LOG_WRN("%s: entry '%40s' has partial data (%.2f%%)\n", __func__, kv.first.c_str(), 100.0f * (n_all - n_zeros) / n_all);
  461. }
  462. to_store.push_back(kv.first);
  463. data_size += GGML_PAD(ggml_tensor_overhead() + sizeof(float) * kv.second.values.size(), GGML_MEM_ALIGN);
  464. data_size += GGML_PAD(ggml_tensor_overhead() + sizeof(float) * kv.second.counts.size(), GGML_MEM_ALIGN);
  465. }
  466. // deterministic tensor name order
  467. std::sort(to_store.begin(), to_store.end());
  468. struct ggml_init_params params = {
  469. /* .mem_size = */ data_size,
  470. /* .mem_buffer = */ NULL,
  471. /* .no_alloc = */ false,
  472. };
  473. struct ggml_context * ctx = ggml_init(params);
  474. struct gguf_context * ctx_gguf = gguf_init_empty();
  475. {
  476. std::vector<const char *> datasets;
  477. datasets.reserve(m_datasets.size() + 1);
  478. for (size_t i = 0; i < m_datasets.size(); ++i) {
  479. datasets.push_back(m_datasets[i].c_str());
  480. }
  481. if (!m_params.prompt_file.empty()) {
  482. datasets.push_back(m_params.prompt_file.c_str());
  483. }
  484. gguf_set_val_str(ctx_gguf, "general.type", "imatrix");
  485. // Write the dataset paths
  486. gguf_set_arr_str(ctx_gguf, LLM_KV_IMATRIX_DATASETS, datasets.data(), datasets.size());
  487. // Write the number of chunks the matrix was computed with
  488. gguf_set_val_u32(ctx_gguf, LLM_KV_IMATRIX_CHUNK_COUNT, m_last_chunk);
  489. gguf_set_val_u32(ctx_gguf, LLM_KV_IMATRIX_CHUNK_SIZE, m_params.n_ctx / m_params.n_parallel);
  490. }
  491. for (const auto & name : to_store) {
  492. const auto & stat = m_stats.at(name);
  493. const int32_t nval = (int32_t) stat.values.size();
  494. const int32_t nmat = (int32_t) stat.counts.size();
  495. if (nval > 0 && nmat > 0) {
  496. struct ggml_tensor * in_sum2 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, nval / nmat, nmat);
  497. struct ggml_tensor * counts = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 1, nmat);
  498. ggml_format_name(in_sum2, "%s.in_sum2", name.c_str());
  499. ggml_format_name(counts, "%s.counts", name.c_str());
  500. for (int32_t j = 0; j < nval; ++j) {
  501. ((float *) in_sum2->data)[j] = (float) stat.values[j];
  502. }
  503. for (int32_t j = 0; j < nmat; ++j) {
  504. ((float *) counts->data)[j] = (float) stat.counts[j];
  505. }
  506. gguf_add_tensor(ctx_gguf, in_sum2);
  507. gguf_add_tensor(ctx_gguf, counts);
  508. }
  509. }
  510. gguf_write_to_file(ctx_gguf, fname.c_str(), false);
  511. LOGV(1, "\n");
  512. LOG_DBGV(1, "%s: stored collected data after %d chunks in %s\n", __func__, m_last_chunk, fname.c_str());
  513. gguf_free(ctx_gguf);
  514. ggml_free(ctx);
  515. }
  516. bool IMatrixCollector::load_imatrix_legacy(const char * fname) {
  517. std::ifstream in(fname, std::ios::binary);
  518. if (!in) {
  519. LOG_ERR("%s: failed to open %s\n", __func__, fname);
  520. return false;
  521. }
  522. int n_entries;
  523. in.read((char *) &n_entries, sizeof(n_entries));
  524. if (in.fail() || n_entries < 1) {
  525. LOG_ERR("%s: no data in file %s\n", __func__, fname);
  526. return false;
  527. }
  528. // Guess the chunk size because it's not stored in the file
  529. const int32_t chunk_size = m_params.n_ctx / m_params.n_parallel;
  530. for (int i = 0; i < n_entries; ++i) {
  531. int32_t len = 0;
  532. in.read((char *) &len, sizeof(len));
  533. std::vector<char> name_as_vec(len + 1);
  534. in.read((char *) name_as_vec.data(), len);
  535. if (in.fail()) {
  536. LOG_ERR("%s: failed reading name for entry %d from %s\n", __func__, i + 1, fname);
  537. return false;
  538. }
  539. name_as_vec[len] = 0;
  540. std::string name{ name_as_vec.data() };
  541. auto & e = m_stats[std::move(name)];
  542. int32_t ncall = 0;
  543. in.read((char *) &ncall, sizeof(ncall));
  544. int32_t nval = 0;
  545. in.read((char *) &nval, sizeof(nval));
  546. if (in.fail() || nval < 1) {
  547. LOG_ERR("%s: failed reading number of values for entry %d\n", __func__, i);
  548. m_stats = {};
  549. return false;
  550. }
  551. if (e.values.empty()) {
  552. e.values.resize(nval, 0.0f);
  553. e.counts.resize(1, 0);
  554. }
  555. std::vector<float> tmp(nval);
  556. in.read((char *) tmp.data(), nval * sizeof(float));
  557. if (in.fail()) {
  558. LOG_ERR("%s: failed reading data for entry %d\n", __func__, i);
  559. m_stats = {};
  560. return false;
  561. }
  562. // Recreate the state as expected by save_imatrix(), and correct for weighted sum.
  563. for (int i = 0; i < nval; i++) {
  564. e.values[i] += tmp[i] * chunk_size;
  565. }
  566. // The legacy format doesn't distinguish the counts for different experts
  567. for (size_t j = 0; j < e.counts.size(); ++j) {
  568. e.counts[j] += ncall * chunk_size;
  569. }
  570. }
  571. {
  572. // TODO: extract into its own method; this is also used by the GGUF-based format
  573. // Calculate the last chunk count
  574. int64_t max_count = 0;
  575. for (const auto & stats : m_stats) {
  576. for (int64_t count : stats.second.counts) {
  577. if (count > max_count) {
  578. max_count = count;
  579. }
  580. }
  581. }
  582. m_last_chunk = max_count / (chunk_size);
  583. }
  584. {
  585. // Read the number of calls the matrix was computed with
  586. int32_t n_calls;
  587. in.read((char *) &n_calls, sizeof(n_calls));
  588. // ignore it because it's not important
  589. }
  590. // Read the dataset path to include it when writing to GGUF
  591. if (!in.fail()){
  592. int32_t len = 0;
  593. in.read((char *) &len, sizeof(len));
  594. if (!in.fail()) {
  595. std::vector<char> dataset;
  596. dataset.resize(len + 1, 0);
  597. in.read(dataset.data(), len);
  598. if (!in.fail()) {
  599. m_datasets.push_back(dataset.data());
  600. }
  601. }
  602. }
  603. return true;
  604. }
  605. // Using GGUF as the file format, for greater extensibility
  606. bool IMatrixCollector::load_imatrix(const char * file_name) {
  607. struct ggml_context * ctx = nullptr;
  608. struct gguf_init_params meta_gguf_params = {
  609. /* .no_alloc = */ false, // the data is needed
  610. /* .ctx = */ &ctx,
  611. };
  612. struct gguf_context * ctx_gguf = gguf_init_from_file(file_name, meta_gguf_params);
  613. if (!ctx_gguf) {
  614. return this->load_imatrix_legacy(file_name);
  615. }
  616. const int32_t n_entries = gguf_get_n_tensors(ctx_gguf);
  617. if (n_entries < 1) {
  618. LOG_ERR("%s: no data in file %s\n", __func__, file_name);
  619. gguf_free(ctx_gguf);
  620. ggml_free(ctx);
  621. return false;
  622. }
  623. const int64_t datasets_key = gguf_find_key(ctx_gguf, LLM_KV_IMATRIX_DATASETS);
  624. if (datasets_key != -1 && gguf_get_arr_type(ctx_gguf, datasets_key) == GGUF_TYPE_STRING) {
  625. const int64_t n = gguf_get_arr_n(ctx_gguf, datasets_key);
  626. m_datasets.reserve(m_datasets.size() + n);
  627. for (int64_t i = 0; i < n; ++i) {
  628. m_datasets.push_back(gguf_get_arr_str(ctx_gguf, datasets_key, i));
  629. }
  630. }
  631. const std::string in_sum2_suffix{ ".in_sum2" };
  632. const std::string counts_suffix{ ".counts" };
  633. // Could re-use m_stats instead, but this allows
  634. // checking for completeness of *each* loaded imatrix file
  635. // and also makes it easier to re-use a similar implementation in quantize.cpp
  636. // Using an ordered map to get a deterministic iteration order.
  637. std::map<std::string, std::pair<struct ggml_tensor *, struct ggml_tensor *>> sums_counts_for;
  638. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  639. std::string name = cur->name;
  640. if (name.empty()) { continue; }
  641. if (string_remove_suffix(name, in_sum2_suffix)) {
  642. // in_sum2
  643. sums_counts_for[std::move(name)].first = cur;
  644. } else if (string_remove_suffix(name, counts_suffix)) {
  645. // counts
  646. sums_counts_for[std::move(name)].second = cur;
  647. } else {
  648. // ignore other tensors
  649. }
  650. }
  651. for (const auto & sc : sums_counts_for) {
  652. const std::string & name = sc.first;
  653. const struct ggml_tensor * in_sum2 = sc.second.first;
  654. const struct ggml_tensor * counts = sc.second.second;
  655. if (!in_sum2 || !counts) {
  656. LOG_ERR("%s: mismatched sums and counts for %s\n", __func__, name.c_str());
  657. gguf_free(ctx_gguf);
  658. ggml_free(ctx);
  659. return false;
  660. }
  661. auto & e = m_stats[name];
  662. int64_t nval = ggml_nelements(in_sum2);
  663. if (e.values.empty()) {
  664. e.values.resize(nval, 0.0f);
  665. } else if ((size_t) nval != e.values.size()) {
  666. LOG_ERR("%s: mismatched sums size for %s: %zu != %zu\n", __func__, name.c_str(), (size_t) nval, e.values.size());
  667. gguf_free(ctx_gguf);
  668. ggml_free(ctx);
  669. return false;
  670. }
  671. int64_t ncounts = ggml_nelements(counts);
  672. if (e.counts.empty()) {
  673. e.counts.resize(ncounts, 0);
  674. } else if (e.counts.size() == 1 && ncounts > 1) {
  675. // broadcast, when loading an old imatrix
  676. e.counts.resize(ncounts, e.counts[0]);
  677. } else if ((size_t) ncounts != e.counts.size()) {
  678. LOG_ERR("%s: mismatched counts size for %s: %zu != %zu\n", __func__, name.c_str(), (size_t) ncounts, e.counts.size());
  679. gguf_free(ctx_gguf);
  680. ggml_free(ctx);
  681. return false;
  682. }
  683. // Recreate the state as expected by save_imatrix()
  684. for (int64_t j = 0; j < nval; j++) {
  685. e.values[j] += ((const float *) in_sum2->data)[j];
  686. }
  687. for (int64_t j = 0; j < ncounts; j++) {
  688. e.counts[j] += std::lround(((const float *) counts->data)[j]);
  689. }
  690. }
  691. // TODO: extract into its own method; this is also used by the legacy format
  692. // Calculate the last chunk count
  693. int64_t max_count = 0;
  694. for (const auto & stats : m_stats) {
  695. for (int64_t count : stats.second.counts) {
  696. if (count > max_count) {
  697. max_count = count;
  698. }
  699. }
  700. }
  701. m_last_chunk = max_count / (m_params.n_ctx / m_params.n_parallel);
  702. gguf_free(ctx_gguf);
  703. ggml_free(ctx);
  704. return true;
  705. }
  706. static IMatrixCollector g_collector;
  707. static bool ik_collect_imatrix(struct ggml_tensor * t, bool ask, void * user_data) {
  708. return g_collector.collect_imatrix(t, ask, user_data);
  709. }
  710. struct results_log_softmax {
  711. double log_softmax;
  712. float logit;
  713. float prob;
  714. };
  715. static std::vector<float> softmax(const std::vector<float> & logits) {
  716. std::vector<float> probs(logits.size());
  717. float max_logit = logits[0];
  718. for (float v : logits) {
  719. max_logit = std::max(max_logit, v);
  720. }
  721. double sum_exp = 0.0;
  722. for (size_t i = 0; i < logits.size(); i++) {
  723. // Subtract the maximum logit value from the current logit value for numerical stability
  724. const float logit = logits[i] - max_logit;
  725. const float exp_logit = expf(logit);
  726. sum_exp += exp_logit;
  727. probs[i] = exp_logit;
  728. }
  729. for (size_t i = 0; i < probs.size(); i++) {
  730. probs[i] /= sum_exp;
  731. }
  732. return probs;
  733. }
  734. static results_log_softmax log_softmax(int n_vocab, const float * logits, int tok) {
  735. float max_logit = logits[0];
  736. for (int i = 1; i < n_vocab; ++i) {
  737. max_logit = std::max(max_logit, logits[i]);
  738. }
  739. double sum_exp = 0.0;
  740. for (int i = 0; i < n_vocab; ++i) {
  741. sum_exp += expf(logits[i] - max_logit);
  742. }
  743. return {logits[tok] - max_logit - log(sum_exp), logits[tok], expf(logits[tok] - max_logit) / (float) sum_exp};
  744. }
  745. static void process_logits(
  746. int n_vocab, const float * logits, const int * tokens, int n_token, std::vector<std::thread> & workers,
  747. double & nll, double & nll2, float * logit_history, float * prob_history) {
  748. std::mutex mutex;
  749. int counter = 0;
  750. auto compute = [&mutex, &counter, &nll, &nll2, logit_history, prob_history, n_vocab, logits, tokens, n_token] () {
  751. double local_nll = 0;
  752. double local_nll2 = 0;
  753. while (true) {
  754. std::unique_lock<std::mutex> lock(mutex);
  755. int i = counter++;
  756. if (i >= n_token) {
  757. nll += local_nll; nll2 += local_nll2;
  758. break;
  759. }
  760. lock.unlock();
  761. const results_log_softmax results = log_softmax(n_vocab, logits + i*n_vocab, tokens[i+1]);
  762. const double v = -results.log_softmax;
  763. local_nll += v;
  764. local_nll2 += v*v;
  765. logit_history[i] = results.logit;
  766. prob_history[i] = results.prob;
  767. }
  768. };
  769. for (auto & w : workers) {
  770. w = std::thread(compute);
  771. }
  772. compute();
  773. for (auto & w : workers) {
  774. w.join();
  775. }
  776. }
  777. static bool compute_imatrix(llama_context * ctx, const common_params & params, const int32_t n_ctx) {
  778. const llama_model * model = llama_get_model(ctx);
  779. const llama_vocab * vocab = llama_model_get_vocab(model);
  780. const bool add_bos = llama_vocab_get_add_bos(vocab);
  781. GGML_ASSERT(!llama_vocab_get_add_eos(vocab));
  782. auto tim1 = std::chrono::high_resolution_clock::now();
  783. LOG_INF("%s: tokenizing the input ..\n", __func__);
  784. std::vector<llama_token> tokens = common_tokenize(ctx, params.prompt, true, params.parse_special);
  785. auto tim2 = std::chrono::high_resolution_clock::now();
  786. LOG_INF("%s: tokenization took %g ms\n",__func__,1e-3*std::chrono::duration_cast<std::chrono::microseconds>(tim2-tim1).count());
  787. if (params.i_chunk > 0) {
  788. if (size_t((params.i_chunk + 2)*n_ctx) >= tokens.size()) {
  789. LOG_ERR("%s: there will be not enough tokens left after removing %d chunks\n", __func__, params.i_chunk);
  790. return false;
  791. }
  792. LOG_INF("%s: removing initial %d chunks (%d tokens)\n", __func__, params.i_chunk, params.i_chunk*n_ctx);
  793. tokens.erase(tokens.begin(), tokens.begin() + params.i_chunk*n_ctx);
  794. }
  795. if (int(tokens.size()) < 2*n_ctx) {
  796. LOG_ERR("%s: you need at least %d tokens for a context of %d tokens\n", __func__, 2*n_ctx, n_ctx);
  797. LOG_ERR("%s: the data file you provided tokenizes to only %zu tokens\n", __func__, tokens.size());
  798. return false;
  799. }
  800. std::vector<float> logit_history;
  801. std::vector<float> prob_history;
  802. if (params.compute_ppl) {
  803. logit_history.resize(tokens.size());
  804. prob_history.resize(tokens.size());
  805. }
  806. const int n_chunk_max = tokens.size() / n_ctx;
  807. const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max);
  808. const int n_vocab = llama_vocab_n_tokens(vocab);
  809. const int n_batch = params.n_batch;
  810. int count = 0;
  811. double nll = 0.0;
  812. double nll2 = 0.0;
  813. const int num_batches = (n_ctx + n_batch - 1) / n_batch;
  814. const int n_seq = std::max(1, n_batch / n_ctx);
  815. GGML_ASSERT(n_batch < n_ctx || n_batch % n_ctx == 0);
  816. GGML_ASSERT(params.n_ctx == n_seq * n_ctx);
  817. llama_batch batch = llama_batch_init(std::min(n_batch, n_ctx*n_seq), 0, 1);
  818. std::vector<float> logits;
  819. if (params.compute_ppl && num_batches > 1) {
  820. logits.reserve((size_t)n_ctx * n_vocab);
  821. }
  822. 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);
  823. std::vector<std::thread> workers(std::thread::hardware_concurrency() - 1);
  824. for (int i = 0; i < n_chunk; i += n_seq) {
  825. const int start = i * n_ctx;
  826. const int end = start + n_ctx;
  827. const int n_seq_batch = std::min(n_seq, n_chunk - i);
  828. const auto t_start = std::chrono::high_resolution_clock::now();
  829. // clear the KV cache
  830. llama_memory_clear(llama_get_memory(ctx), true);
  831. for (int j = 0; j < num_batches; ++j) {
  832. const int batch_start = start + j * n_batch;
  833. const int batch_size = std::min(end - batch_start, n_batch);
  834. // clear the batch
  835. common_batch_clear(batch);
  836. for (int seq = 0; seq < n_seq_batch; seq++) {
  837. int seq_start = batch_start + seq*n_ctx;
  838. // save original token and restore it after eval
  839. const auto token_org = tokens[seq_start];
  840. // add BOS token for the first batch of each chunk
  841. if (add_bos && j == 0) {
  842. tokens[seq_start] = llama_vocab_bos(vocab);
  843. }
  844. for (int k = 0; k < batch_size; ++k) {
  845. // NOTE: specifying all logits to get activations for the output.weight tensor
  846. // and also for the perplexity calculation.
  847. // TODO: only get outputs when (params.process_output || params.compute_ppl)
  848. // (not possible when this skips FFN computation of the last layer)
  849. common_batch_add(batch, tokens[seq_start + k], j*n_batch + k, { seq }, true);
  850. }
  851. // restore the original token in case it was set to BOS
  852. tokens[seq_start] = token_org;
  853. }
  854. if (llama_decode(ctx, batch)) {
  855. LOG_ERR("%s : failed to eval\n", __func__);
  856. llama_batch_free(batch);
  857. return false;
  858. }
  859. if (params.compute_ppl && num_batches > 1) {
  860. const auto * batch_logits = llama_get_logits(ctx);
  861. logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
  862. }
  863. }
  864. if (i == 0) {
  865. llama_synchronize(ctx);
  866. const auto t_end = std::chrono::high_resolution_clock::now();
  867. const float t_total = std::chrono::duration<float>(t_end - t_start).count();
  868. LOG_INF("%s: %.2f seconds per pass - ETA ", __func__, t_total);
  869. int total_seconds = (int)(t_total * n_chunk / n_seq);
  870. if (total_seconds >= 60*60) {
  871. LOG("%d hours ", total_seconds / (60*60));
  872. total_seconds = total_seconds % (60*60);
  873. }
  874. LOG("%.2f minutes\n", total_seconds / 60.0);
  875. }
  876. if (params.compute_ppl) {
  877. const int first = n_ctx/2;
  878. for (int seq = 0; seq < n_seq_batch; seq++) {
  879. const float * all_logits = num_batches > 1 ? logits.data() : llama_get_logits_ith(ctx, seq*n_ctx);
  880. llama_token * tokens_data = tokens.data() + start + seq*n_ctx + first;
  881. process_logits(n_vocab, all_logits + first*n_vocab,
  882. tokens_data, n_ctx - 1 - first,
  883. workers, nll, nll2,
  884. logit_history.data() + start + seq*n_ctx + first,
  885. prob_history.data() + start + seq*n_ctx + first);
  886. count += n_ctx - first - 1;
  887. LOG("[%d]%.4lf,", i + seq + 1, std::exp(nll / count));
  888. }
  889. fflush(stdout);
  890. logits.clear();
  891. }
  892. }
  893. LOG("\n");
  894. if (params.compute_ppl) {
  895. nll2 /= count;
  896. nll /= count;
  897. const double ppl = exp(nll);
  898. nll2 -= nll * nll;
  899. if (nll2 > 0) {
  900. nll2 = sqrt(nll2/(count-1));
  901. LOG("Final estimate: PPL = %.4lf +/- %.5lf\n", ppl, nll2*ppl);
  902. } else {
  903. LOG("Unexpected negative standard deviation of log(prob)\n");
  904. }
  905. }
  906. llama_batch_free(batch);
  907. return true;
  908. }
  909. static bool show_statistics(const common_params & params) {
  910. std::vector<tensor_statistics> ts;
  911. if (params.in_files.empty() || params.in_files.size() > 1) {
  912. LOG_ERR("\nError: a single imatrix file is required to compute tensor statistics\n\n");
  913. return false;
  914. }
  915. if (g_collector.load_imatrix(params.in_files[0].c_str())) {
  916. for (const auto & [name, stats] :g_collector.get_mstats()) {
  917. compute_statistics(ts, name, stats);
  918. }
  919. } else {
  920. LOG_ERR("\nError: %s is not a valid imatrix file\n\n", params.in_files[0].c_str());
  921. return false;
  922. }
  923. if (!ts.empty()) {
  924. compute_cossim(ts);
  925. } else {
  926. LOG_ERR("Error: cannot compute statistics for %s\n\n", params.in_files[0].c_str());
  927. return false;
  928. }
  929. struct tensor_comparer {
  930. bool operator()(const tensor_statistics & a, const tensor_statistics & b) const {
  931. std::string layer, name_a, name_b;
  932. ;
  933. process_tensor_name(a.tensor, layer, name_a);
  934. process_tensor_name(b.tensor, layer, name_b);
  935. return name_a < name_b || (name_a == name_b && a.total_sqract > b.total_sqract);
  936. }
  937. };
  938. std::sort(ts.begin(), ts.end(), tensor_comparer());
  939. struct weighted_stats {
  940. float weighted_bias = 0.0f;
  941. float weighted_zd = 0.0f;
  942. float weighted_cossim = 0.0f;
  943. int total_elements = 0;
  944. };
  945. std::map<int, weighted_stats> ws;
  946. LOG_INF("\nComputing statistics for %s (%d tensors)\n", params.in_files[0].c_str(), static_cast<int>(ts.size()));
  947. LOG_INF("\n%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n", " Layer", " Tensor", " Σ(Act²)",
  948. " Min", " Max", " μ", " σ", " % Active", "N", " Entropy", "E (norm)", "ZD",
  949. " CosSim");
  950. LOG_INF(
  951. "=============================================================================================================="
  952. "===========================================================\n");
  953. for (const auto & tstat : ts) {
  954. std::string layer, name;
  955. process_tensor_name(tstat.tensor, layer, name);
  956. int blk;
  957. try {
  958. blk = std::stoi(layer);
  959. } catch (const std::exception & e) {
  960. blk = -1; // not a block layer
  961. }
  962. LOG_INF("%5s\t%-20s\t%10.2f\t%8.4f\t%11.4f\t%6.2f\t%6.2f\t%8.2f%%\t%6d\t%10.4f\t%6.2f%%\t%10.2f%%\t%8.4f\n",
  963. layer.c_str(), name.c_str(), tstat.total_sqract, tstat.min_sqract, tstat.max_sqract, tstat.mean_sqract,
  964. tstat.stddev, tstat.active * 100.0f, tstat.elements, tstat.entropy,
  965. 100.0f * (tstat.entropy / std::log2(tstat.elements)), 100.0f * tstat.zd, tstat.cossim);
  966. const float weighted_bias = tstat.elements * tstat.total_sqract;
  967. const float weighted_zd = tstat.elements * tstat.zd;
  968. const float weighted_cossim = tstat.elements * tstat.cossim;
  969. if (ws.find(blk) != ws.end()) {
  970. ws[blk].weighted_bias += weighted_bias;
  971. ws[blk].weighted_zd += weighted_zd;
  972. ws[blk].weighted_cossim += weighted_cossim;
  973. ws[blk].total_elements += tstat.elements;
  974. } else {
  975. weighted_stats temp_ws;
  976. temp_ws.weighted_bias = weighted_bias;
  977. temp_ws.weighted_zd = weighted_zd;
  978. temp_ws.weighted_cossim = weighted_cossim;
  979. temp_ws.total_elements = tstat.elements;
  980. ws[blk] = temp_ws;
  981. }
  982. }
  983. const int layers = std::count_if(ws.begin(), ws.end(), [](const auto & kv) { return kv.first >= 0; });
  984. LOG_INF("\nComputing weighted average statistics per layer (%d layers)\n", layers);
  985. LOG_INF("\n%s\t%s\t%s\t%s\n", " Layer", " μΣ(Act²)", " μZD", "μCosSim");
  986. LOG_INF("================================================\n");
  987. for (const auto & [first, second] : ws) {
  988. const auto & layer = first;
  989. const auto & stats = second;
  990. if (stats.total_elements == 0) {
  991. continue;
  992. }
  993. if (layer >= 0) {
  994. const float bias = stats.weighted_bias / stats.total_elements;
  995. const float zd = stats.weighted_zd / stats.total_elements;
  996. const float cossim = stats.weighted_cossim / stats.total_elements;
  997. LOG_INF("%5d\t%14.2f\t%10.4f%%\t%6.4f\n", layer, bias, 100.0f * zd, cossim);
  998. }
  999. }
  1000. LOG_INF("\n");
  1001. return true;
  1002. }
  1003. int main(int argc, char ** argv) {
  1004. common_params params;
  1005. params.out_file = "imatrix.gguf";
  1006. params.n_ctx = 512;
  1007. params.escape = false;
  1008. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_IMATRIX, print_usage)) {
  1009. return 1;
  1010. }
  1011. if (params.show_statistics) {
  1012. if (!show_statistics(params)) {
  1013. return 1;
  1014. }
  1015. return 0;
  1016. }
  1017. common_init();
  1018. const int32_t n_ctx = params.n_ctx;
  1019. if (n_ctx <= 0) {
  1020. LOG_ERR("%s: imatrix tool requires '--ctx-size' > 0\n", __func__);
  1021. return 1;
  1022. }
  1023. {
  1024. const int32_t n_seq = std::max(1, params.n_batch / n_ctx);
  1025. const int32_t n_kv = n_seq * n_ctx;
  1026. params.n_parallel = n_seq;
  1027. params.n_ctx = n_kv;
  1028. params.n_batch = std::min(params.n_batch, n_kv);
  1029. }
  1030. g_collector.set_params(params);
  1031. for (const auto & in_file : params.in_files) {
  1032. LOG_INF("%s : loading imatrix from '%s'\n", __func__, in_file.c_str());
  1033. if (!g_collector.load_imatrix(in_file.c_str())) {
  1034. LOG_ERR("%s : failed to load %s\n", __func__, in_file.c_str());
  1035. return 1;
  1036. }
  1037. }
  1038. if (params.prompt.empty()) {
  1039. LOG_INF("No prompt provided; combining precomputed matrices only.\n");
  1040. if (params.in_files.empty()) {
  1041. LOG_ERR("Error: No prompt provided and no precomputed matrices (--in-file) to combine.\n");
  1042. return 1;
  1043. }
  1044. if (params.in_files.size() == 1) {
  1045. LOG_INF("%s : saving imatrix to '%s'\n", __func__, params.out_file.c_str());
  1046. } else if (params.in_files.size() > 1) {
  1047. LOG_INF("%s : saving combined imatrix to '%s'\n", __func__, params.out_file.c_str());
  1048. }
  1049. g_collector.save_imatrix();
  1050. return 0;
  1051. }
  1052. llama_backend_init();
  1053. llama_numa_init(params.numa);
  1054. // pass the callback to the backend scheduler
  1055. // it will be executed for each node during the graph computation
  1056. params.cb_eval = ik_collect_imatrix;
  1057. params.cb_eval_user_data = NULL;
  1058. params.warmup = false;
  1059. // init
  1060. common_init_result llama_init = common_init_from_params(params);
  1061. llama_model * model = llama_init.model.get();
  1062. llama_context * ctx = llama_init.context.get();
  1063. if (model == nullptr || ctx == nullptr) {
  1064. LOG_ERR("%s : failed to init\n", __func__);
  1065. return 1;
  1066. }
  1067. const int n_ctx_train = llama_model_n_ctx_train(model);
  1068. if (params.n_ctx > n_ctx_train) {
  1069. LOG_WRN("%s: model was trained on only %d context tokens (%d specified)\n",
  1070. __func__, n_ctx_train, params.n_ctx);
  1071. }
  1072. // print system information
  1073. {
  1074. LOG_INF("\n");
  1075. LOG_INF("%s\n", common_params_get_system_info(params).c_str());
  1076. }
  1077. if (!compute_imatrix(ctx, params, n_ctx)) {
  1078. return 1;
  1079. }
  1080. g_collector.save_imatrix();
  1081. LOG("\n");
  1082. llama_perf_context_print(ctx);
  1083. llama_backend_free();
  1084. return 0;
  1085. }