imatrix.cpp 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298
  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. bool use_legacy_format = m_params.imat_dat;
  446. if (use_legacy_format) {
  447. this->save_imatrix_legacy(n_chunk);
  448. return;
  449. }
  450. // else, default to GGUF imatrix
  451. if (n_chunk > 0) {
  452. fname += ".at_";
  453. fname += std::to_string(n_chunk);
  454. }
  455. // write imatrix entries even if they don't have full data. (can be corrected when reading)
  456. // this can happen with MoE models where some of the experts end up not being exercised by the provided training data
  457. std::vector<std::string> to_store;
  458. size_t data_size = 0;
  459. bool is_first = true; // for printing
  460. for (const auto & kv : m_stats) {
  461. const int n_all = kv.second.counts.size();
  462. int n_zeros = 0;
  463. for (const auto c : kv.second.counts) {
  464. if (c == 0) {
  465. n_zeros++;
  466. }
  467. }
  468. if (n_zeros != 0 && is_first) {
  469. LOG_INF("\n");
  470. is_first = false;
  471. }
  472. if (n_zeros > 0) {
  473. LOG_WRN("%s: entry '%40s' has partial data (%.2f%%)\n", __func__, kv.first.c_str(), 100.0f * (n_all - n_zeros) / n_all);
  474. }
  475. to_store.push_back(kv.first);
  476. data_size += GGML_PAD(ggml_tensor_overhead() + sizeof(float) * kv.second.values.size(), GGML_MEM_ALIGN);
  477. data_size += GGML_PAD(ggml_tensor_overhead() + sizeof(float) * kv.second.counts.size(), GGML_MEM_ALIGN);
  478. }
  479. // deterministic tensor name order
  480. std::sort(to_store.begin(), to_store.end());
  481. struct ggml_init_params params = {
  482. /* .mem_size = */ data_size,
  483. /* .mem_buffer = */ NULL,
  484. /* .no_alloc = */ false,
  485. };
  486. struct ggml_context * ctx = ggml_init(params);
  487. struct gguf_context * ctx_gguf = gguf_init_empty();
  488. {
  489. std::vector<const char *> datasets;
  490. datasets.reserve(m_datasets.size() + 1);
  491. for (size_t i = 0; i < m_datasets.size(); ++i) {
  492. datasets.push_back(m_datasets[i].c_str());
  493. }
  494. if (!m_params.prompt_file.empty()) {
  495. datasets.push_back(m_params.prompt_file.c_str());
  496. }
  497. gguf_set_val_str(ctx_gguf, "general.type", "imatrix");
  498. // Write the dataset paths
  499. gguf_set_arr_str(ctx_gguf, LLM_KV_IMATRIX_DATASETS, datasets.data(), datasets.size());
  500. // Write the number of chunks the matrix was computed with
  501. gguf_set_val_u32(ctx_gguf, LLM_KV_IMATRIX_CHUNK_COUNT, m_last_chunk);
  502. gguf_set_val_u32(ctx_gguf, LLM_KV_IMATRIX_CHUNK_SIZE, m_params.n_ctx / m_params.n_parallel);
  503. }
  504. for (const auto & name : to_store) {
  505. const auto & stat = m_stats.at(name);
  506. const int32_t nval = (int32_t) stat.values.size();
  507. const int32_t nmat = (int32_t) stat.counts.size();
  508. if (nval > 0 && nmat > 0) {
  509. struct ggml_tensor * in_sum2 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, nval / nmat, nmat);
  510. struct ggml_tensor * counts = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 1, nmat);
  511. ggml_format_name(in_sum2, "%s.in_sum2", name.c_str());
  512. ggml_format_name(counts, "%s.counts", name.c_str());
  513. for (int32_t j = 0; j < nval; ++j) {
  514. ((float *) in_sum2->data)[j] = (float) stat.values[j];
  515. }
  516. for (int32_t j = 0; j < nmat; ++j) {
  517. ((float *) counts->data)[j] = (float) stat.counts[j];
  518. }
  519. gguf_add_tensor(ctx_gguf, in_sum2);
  520. gguf_add_tensor(ctx_gguf, counts);
  521. }
  522. }
  523. gguf_write_to_file(ctx_gguf, fname.c_str(), false);
  524. LOGV(1, "\n");
  525. LOG_DBGV(1, "%s: stored collected data after %d chunks in %s\n", __func__, m_last_chunk, fname.c_str());
  526. gguf_free(ctx_gguf);
  527. ggml_free(ctx);
  528. }
  529. bool IMatrixCollector::load_imatrix_legacy(const char * fname) {
  530. std::ifstream in(fname, std::ios::binary);
  531. if (!in) {
  532. LOG_ERR("%s: failed to open %s\n", __func__, fname);
  533. return false;
  534. }
  535. int n_entries;
  536. in.read((char *) &n_entries, sizeof(n_entries));
  537. if (in.fail() || n_entries < 1) {
  538. LOG_ERR("%s: no data in file %s\n", __func__, fname);
  539. return false;
  540. }
  541. // Guess the chunk size because it's not stored in the file
  542. const int32_t chunk_size = m_params.n_ctx / m_params.n_parallel;
  543. for (int i = 0; i < n_entries; ++i) {
  544. int32_t len = 0;
  545. in.read((char *) &len, sizeof(len));
  546. std::vector<char> name_as_vec(len + 1);
  547. in.read((char *) name_as_vec.data(), len);
  548. if (in.fail()) {
  549. LOG_ERR("%s: failed reading name for entry %d from %s\n", __func__, i + 1, fname);
  550. return false;
  551. }
  552. name_as_vec[len] = 0;
  553. std::string name{ name_as_vec.data() };
  554. auto & e = m_stats[std::move(name)];
  555. int32_t ncall = 0;
  556. in.read((char *) &ncall, sizeof(ncall));
  557. int32_t nval = 0;
  558. in.read((char *) &nval, sizeof(nval));
  559. if (in.fail() || nval < 1) {
  560. LOG_ERR("%s: failed reading number of values for entry %d\n", __func__, i);
  561. m_stats = {};
  562. return false;
  563. }
  564. if (e.values.empty()) {
  565. e.values.resize(nval, 0.0f);
  566. e.counts.resize(1, 0);
  567. }
  568. std::vector<float> tmp(nval);
  569. in.read((char *) tmp.data(), nval * sizeof(float));
  570. if (in.fail()) {
  571. LOG_ERR("%s: failed reading data for entry %d\n", __func__, i);
  572. m_stats = {};
  573. return false;
  574. }
  575. // Recreate the state as expected by save_imatrix(), and correct for weighted sum.
  576. for (int i = 0; i < nval; i++) {
  577. e.values[i] += tmp[i] * chunk_size;
  578. }
  579. // The legacy format doesn't distinguish the counts for different experts
  580. for (size_t j = 0; j < e.counts.size(); ++j) {
  581. e.counts[j] += ncall * chunk_size;
  582. }
  583. }
  584. {
  585. // TODO: extract into its own method; this is also used by the GGUF-based format
  586. // Calculate the last chunk count
  587. int64_t max_count = 0;
  588. for (const auto & stats : m_stats) {
  589. for (int64_t count : stats.second.counts) {
  590. if (count > max_count) {
  591. max_count = count;
  592. }
  593. }
  594. }
  595. m_last_chunk = max_count / (chunk_size);
  596. }
  597. {
  598. // Read the number of calls the matrix was computed with
  599. int32_t n_calls;
  600. in.read((char *) &n_calls, sizeof(n_calls));
  601. // ignore it because it's not important
  602. }
  603. // Read the dataset path to include it when writing to GGUF
  604. if (!in.fail()){
  605. int32_t len = 0;
  606. in.read((char *) &len, sizeof(len));
  607. if (!in.fail()) {
  608. std::vector<char> dataset;
  609. dataset.resize(len + 1, 0);
  610. in.read(dataset.data(), len);
  611. if (!in.fail()) {
  612. m_datasets.push_back(dataset.data());
  613. }
  614. }
  615. }
  616. return true;
  617. }
  618. // Using GGUF as the file format, for greater extensibility
  619. bool IMatrixCollector::load_imatrix(const char * file_name) {
  620. struct ggml_context * ctx = nullptr;
  621. struct gguf_init_params meta_gguf_params = {
  622. /* .no_alloc = */ false, // the data is needed
  623. /* .ctx = */ &ctx,
  624. };
  625. struct gguf_context * ctx_gguf = gguf_init_from_file(file_name, meta_gguf_params);
  626. if (!ctx_gguf) {
  627. return this->load_imatrix_legacy(file_name);
  628. }
  629. const int32_t n_entries = gguf_get_n_tensors(ctx_gguf);
  630. if (n_entries < 1) {
  631. LOG_ERR("%s: no data in file %s\n", __func__, file_name);
  632. gguf_free(ctx_gguf);
  633. ggml_free(ctx);
  634. return false;
  635. }
  636. const int64_t datasets_key = gguf_find_key(ctx_gguf, LLM_KV_IMATRIX_DATASETS);
  637. if (datasets_key != -1 && gguf_get_arr_type(ctx_gguf, datasets_key) == GGUF_TYPE_STRING) {
  638. const int64_t n = gguf_get_arr_n(ctx_gguf, datasets_key);
  639. m_datasets.reserve(m_datasets.size() + n);
  640. for (int64_t i = 0; i < n; ++i) {
  641. m_datasets.push_back(gguf_get_arr_str(ctx_gguf, datasets_key, i));
  642. }
  643. }
  644. const std::string in_sum2_suffix{ ".in_sum2" };
  645. const std::string counts_suffix{ ".counts" };
  646. // Could re-use m_stats instead, but this allows
  647. // checking for completeness of *each* loaded imatrix file
  648. // and also makes it easier to re-use a similar implementation in quantize.cpp
  649. // Using an ordered map to get a deterministic iteration order.
  650. std::map<std::string, std::pair<struct ggml_tensor *, struct ggml_tensor *>> sums_counts_for;
  651. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  652. std::string name = cur->name;
  653. if (name.empty()) { continue; }
  654. if (string_remove_suffix(name, in_sum2_suffix)) {
  655. // in_sum2
  656. sums_counts_for[std::move(name)].first = cur;
  657. } else if (string_remove_suffix(name, counts_suffix)) {
  658. // counts
  659. sums_counts_for[std::move(name)].second = cur;
  660. } else {
  661. // ignore other tensors
  662. }
  663. }
  664. for (const auto & sc : sums_counts_for) {
  665. const std::string & name = sc.first;
  666. const struct ggml_tensor * in_sum2 = sc.second.first;
  667. const struct ggml_tensor * counts = sc.second.second;
  668. if (!in_sum2 || !counts) {
  669. LOG_ERR("%s: mismatched sums and counts for %s\n", __func__, name.c_str());
  670. gguf_free(ctx_gguf);
  671. ggml_free(ctx);
  672. return false;
  673. }
  674. auto & e = m_stats[name];
  675. int64_t nval = ggml_nelements(in_sum2);
  676. if (e.values.empty()) {
  677. e.values.resize(nval, 0.0f);
  678. } else if ((size_t) nval != e.values.size()) {
  679. LOG_ERR("%s: mismatched sums size for %s: %zu != %zu\n", __func__, name.c_str(), (size_t) nval, e.values.size());
  680. gguf_free(ctx_gguf);
  681. ggml_free(ctx);
  682. return false;
  683. }
  684. int64_t ncounts = ggml_nelements(counts);
  685. if (e.counts.empty()) {
  686. e.counts.resize(ncounts, 0);
  687. } else if (e.counts.size() == 1 && ncounts > 1) {
  688. // broadcast, when loading an old imatrix
  689. e.counts.resize(ncounts, e.counts[0]);
  690. } else if ((size_t) ncounts != e.counts.size()) {
  691. LOG_ERR("%s: mismatched counts size for %s: %zu != %zu\n", __func__, name.c_str(), (size_t) ncounts, e.counts.size());
  692. gguf_free(ctx_gguf);
  693. ggml_free(ctx);
  694. return false;
  695. }
  696. // Recreate the state as expected by save_imatrix()
  697. for (int64_t j = 0; j < nval; j++) {
  698. e.values[j] += ((const float *) in_sum2->data)[j];
  699. }
  700. for (int64_t j = 0; j < ncounts; j++) {
  701. e.counts[j] += std::lround(((const float *) counts->data)[j]);
  702. }
  703. }
  704. // TODO: extract into its own method; this is also used by the legacy format
  705. // Calculate the last chunk count
  706. int64_t max_count = 0;
  707. for (const auto & stats : m_stats) {
  708. for (int64_t count : stats.second.counts) {
  709. if (count > max_count) {
  710. max_count = count;
  711. }
  712. }
  713. }
  714. m_last_chunk = max_count / (m_params.n_ctx / m_params.n_parallel);
  715. gguf_free(ctx_gguf);
  716. ggml_free(ctx);
  717. return true;
  718. }
  719. static IMatrixCollector g_collector;
  720. static bool ik_collect_imatrix(struct ggml_tensor * t, bool ask, void * user_data) {
  721. return g_collector.collect_imatrix(t, ask, user_data);
  722. }
  723. struct results_log_softmax {
  724. double log_softmax;
  725. float logit;
  726. float prob;
  727. };
  728. static std::vector<float> softmax(const std::vector<float> & logits) {
  729. std::vector<float> probs(logits.size());
  730. float max_logit = logits[0];
  731. for (float v : logits) {
  732. max_logit = std::max(max_logit, v);
  733. }
  734. double sum_exp = 0.0;
  735. for (size_t i = 0; i < logits.size(); i++) {
  736. // Subtract the maximum logit value from the current logit value for numerical stability
  737. const float logit = logits[i] - max_logit;
  738. const float exp_logit = expf(logit);
  739. sum_exp += exp_logit;
  740. probs[i] = exp_logit;
  741. }
  742. for (size_t i = 0; i < probs.size(); i++) {
  743. probs[i] /= sum_exp;
  744. }
  745. return probs;
  746. }
  747. static results_log_softmax log_softmax(int n_vocab, const float * logits, int tok) {
  748. float max_logit = logits[0];
  749. for (int i = 1; i < n_vocab; ++i) {
  750. max_logit = std::max(max_logit, logits[i]);
  751. }
  752. double sum_exp = 0.0;
  753. for (int i = 0; i < n_vocab; ++i) {
  754. sum_exp += expf(logits[i] - max_logit);
  755. }
  756. return {logits[tok] - max_logit - log(sum_exp), logits[tok], expf(logits[tok] - max_logit) / (float) sum_exp};
  757. }
  758. static void process_logits(
  759. int n_vocab, const float * logits, const int * tokens, int n_token, std::vector<std::thread> & workers,
  760. double & nll, double & nll2, float * logit_history, float * prob_history) {
  761. std::mutex mutex;
  762. int counter = 0;
  763. auto compute = [&mutex, &counter, &nll, &nll2, logit_history, prob_history, n_vocab, logits, tokens, n_token] () {
  764. double local_nll = 0;
  765. double local_nll2 = 0;
  766. while (true) {
  767. std::unique_lock<std::mutex> lock(mutex);
  768. int i = counter++;
  769. if (i >= n_token) {
  770. nll += local_nll; nll2 += local_nll2;
  771. break;
  772. }
  773. lock.unlock();
  774. const results_log_softmax results = log_softmax(n_vocab, logits + i*n_vocab, tokens[i+1]);
  775. const double v = -results.log_softmax;
  776. local_nll += v;
  777. local_nll2 += v*v;
  778. logit_history[i] = results.logit;
  779. prob_history[i] = results.prob;
  780. }
  781. };
  782. for (auto & w : workers) {
  783. w = std::thread(compute);
  784. }
  785. compute();
  786. for (auto & w : workers) {
  787. w.join();
  788. }
  789. }
  790. static bool compute_imatrix(llama_context * ctx, const common_params & params, const int32_t n_ctx) {
  791. const llama_model * model = llama_get_model(ctx);
  792. const llama_vocab * vocab = llama_model_get_vocab(model);
  793. const bool add_bos = llama_vocab_get_add_bos(vocab);
  794. GGML_ASSERT(!llama_vocab_get_add_eos(vocab));
  795. auto tim1 = std::chrono::high_resolution_clock::now();
  796. LOG_INF("%s: tokenizing the input ..\n", __func__);
  797. std::vector<llama_token> tokens = common_tokenize(ctx, params.prompt, true, params.parse_special);
  798. auto tim2 = std::chrono::high_resolution_clock::now();
  799. LOG_INF("%s: tokenization took %g ms\n",__func__,1e-3*std::chrono::duration_cast<std::chrono::microseconds>(tim2-tim1).count());
  800. if (params.i_chunk > 0) {
  801. if (size_t((params.i_chunk + 2)*n_ctx) >= tokens.size()) {
  802. LOG_ERR("%s: there will be not enough tokens left after removing %d chunks\n", __func__, params.i_chunk);
  803. return false;
  804. }
  805. LOG_INF("%s: removing initial %d chunks (%d tokens)\n", __func__, params.i_chunk, params.i_chunk*n_ctx);
  806. tokens.erase(tokens.begin(), tokens.begin() + params.i_chunk*n_ctx);
  807. }
  808. if (int(tokens.size()) < 2*n_ctx) {
  809. LOG_ERR("%s: you need at least %d tokens for a context of %d tokens\n", __func__, 2*n_ctx, n_ctx);
  810. LOG_ERR("%s: the data file you provided tokenizes to only %zu tokens\n", __func__, tokens.size());
  811. return false;
  812. }
  813. std::vector<float> logit_history;
  814. std::vector<float> prob_history;
  815. if (params.compute_ppl) {
  816. logit_history.resize(tokens.size());
  817. prob_history.resize(tokens.size());
  818. }
  819. const int n_chunk_max = tokens.size() / n_ctx;
  820. const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max);
  821. const int n_vocab = llama_vocab_n_tokens(vocab);
  822. const int n_batch = params.n_batch;
  823. int count = 0;
  824. double nll = 0.0;
  825. double nll2 = 0.0;
  826. const int num_batches = (n_ctx + n_batch - 1) / n_batch;
  827. const int n_seq = std::max(1, n_batch / n_ctx);
  828. GGML_ASSERT(n_batch < n_ctx || n_batch % n_ctx == 0);
  829. GGML_ASSERT(params.n_ctx == n_seq * n_ctx);
  830. llama_batch batch = llama_batch_init(std::min(n_batch, n_ctx*n_seq), 0, 1);
  831. std::vector<float> logits;
  832. if (params.compute_ppl && num_batches > 1) {
  833. logits.reserve((size_t)n_ctx * n_vocab);
  834. }
  835. 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);
  836. std::vector<std::thread> workers(std::thread::hardware_concurrency() - 1);
  837. for (int i = 0; i < n_chunk; i += n_seq) {
  838. const int start = i * n_ctx;
  839. const int end = start + n_ctx;
  840. const int n_seq_batch = std::min(n_seq, n_chunk - i);
  841. const auto t_start = std::chrono::high_resolution_clock::now();
  842. // clear the KV cache
  843. llama_memory_clear(llama_get_memory(ctx), true);
  844. for (int j = 0; j < num_batches; ++j) {
  845. const int batch_start = start + j * n_batch;
  846. const int batch_size = std::min(end - batch_start, n_batch);
  847. // clear the batch
  848. common_batch_clear(batch);
  849. for (int seq = 0; seq < n_seq_batch; seq++) {
  850. int seq_start = batch_start + seq*n_ctx;
  851. // save original token and restore it after eval
  852. const auto token_org = tokens[seq_start];
  853. // add BOS token for the first batch of each chunk
  854. if (add_bos && j == 0) {
  855. tokens[seq_start] = llama_vocab_bos(vocab);
  856. }
  857. for (int k = 0; k < batch_size; ++k) {
  858. // NOTE: specifying all logits to get activations for the output.weight tensor
  859. // and also for the perplexity calculation.
  860. // TODO: only get outputs when (params.process_output || params.compute_ppl)
  861. // (not possible when this skips FFN computation of the last layer)
  862. common_batch_add(batch, tokens[seq_start + k], j*n_batch + k, { seq }, true);
  863. }
  864. // restore the original token in case it was set to BOS
  865. tokens[seq_start] = token_org;
  866. }
  867. if (llama_decode(ctx, batch)) {
  868. LOG_ERR("%s : failed to eval\n", __func__);
  869. llama_batch_free(batch);
  870. return false;
  871. }
  872. if (params.compute_ppl && num_batches > 1) {
  873. const auto * batch_logits = llama_get_logits(ctx);
  874. logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
  875. }
  876. }
  877. if (i == 0) {
  878. llama_synchronize(ctx);
  879. const auto t_end = std::chrono::high_resolution_clock::now();
  880. const float t_total = std::chrono::duration<float>(t_end - t_start).count();
  881. LOG_INF("%s: %.2f seconds per pass - ETA ", __func__, t_total);
  882. int total_seconds = (int)(t_total * n_chunk / n_seq);
  883. if (total_seconds >= 60*60) {
  884. LOG("%d hours ", total_seconds / (60*60));
  885. total_seconds = total_seconds % (60*60);
  886. }
  887. LOG("%.2f minutes\n", total_seconds / 60.0);
  888. }
  889. if (params.compute_ppl) {
  890. const int first = n_ctx/2;
  891. for (int seq = 0; seq < n_seq_batch; seq++) {
  892. const float * all_logits = num_batches > 1 ? logits.data() : llama_get_logits_ith(ctx, seq*n_ctx);
  893. llama_token * tokens_data = tokens.data() + start + seq*n_ctx + first;
  894. process_logits(n_vocab, all_logits + first*n_vocab,
  895. tokens_data, n_ctx - 1 - first,
  896. workers, nll, nll2,
  897. logit_history.data() + start + seq*n_ctx + first,
  898. prob_history.data() + start + seq*n_ctx + first);
  899. count += n_ctx - first - 1;
  900. LOG("[%d]%.4lf,", i + seq + 1, std::exp(nll / count));
  901. }
  902. fflush(stdout);
  903. logits.clear();
  904. }
  905. }
  906. LOG("\n");
  907. if (params.compute_ppl) {
  908. nll2 /= count;
  909. nll /= count;
  910. const double ppl = exp(nll);
  911. nll2 -= nll * nll;
  912. if (nll2 > 0) {
  913. nll2 = sqrt(nll2/(count-1));
  914. LOG("Final estimate: PPL = %.4lf +/- %.5lf\n", ppl, nll2*ppl);
  915. } else {
  916. LOG("Unexpected negative standard deviation of log(prob)\n");
  917. }
  918. }
  919. llama_batch_free(batch);
  920. return true;
  921. }
  922. static bool show_statistics(const common_params & params) {
  923. std::vector<tensor_statistics> ts;
  924. if (params.in_files.empty() || params.in_files.size() > 1) {
  925. LOG_ERR("\nError: a single imatrix file is required to compute tensor statistics\n\n");
  926. return false;
  927. }
  928. if (g_collector.load_imatrix(params.in_files[0].c_str())) {
  929. for (const auto & [name, stats] :g_collector.get_mstats()) {
  930. compute_statistics(ts, name, stats);
  931. }
  932. } else {
  933. LOG_ERR("\nError: %s is not a valid imatrix file\n\n", params.in_files[0].c_str());
  934. return false;
  935. }
  936. if (!ts.empty()) {
  937. compute_cossim(ts);
  938. } else {
  939. LOG_ERR("Error: cannot compute statistics for %s\n\n", params.in_files[0].c_str());
  940. return false;
  941. }
  942. struct tensor_comparer {
  943. bool operator()(const tensor_statistics & a, const tensor_statistics & b) const {
  944. std::string layer, name_a, name_b;
  945. ;
  946. process_tensor_name(a.tensor, layer, name_a);
  947. process_tensor_name(b.tensor, layer, name_b);
  948. return name_a < name_b || (name_a == name_b && a.total_sqract > b.total_sqract);
  949. }
  950. };
  951. std::sort(ts.begin(), ts.end(), tensor_comparer());
  952. struct weighted_stats {
  953. float weighted_bias = 0.0f;
  954. float weighted_zd = 0.0f;
  955. float weighted_cossim = 0.0f;
  956. int total_elements = 0;
  957. };
  958. std::map<int, weighted_stats> ws;
  959. LOG_INF("\nComputing statistics for %s (%d tensors)\n", params.in_files[0].c_str(), static_cast<int>(ts.size()));
  960. 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²)",
  961. " Min", " Max", " μ", " σ", " % Active", "N", " Entropy", "E (norm)", "ZD",
  962. " CosSim");
  963. LOG_INF(
  964. "=============================================================================================================="
  965. "===========================================================\n");
  966. for (const auto & tstat : ts) {
  967. std::string layer, name;
  968. process_tensor_name(tstat.tensor, layer, name);
  969. int blk;
  970. try {
  971. blk = std::stoi(layer);
  972. } catch (const std::exception & e) {
  973. blk = -1; // not a block layer
  974. }
  975. 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",
  976. layer.c_str(), name.c_str(), tstat.total_sqract, tstat.min_sqract, tstat.max_sqract, tstat.mean_sqract,
  977. tstat.stddev, tstat.active * 100.0f, tstat.elements, tstat.entropy,
  978. 100.0f * (tstat.entropy / std::log2(tstat.elements)), 100.0f * tstat.zd, tstat.cossim);
  979. const float weighted_bias = tstat.elements * tstat.total_sqract;
  980. const float weighted_zd = tstat.elements * tstat.zd;
  981. const float weighted_cossim = tstat.elements * tstat.cossim;
  982. if (ws.find(blk) != ws.end()) {
  983. ws[blk].weighted_bias += weighted_bias;
  984. ws[blk].weighted_zd += weighted_zd;
  985. ws[blk].weighted_cossim += weighted_cossim;
  986. ws[blk].total_elements += tstat.elements;
  987. } else {
  988. weighted_stats temp_ws;
  989. temp_ws.weighted_bias = weighted_bias;
  990. temp_ws.weighted_zd = weighted_zd;
  991. temp_ws.weighted_cossim = weighted_cossim;
  992. temp_ws.total_elements = tstat.elements;
  993. ws[blk] = temp_ws;
  994. }
  995. }
  996. const int layers = std::count_if(ws.begin(), ws.end(), [](const auto & kv) { return kv.first >= 0; });
  997. LOG_INF("\nComputing weighted average statistics per layer (%d layers)\n", layers);
  998. LOG_INF("\n%s\t%s\t%s\t%s\n", " Layer", " μΣ(Act²)", " μZD", "μCosSim");
  999. LOG_INF("================================================\n");
  1000. for (const auto & [first, second] : ws) {
  1001. const auto & layer = first;
  1002. const auto & stats = second;
  1003. if (stats.total_elements == 0) {
  1004. continue;
  1005. }
  1006. if (layer >= 0) {
  1007. const float bias = stats.weighted_bias / stats.total_elements;
  1008. const float zd = stats.weighted_zd / stats.total_elements;
  1009. const float cossim = stats.weighted_cossim / stats.total_elements;
  1010. LOG_INF("%5d\t%14.2f\t%10.4f%%\t%6.4f\n", layer, bias, 100.0f * zd, cossim);
  1011. }
  1012. }
  1013. LOG_INF("\n");
  1014. return true;
  1015. }
  1016. int main(int argc, char ** argv) {
  1017. common_params params;
  1018. params.out_file = "imatrix.gguf";
  1019. params.n_ctx = 512;
  1020. params.escape = false;
  1021. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_IMATRIX, print_usage)) {
  1022. return 1;
  1023. }
  1024. if (params.show_statistics) {
  1025. if (!show_statistics(params)) {
  1026. return 1;
  1027. }
  1028. return 0;
  1029. }
  1030. common_init();
  1031. const int32_t n_ctx = params.n_ctx;
  1032. if (n_ctx <= 0) {
  1033. LOG_ERR("%s: imatrix tool requires '--ctx-size' > 0\n", __func__);
  1034. return 1;
  1035. }
  1036. {
  1037. const int32_t n_seq = std::max(1, params.n_batch / n_ctx);
  1038. const int32_t n_kv = n_seq * n_ctx;
  1039. params.n_parallel = n_seq;
  1040. params.n_ctx = n_kv;
  1041. params.n_batch = std::min(params.n_batch, n_kv);
  1042. }
  1043. g_collector.set_params(params);
  1044. for (const auto & in_file : params.in_files) {
  1045. LOG_INF("%s : loading imatrix from '%s'\n", __func__, in_file.c_str());
  1046. if (!g_collector.load_imatrix(in_file.c_str())) {
  1047. LOG_ERR("%s : failed to load %s\n", __func__, in_file.c_str());
  1048. return 1;
  1049. }
  1050. }
  1051. if (params.prompt.empty()) {
  1052. LOG_INF("No prompt provided; combining precomputed matrices only.\n");
  1053. if (params.in_files.empty()) {
  1054. LOG_ERR("Error: No prompt provided and no precomputed matrices (--in-file) to combine.\n");
  1055. return 1;
  1056. }
  1057. if (params.in_files.size() == 1) {
  1058. LOG_INF("%s : saving imatrix to '%s'\n", __func__, params.out_file.c_str());
  1059. } else if (params.in_files.size() > 1) {
  1060. LOG_INF("%s : saving combined imatrix to '%s'\n", __func__, params.out_file.c_str());
  1061. }
  1062. g_collector.save_imatrix();
  1063. return 0;
  1064. }
  1065. llama_backend_init();
  1066. llama_numa_init(params.numa);
  1067. // pass the callback to the backend scheduler
  1068. // it will be executed for each node during the graph computation
  1069. params.cb_eval = ik_collect_imatrix;
  1070. params.cb_eval_user_data = NULL;
  1071. params.warmup = false;
  1072. // init
  1073. common_init_result llama_init = common_init_from_params(params);
  1074. llama_model * model = llama_init.model.get();
  1075. llama_context * ctx = llama_init.context.get();
  1076. if (model == nullptr || ctx == nullptr) {
  1077. LOG_ERR("%s : failed to init\n", __func__);
  1078. return 1;
  1079. }
  1080. const int n_ctx_train = llama_model_n_ctx_train(model);
  1081. if (params.n_ctx > n_ctx_train) {
  1082. LOG_WRN("%s: model was trained on only %d context tokens (%d specified)\n",
  1083. __func__, n_ctx_train, params.n_ctx);
  1084. }
  1085. // print system information
  1086. {
  1087. LOG_INF("\n");
  1088. LOG_INF("%s\n", common_params_get_system_info(params).c_str());
  1089. }
  1090. if (!compute_imatrix(ctx, params, n_ctx)) {
  1091. return 1;
  1092. }
  1093. g_collector.save_imatrix();
  1094. LOG("\n");
  1095. llama_perf_context_print(ctx);
  1096. llama_backend_free();
  1097. return 0;
  1098. }