imatrix.cpp 47 KB

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