KBaba7/llama.cpp
0
1#include "arg.h"2#include "common.h"3#include "log.h"4#include "llama.h"5 6#include <cmath>7#include <cstdio>8#include <cstring>9#include <ctime>10#include <thread>11#include <mutex>12#include <vector>13#include <fstream>14#include <unordered_map>15#include <algorithm>16 17#if defined(_MSC_VER)18#pragma warning(disable: 4244 4267) // possible loss of data19#endif20 21static void print_usage(int, char ** argv) {22 LOG("\nexample usage:\n");23 LOG("\n %s \\\n"24 " -m model.gguf -f some-text.txt [-o imatrix.dat] [--process-output] \\\n"25 " [--no-ppl] [--chunk 123] [--output-frequency 10] [--save-frequency 0] \\\n"26 " [--in-file imatrix-prev-0.dat --in-file imatrix-prev-1.dat ...]\n" , argv[0]);27 LOG("\n");28}29 30struct Stats {31 std::vector<float> values;32 std::vector<int> counts;33 int ncall = 0;34};35 36class IMatrixCollector {37public:38 IMatrixCollector() = default;39 void set_params(common_params params) { m_params = std::move(params); }40 bool collect_imatrix(struct ggml_tensor * t, bool ask, void * user_data);41 void save_imatrix(int ncall = -1) const;42 bool load_imatrix(const char * fname);43private:44 std::unordered_map<std::string, Stats> m_stats;45 common_params m_params;46 std::mutex m_mutex;47 int m_last_call = 0;48 std::vector<float> m_src1_data;49 std::vector<char> m_ids; // the expert ids from ggml_mul_mat_id50};51 52// remove any prefix and suffixes from the name53// CUDA0#blk.0.attn_k.weight#0 => blk.0.attn_k.weight54static std::string filter_tensor_name(const char * name) {55 std::string wname;56 const char * p = strchr(name, '#');57 if (p != NULL) {58 p = p + 1;59 const char * q = strchr(p, '#');60 if (q != NULL) {61 wname = std::string(p, q - p);62 } else {63 wname = p;64 }65 } else {66 wname = name;67 }68 return wname;69}70 71bool IMatrixCollector::collect_imatrix(struct ggml_tensor * t, bool ask, void * user_data) {72 GGML_UNUSED(user_data);73 74 const struct ggml_tensor * src0 = t->src[0];75 const struct ggml_tensor * src1 = t->src[1];76 std::string wname = filter_tensor_name(src0->name);77 78 // when ask is true, the scheduler wants to know if we are interested in data from this tensor79 // if we return true, a follow-up call will be made with ask=false in which we can do the actual collection80 if (ask) {81 if (t->op == GGML_OP_MUL_MAT_ID) return true; // collect all indirect matrix multiplications82 if (t->op != GGML_OP_MUL_MAT) return false;83 // why are small batches ignored (<16 tokens)?84 if (src1->ne[1] < 16 || src1->type != GGML_TYPE_F32) return false;85 if (!(wname.substr(0, 4) == "blk." || (m_params.process_output && wname == "output.weight"))) return false;86 return true;87 }88 89 std::lock_guard<std::mutex> lock(m_mutex);90 91 // copy the data from the GPU memory if needed92 const bool is_host = ggml_backend_buffer_is_host(src1->buffer);93 94 if (!is_host) {95 m_src1_data.resize(ggml_nelements(src1));96 ggml_backend_tensor_get(src1, m_src1_data.data(), 0, ggml_nbytes(src1));97 }98 99 const float * data = is_host ? (const float *) src1->data : m_src1_data.data();100 101 // this has been adapted to the new format of storing merged experts in a single 3d tensor102 // ref: https://github.com/ggerganov/llama.cpp/pull/6387103 if (t->op == GGML_OP_MUL_MAT_ID) {104 // ids -> [n_experts_used, n_tokens]105 // src1 -> [cols, n_expert_used, n_tokens]106 const ggml_tensor * ids = t->src[2];107 const int n_as = src0->ne[2];108 const int n_ids = ids->ne[0];109 110 // the top-k selected expert ids are stored in the ids tensor111 // for simplicity, always copy ids to host, because it is small112 // take into account that ids is not contiguous!113 114 GGML_ASSERT(ids->ne[1] == src1->ne[2]);115 116 m_ids.resize(ggml_nbytes(ids));117 ggml_backend_tensor_get(ids, m_ids.data(), 0, ggml_nbytes(ids));118 119 auto & e = m_stats[wname];120 121 ++e.ncall;122 123 if (e.values.empty()) {124 e.values.resize(src1->ne[0]*n_as, 0);125 e.counts.resize(src1->ne[0]*n_as, 0);126 }127 else if (e.values.size() != (size_t)src1->ne[0]*n_as) {128 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);129 exit(1); //GGML_ABORT("fatal error");130 }131 LOG_DBGV(2, "%s[%d]: %32s, %s, %5d x %5d, %d\n", __func__, m_last_call, wname.c_str(), ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[2], (int)src1->type);132 // loop over all possible experts, regardless if they are used or not in the batch133 for (int ex = 0; ex < n_as; ++ex) {134 size_t e_start = ex*src1->ne[0];135 136 for (int idx = 0; idx < n_ids; ++idx) {137 for (int row = 0; row < (int)src1->ne[2]; ++row) {138 const int excur = *(const int32_t *) (m_ids.data() + row*ids->nb[1] + idx*ids->nb[0]);139 140 GGML_ASSERT(excur >= 0 && excur < n_as); // sanity check141 142 if (excur != ex) continue;143 144 const int64_t i11 = idx % src1->ne[1];145 const int64_t i12 = row;146 const float * x = (const float *)((const char *)data + i11*src1->nb[1] + i12*src1->nb[2]);147 148 for (int j = 0; j < (int)src1->ne[0]; ++j) {149 e.values[e_start + j] += x[j]*x[j];150 e.counts[e_start + j]++;151 if (!std::isfinite(e.values[e_start + j])) {152 LOG("\n");153 LOG_ERR("%f detected in %s\n", e.values[e_start + j], wname.c_str());154 exit(1);155 }156 }157 }158 }159 if (e.ncall > m_last_call) {160 m_last_call = e.ncall;161 if (m_last_call % m_params.n_out_freq == 0) {162 save_imatrix();163 }164 if (m_params.n_save_freq > 0 && m_last_call%m_params.n_save_freq == 0) {165 save_imatrix(m_last_call);166 }167 }168 }169 } else {170 auto & e = m_stats[wname];171 if (e.values.empty()) {172 e.values.resize(src1->ne[0], 0);173 e.counts.resize(src1->ne[0], 0);174 }175 else if (e.values.size() != (size_t)src1->ne[0]) {176 LOG_ERR("%s: inconsistent size for %s (%d vs %d)\n", __func__, wname.c_str(), (int)e.values.size(), (int)src1->ne[0]);177 exit(1); //GGML_ABORT("fatal error");178 }179 ++e.ncall;180 LOG_DBGV(2, "%s[%d]: %32s, %s, %5d x %5d, %d\n", __func__, m_last_call, wname.c_str(), ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[1], (int)src1->type);181 for (int row = 0; row < (int)src1->ne[1]; ++row) {182 const float * x = data + row * src1->ne[0];183 for (int j = 0; j < (int)src1->ne[0]; ++j) {184 e.values[j] += x[j]*x[j];185 e.counts[j]++;186 if (!std::isfinite(e.values[j])) {187 LOG_ERR("%f detected in %s\n", e.values[j], wname.c_str());188 exit(1);189 }190 }191 }192 if (e.ncall > m_last_call) {193 m_last_call = e.ncall;194 if (m_last_call % m_params.n_out_freq == 0) {195 save_imatrix();196 }197 if (m_params.n_save_freq > 0 && m_last_call%m_params.n_save_freq == 0) {198 save_imatrix(m_last_call);199 }200 }201 }202 203 return true;204}205 206void IMatrixCollector::save_imatrix(int ncall) const {207 auto fname = m_params.out_file;208 if (fname.empty()) {209 fname = "imatrix.dat";210 }211 212 if (ncall > 0) {213 fname += ".at_";214 fname += std::to_string(ncall);215 }216 217 // avoid writing imatrix entries that do not have full data218 // this can happen with MoE models where some of the experts end up not being exercised by the provided training data219 220 int n_entries = 0;221 std::vector<std::string> to_store;222 223 bool is_first = true; // for printing224 for (const auto & kv : m_stats) {225 const int n_all = kv.second.counts.size();226 227 if (n_all == 0) {228 continue;229 }230 231 int n_zeros = 0;232 for (const int c : kv.second.counts) {233 if (c == 0) {234 n_zeros++;235 }236 }237 238 if (n_zeros != 0 && is_first) {239 LOG_INF("\n");240 is_first = false;241 }242 243 if (n_zeros == n_all) {244 LOG_WRN("%s: entry '%40s' has no data - skipping\n", __func__, kv.first.c_str());245 continue;246 }247 248 if (n_zeros > 0) {249 LOG_WRN("%s: entry '%40s' has partial data (%.2f%%) - skipping\n", __func__, kv.first.c_str(), 100.0f * (n_all - n_zeros) / n_all);250 continue;251 }252 253 n_entries++;254 to_store.push_back(kv.first);255 }256 257 if (to_store.size() < m_stats.size()) {258 LOG_WRN("%s: storing only %zu out of %zu entries\n", __func__, to_store.size(), m_stats.size());259 }260 261 std::ofstream out(fname, std::ios::binary);262 out.write((const char *) &n_entries, sizeof(n_entries));263 for (const auto & name : to_store) {264 const auto & stat = m_stats.at(name);265 int len = name.size();266 out.write((const char *) &len, sizeof(len));267 out.write(name.c_str(), len);268 out.write((const char *) &stat.ncall, sizeof(stat.ncall));269 int nval = stat.values.size();270 out.write((const char *) &nval, sizeof(nval));271 if (nval > 0) {272 std::vector<float> tmp(nval);273 for (int i = 0; i < nval; i++) {274 tmp[i] = (stat.values[i] / static_cast<float>(stat.counts[i])) * static_cast<float>(stat.ncall);275 }276 out.write((const char*)tmp.data(), nval*sizeof(float));277 }278 }279 280 // Write the number of call the matrix was computed with281 out.write((const char *) &m_last_call, sizeof(m_last_call));282 283 // Write the input filename at the end of the file to later on specify it in quantize284 {285 int len = m_params.prompt_file.size();286 out.write((const char *) &len, sizeof(len));287 out.write(m_params.prompt_file.c_str(), len);288 }289 290 LOGV(1, "\n");291 LOG_DBGV(1, "%s: stored collected data after %d chunks in %s\n", __func__, m_last_call, fname.c_str());292}293 294bool IMatrixCollector::load_imatrix(const char * fname) {295 std::ifstream in(fname, std::ios::binary);296 if (!in) {297 LOG_ERR("%s: failed to open %s\n",__func__, fname);298 return false;299 }300 int n_entries;301 in.read((char*)&n_entries, sizeof(n_entries));302 if (in.fail() || n_entries < 1) {303 LOG_ERR("%s: no data in file %s\n", __func__, fname);304 return false;305 }306 for (int i = 0; i < n_entries; ++i) {307 int len; in.read((char *)&len, sizeof(len));308 std::vector<char> name_as_vec(len+1);309 in.read((char *)name_as_vec.data(), len);310 if (in.fail()) {311 LOG_ERR("%s: failed reading name for entry %d from %s\n",__func__,i+1, fname);312 return false;313 }314 name_as_vec[len] = 0;315 std::string name{name_as_vec.data()};316 auto & e = m_stats[std::move(name)];317 int ncall;318 in.read((char*)&ncall, sizeof(ncall));319 int nval;320 in.read((char *)&nval, sizeof(nval));321 if (in.fail() || nval < 1) {322 LOG_ERR("%s: failed reading number of values for entry %d\n",__func__,i);323 m_stats = {};324 return false;325 }326 327 if (e.values.empty()) {328 e.values.resize(nval, 0);329 e.counts.resize(nval, 0);330 }331 332 std::vector<float> tmp(nval);333 in.read((char*)tmp.data(), nval*sizeof(float));334 if (in.fail()) {335 LOG_ERR("%s: failed reading data for entry %d\n",__func__,i);336 m_stats = {};337 return false;338 }339 340 // Recreate the state as expected by save_imatrix(), and corerct for weighted sum.341 for (int i = 0; i < nval; i++) {342 e.values[i] += tmp[i];343 e.counts[i] += ncall;344 }345 e.ncall += ncall;346 347 }348 return true;349}350 351static IMatrixCollector g_collector;352 353static bool ik_collect_imatrix(struct ggml_tensor * t, bool ask, void * user_data) {354 return g_collector.collect_imatrix(t, ask, user_data);355}356 357 358struct results_log_softmax {359 double log_softmax;360 float logit;361 float prob;362};363 364static std::vector<float> softmax(const std::vector<float> & logits) {365 std::vector<float> probs(logits.size());366 float max_logit = logits[0];367 for (float v : logits) {368 max_logit = std::max(max_logit, v);369 }370 double sum_exp = 0.0;371 for (size_t i = 0; i < logits.size(); i++) {372 // Subtract the maximum logit value from the current logit value for numerical stability373 const float logit = logits[i] - max_logit;374 const float exp_logit = expf(logit);375 sum_exp += exp_logit;376 probs[i] = exp_logit;377 }378 for (size_t i = 0; i < probs.size(); i++) {379 probs[i] /= sum_exp;380 }381 return probs;382}383 384static results_log_softmax log_softmax(int n_vocab, const float * logits, int tok) {385 float max_logit = logits[0];386 for (int i = 1; i < n_vocab; ++i) {387 max_logit = std::max(max_logit, logits[i]);388 }389 double sum_exp = 0.0;390 for (int i = 0; i < n_vocab; ++i) {391 sum_exp += expf(logits[i] - max_logit);392 }393 return {logits[tok] - max_logit - log(sum_exp), logits[tok], expf(logits[tok] - max_logit) / (float) sum_exp};394}395 396static void process_logits(397 int n_vocab, const float * logits, const int * tokens, int n_token, std::vector<std::thread> & workers,398 double & nll, double & nll2, float * logit_history, float * prob_history) {399 std::mutex mutex;400 int counter = 0;401 auto compute = [&mutex, &counter, &nll, &nll2, logit_history, prob_history, n_vocab, logits, tokens, n_token] () {402 double local_nll = 0;403 double local_nll2 = 0;404 while (true) {405 std::unique_lock<std::mutex> lock(mutex);406 int i = counter++;407 if (i >= n_token) {408 nll += local_nll; nll2 += local_nll2;409 break;410 }411 lock.unlock();412 const results_log_softmax results = log_softmax(n_vocab, logits + i*n_vocab, tokens[i+1]);413 const double v = -results.log_softmax;414 local_nll += v;415 local_nll2 += v*v;416 417 logit_history[i] = results.logit;418 prob_history[i] = results.prob;419 }420 };421 for (auto & w : workers) {422 w = std::thread(compute);423 }424 compute();425 for (auto & w : workers) {426 w.join();427 }428}429 430static bool compute_imatrix(llama_context * ctx, const common_params & params) {431 const llama_model * model = llama_get_model(ctx);432 const llama_vocab * vocab = llama_model_get_vocab(model);433 434 const bool add_bos = llama_vocab_get_add_bos(vocab);435 const int n_ctx = llama_n_ctx(ctx);436 437 GGML_ASSERT(!llama_vocab_get_add_eos(vocab));438 439 auto tim1 = std::chrono::high_resolution_clock::now();440 LOG_INF("%s: tokenizing the input ..\n", __func__);441 442 std::vector<llama_token> tokens = common_tokenize(ctx, params.prompt, true);443 444 auto tim2 = std::chrono::high_resolution_clock::now();445 LOG_INF("%s: tokenization took %g ms\n",__func__,1e-3*std::chrono::duration_cast<std::chrono::microseconds>(tim2-tim1).count());446 447 if (params.i_chunk > 0) {448 if (size_t((params.i_chunk + 2)*n_ctx) >= tokens.size()) {449 LOG_ERR("%s: there will be not enough tokens left after removing %d chunks\n", __func__, params.i_chunk);450 return false;451 }452 LOG_INF("%s: removing initial %d chunks (%d tokens)\n", __func__, params.i_chunk, params.i_chunk*n_ctx);453 tokens.erase(tokens.begin(), tokens.begin() + params.i_chunk*n_ctx);454 }455 456 if (int(tokens.size()) < 2*n_ctx) {457 LOG_ERR("%s: you need at least %d tokens for a context of %d tokens\n", __func__, 2*n_ctx, n_ctx);458 LOG_ERR("%s: the data file you provided tokenizes to only %zu tokens\n", __func__, tokens.size());459 return false;460 }461 462 std::vector<float> logit_history;463 std::vector<float> prob_history;464 465 if (params.compute_ppl) {466 logit_history.resize(tokens.size());467 prob_history.resize(tokens.size());468 }469 470 const int n_chunk_max = tokens.size() / n_ctx;471 472 const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max);473 const int n_vocab = llama_vocab_n_tokens(vocab);474 const int n_batch = params.n_batch;475 476 int count = 0;477 double nll = 0.0;478 double nll2 = 0.0;479 480 LOG_INF("%s: computing over %d chunks with batch_size %d\n", __func__, n_chunk, n_batch);481 482 std::vector<std::thread> workers(std::thread::hardware_concurrency() - 1);483 484 const int num_batches = (n_ctx + n_batch - 1) / n_batch;485 486 std::vector<float> logits;487 if (params.compute_ppl && num_batches > 1) {488 logits.reserve((size_t)n_ctx * n_vocab);489 }490 491 for (int i = 0; i < n_chunk; ++i) {492 const int start = i * n_ctx;493 const int end = start + n_ctx;494 495 std::vector<float> logits;496 497 const auto t_start = std::chrono::high_resolution_clock::now();498 499 // clear the KV cache500 llama_kv_cache_clear(ctx);501 502 llama_batch batch = llama_batch_init(n_batch, 0, 1);503 504 for (int j = 0; j < num_batches; ++j) {505 const int batch_start = start + j * n_batch;506 const int batch_size = std::min(end - batch_start, n_batch);507 508 // save original token and restore it after eval509 const auto token_org = tokens[batch_start];510 511 // add BOS token for the first batch of each chunk512 if (add_bos && j == 0) {513 tokens[batch_start] = llama_vocab_bos(vocab);514 }515 516 common_batch_clear(batch);517 for (int i = 0; i < batch_size; i++) {518 common_batch_add(batch, tokens[batch_start + i], j*n_batch + i, {0}, true);519 }520 521 if (llama_decode(ctx, batch)) {522 LOG_ERR("%s : failed to eval\n", __func__);523 llama_batch_free(batch);524 return false;525 }526 527 // restore the original token in case it was set to BOS528 tokens[batch_start] = token_org;529 530 if (params.compute_ppl && num_batches > 1) {531 const auto * batch_logits = llama_get_logits(ctx);532 logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);533 }534 }535 536 llama_batch_free(batch);537 538 const auto t_end = std::chrono::high_resolution_clock::now();539 540 if (i == 0) {541 const float t_total = std::chrono::duration<float>(t_end - t_start).count();542 LOG_INF("%s: %.2f seconds per pass - ETA ", __func__, t_total);543 int total_seconds = (int)(t_total * n_chunk);544 if (total_seconds >= 60*60) {545 LOG("%d hours ", total_seconds / (60*60));546 total_seconds = total_seconds % (60*60);547 }548 LOG("%.2f minutes\n", total_seconds / 60.0);549 }550 551 if (params.compute_ppl) {552 const int first = n_ctx/2;553 const auto * all_logits = num_batches > 1 ? logits.data() : llama_get_logits(ctx);554 process_logits(n_vocab, all_logits + first*n_vocab, tokens.data() + start + first, n_ctx - 1 - first,555 workers, nll, nll2, logit_history.data() + start + first, prob_history.data() + start + first);556 count += n_ctx - first - 1;557 558 LOG("[%d]%.4lf,", i + 1, std::exp(nll / count));559 fflush(stdout);560 561 logits.clear();562 }563 }564 LOG("\n");565 566 if (params.compute_ppl) {567 nll2 /= count;568 nll /= count;569 const double ppl = exp(nll);570 nll2 -= nll * nll;571 if (nll2 > 0) {572 nll2 = sqrt(nll2/(count-1));573 LOG("Final estimate: PPL = %.4lf +/- %.5lf\n", ppl, nll2*ppl);574 } else {575 LOG("Unexpected negative standard deviation of log(prob)\n");576 }577 }578 579 return true;580}581 582int main(int argc, char ** argv) {583 common_params params;584 585 params.n_ctx = 512;586 params.logits_all = true;587 params.escape = false;588 589 if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_IMATRIX, print_usage)) {590 return 1;591 }592 593 common_init();594 595 params.n_batch = std::min(params.n_batch, params.n_ctx);596 597 g_collector.set_params(params);598 599 for (const auto & in_file : params.in_files) {600 LOG_INF("%s : loading imatrix from '%s'\n", __func__, in_file.c_str());601 if (!g_collector.load_imatrix(in_file.c_str())) {602 LOG_ERR("%s : failed to load %s\n", __func__, in_file.c_str());603 return 1;604 }605 }606 607 if (params.in_files.size() > 1) {608 LOG_INF("%s : saving combined imatrix to '%s'\n", __func__, params.out_file.c_str());609 g_collector.save_imatrix();610 }611 612 llama_backend_init();613 llama_numa_init(params.numa);614 615 // pass the callback to the backend scheduler616 // it will be executed for each node during the graph computation617 params.cb_eval = ik_collect_imatrix;618 params.cb_eval_user_data = NULL;619 params.warmup = false;620 621 // init622 common_init_result llama_init = common_init_from_params(params);623 624 llama_model * model = llama_init.model.get();625 llama_context * ctx = llama_init.context.get();626 627 if (model == nullptr || ctx == nullptr) {628 LOG_ERR("%s : failed to init\n", __func__);629 return 1;630 }631 632 const int n_ctx_train = llama_model_n_ctx_train(model);633 if (params.n_ctx > n_ctx_train) {634 LOG_WRN("%s: model was trained on only %d context tokens (%d specified)\n",635 __func__, n_ctx_train, params.n_ctx);636 }637 638 // print system information639 {640 LOG_INF("\n");641 LOG_INF("%s\n", common_params_get_system_info(params).c_str());642 }643 644 if (params.prompt.empty()) {645 if (params.in_files.empty()) {646 LOG_ERR("Error: No prompt provided and no precomputed matrices (--in-file) to combine.\n");647 return 1;648 }649 LOG_INF("No prompt provided; combining precomputed matrices only.\n");650 } else {651 if (!compute_imatrix(ctx, params)) {652 return 1;653 }654 }655 656 657 g_collector.save_imatrix();658 659 LOG("\n");660 llama_perf_context_print(ctx);661 662 llama_backend_free();663 664 return 0;665}666 