cvector-generator.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. #include "common.h"
  2. #include "llama.h"
  3. #include "ggml.h"
  4. #include "pca.hpp"
  5. #ifdef GGML_USE_CUDA
  6. #include "ggml-cuda.h"
  7. #endif
  8. #ifdef GGML_USE_METAL
  9. #include "ggml-metal.h"
  10. #endif
  11. #include <cstdio>
  12. #include <string>
  13. #include <tuple>
  14. #include <vector>
  15. #include <algorithm>
  16. #include <iostream>
  17. #include <fstream>
  18. #include <climits>
  19. //////////////////////////////////////////////////
  20. // utils
  21. template <class Iter>
  22. static std::string tokens_to_str(llama_context * ctx, Iter begin, Iter end) {
  23. std::string ret;
  24. for (; begin != end; ++begin) {
  25. ret += llama_token_to_piece(ctx, *begin);
  26. }
  27. return ret;
  28. }
  29. static void print_usage(int argc, char ** argv, const gpt_params & params) {
  30. gpt_params_print_usage(argc, argv, params);
  31. printf("\nexample usage:\n");
  32. printf("\n CPU only: %s -m ./dolphin-2.0-mistral-7b.Q4_K_M.gguf\n", argv[0]);
  33. printf("\n with GPU: %s -m ./dolphin-2.0-mistral-7b.Q4_K_M.gguf -ngl 99\n", argv[0]);
  34. printf("\n advanced: %s -m ./dolphin-2.0-mistral-7b.Q4_K_M.gguf -ngl 99 --completions 128 --pca-iter 2000 --pca-batch 100\n", argv[0]);
  35. printf("\n");
  36. }
  37. //////////////////////////////////////////////////
  38. // cb_eval is reused for each pair of positive - negative prompt
  39. struct callback_data {
  40. ggml_context * ctx_ggml = nullptr; // holds v_pos, v_neg, v_diff_filtered
  41. int n_layers = 0;
  42. int n_tokens = 0;
  43. bool is_eval_pos = true;
  44. // each element of the vector correspond to one layer
  45. std::vector<struct ggml_tensor *> v_pos; // vector of matrices of size [n_embd, n_tokens]
  46. std::vector<struct ggml_tensor *> v_neg; // vector of matrices of size [n_embd, n_tokens]
  47. std::vector<struct ggml_tensor *> v_diff_filtered; // vector of matrices of size [n_embd, n_nonzero_rows]. NOTE: n_nonzero_rows maybe different for each layer
  48. // save a tensor into either v_pos or v_neg (decided by is_eval_pos)
  49. void save_tensor_for_layer(struct ggml_tensor * t) {
  50. GGML_ASSERT(t->type == GGML_TYPE_F32);
  51. if (ctx_ggml == nullptr) {
  52. // alloc a new ctx_ggml if needed
  53. struct ggml_init_params params_ggml = {
  54. /*.mem_size =*/ ggml_tensor_overhead() * n_layers * 3u,
  55. /*.mem_buffer =*/ NULL,
  56. /*.no_alloc =*/ true,
  57. };
  58. ctx_ggml = ggml_init(params_ggml);
  59. }
  60. // copy tensor data
  61. auto n_bytes = ggml_nbytes(t);
  62. struct ggml_tensor * t_layer = ggml_new_tensor_2d(ctx_ggml, t->type, t->ne[0], t->ne[1]);
  63. t_layer->data = malloc(n_bytes); // TODO @ngxson : get rid of this malloc somehow
  64. ggml_backend_tensor_get(t, t_layer->data, 0, n_bytes);
  65. ggml_set_name(t_layer, ggml_get_name(t));
  66. //print_debug_tensor(t_layer);
  67. if (is_eval_pos) {
  68. v_pos.push_back(t_layer);
  69. } else {
  70. v_neg.push_back(t_layer);
  71. }
  72. }
  73. // calculate diff (v_pos - v_neg) and place the result back to v_pos
  74. // all zero rows in the diff tensor will also be removed
  75. // NOTE: final layer is ignored. we only have (n_layers - 1) to process
  76. std::vector<struct ggml_tensor *> calc_diff() {
  77. for (float il = 0; il < v_pos.size(); il++) {
  78. float * a = (float *) v_pos[il]->data;
  79. float * b = (float *) v_neg[il]->data;
  80. size_t n_elem = ggml_nelements(v_pos[il]);
  81. for (size_t j = 0; j < n_elem; j++) {
  82. a[j] -= b[j];
  83. }
  84. //print_debug_tensor(v_pos[i]);
  85. auto diff_filtered = filter_nonzero_rows(v_pos[il]);
  86. v_diff_filtered.push_back(diff_filtered);
  87. }
  88. return v_diff_filtered; // for convinient, we return the result std::vector
  89. }
  90. // delete zero rows from a given 2D tensor
  91. struct ggml_tensor * filter_nonzero_rows(struct ggml_tensor * a) {
  92. //printf("filter_nonzero_rows\n");
  93. auto is_row_all_zeros = [](struct ggml_tensor * t, int row, float eps) -> bool {
  94. // check if given row containing all zero elements
  95. int n_cols = t->ne[0]; // hint: should be equal to n_embd
  96. for (int col = 0; col < n_cols; ++col) {
  97. if (ggml_get_f32_nd(t, col, row, 0, 0) > eps) {
  98. return false;
  99. }
  100. }
  101. return true;
  102. };
  103. std::vector<int> rows_to_copy; // the idx of non-zero cols (to be copied to row of diff_filtered)
  104. for (int i_row = 0; i_row < a->ne[1]; i_row++) {
  105. if (!is_row_all_zeros(a, i_row, 1e-6)) {
  106. rows_to_copy.push_back(i_row);
  107. }
  108. }
  109. // get "n_nonzero_rows" for the output "diff_filtered"
  110. int n_nonzero_rows = rows_to_copy.size();
  111. //printf("n_nonzero_rows: %d\n", n_nonzero_rows);
  112. int n_embd = a->ne[0];
  113. GGML_ASSERT(n_nonzero_rows > 0);
  114. // diff_filtered: [n_embd, n_nonzero_rows]
  115. struct ggml_tensor * diff_filtered = ggml_new_tensor_2d(
  116. ctx_ggml, GGML_TYPE_F32, n_embd, n_nonzero_rows);
  117. ggml_format_name(diff_filtered, "diff_filtered_%s", a->name);
  118. diff_filtered->data = malloc(ggml_nbytes(diff_filtered));
  119. // copy non-zero rows
  120. for (int dest_row = 0; dest_row < n_nonzero_rows; dest_row++) {
  121. int src_row = rows_to_copy[dest_row];
  122. for (int i = 0; i < n_embd; i++) {
  123. float src_elem = ggml_get_f32_nd(a, i, src_row, 0, 0);
  124. ggml_set_f32_nd(diff_filtered, i, dest_row, 0, 0, src_elem);
  125. }
  126. }
  127. //print_debug_tensor(diff_filtered);
  128. return diff_filtered;
  129. }
  130. // we don't implement destructor, because we want to reuse callback_data. we just want to free the tensors
  131. void reset() {
  132. for (auto ptr : v_pos) free(ptr->data);
  133. for (auto ptr : v_neg) free(ptr->data);
  134. for (auto ptr : v_diff_filtered) free(ptr->data);
  135. v_pos.clear();
  136. v_neg.clear();
  137. v_diff_filtered.clear();
  138. if (ctx_ggml) {
  139. ggml_free(ctx_ggml);
  140. }
  141. ctx_ggml = nullptr;
  142. }
  143. };
  144. /**
  145. * process_ctx is used to store the ggml context for pre-post processing the diff vectors
  146. * in short, input => v_diff and output => v_final
  147. */
  148. struct train_context {
  149. ggml_context * ctx_ggml;
  150. int n_embd;
  151. int n_layers;
  152. /* pair of prompts to be used for generating final vector */
  153. std::vector<std::string> positive_entries;
  154. std::vector<std::string> negative_entries;
  155. // each element of the vector correspond to one layer
  156. // NOTE: the last layer is discard. therefore, we will have (n_layers - 1) elements here
  157. // NOTE (2): v_diff is transposed from v_diff_tmp
  158. std::vector<struct ggml_tensor *> v_diff; // vector of matrices of size [m, n_embd] where m ~ n_tokens * n_completions (v_diff contains no zero-rows)
  159. std::vector<struct ggml_tensor *> v_final; // vector of vectors of size [n_embd] to be written to file
  160. // to easily re-alloc when concat v_diff, we temporary store v_diff in a vector instead of a tensor
  161. // v_diff_tmp will get converted unto v_diff later on
  162. std::vector<std::vector<uint8_t>> v_diff_tmp;
  163. train_context(int n_embd_, int n_layers_) {
  164. n_embd = n_embd_;
  165. n_layers = n_layers_;
  166. struct ggml_init_params params_ggml = {
  167. /*.mem_size =*/ ggml_tensor_overhead() * (n_layers - 1) * 2u,
  168. /*.mem_buffer =*/ NULL,
  169. /*.no_alloc =*/ true,
  170. };
  171. ctx_ggml = ggml_init(params_ggml);
  172. for (int il = 0; il < n_layers - 1; il++) {
  173. std::vector<uint8_t> empty;
  174. v_diff_tmp.push_back(empty);
  175. auto t = ggml_new_tensor_1d(ctx_ggml, GGML_TYPE_F32, n_embd);
  176. t->data = malloc(ggml_nbytes(t)); // TODO: get rid of malloc if possible
  177. v_final.push_back(t);
  178. }
  179. }
  180. // add new rows into existing tensor in v_diff_tmp
  181. void concat_diff_tmp(const std::vector<struct ggml_tensor *> & diff_filtered) {
  182. GGML_ASSERT((int) diff_filtered.size() == n_layers - 1);
  183. for (int il = 0; il < n_layers - 1; il++) {
  184. auto t = diff_filtered[il];
  185. auto & diff_tmp = v_diff_tmp[il];
  186. size_t curr_size = diff_tmp.size();
  187. diff_tmp.resize(curr_size + ggml_nbytes(t));
  188. memcpy(diff_tmp.data() + curr_size, t->data, ggml_nbytes(t));
  189. }
  190. }
  191. // build the v_diff tensors from v_diff_tmp (v_diff need to be transposed)
  192. // TODO @ngxson : maybe add option NOT to transpose v_diff; will be useful for "mean" method
  193. void build_v_diff() {
  194. printf("build_v_diff\n");
  195. for (int il = 0; il < n_layers - 1; il++) {
  196. auto & diff_tmp = v_diff_tmp[il];
  197. int n_elem = diff_tmp.size() / sizeof(float);
  198. GGML_ASSERT(n_elem % n_embd == 0);
  199. int n_rows = n_elem / n_embd;
  200. struct ggml_tensor * diff = ggml_new_tensor_2d(ctx_ggml, GGML_TYPE_F32, n_rows, n_embd);
  201. ggml_set_name(diff, (std::string("diff_") + std::to_string(il)).c_str());
  202. // copy data & transpose
  203. diff->data = malloc(ggml_nbytes(diff)); // TODO: get rid of this malloc if possible
  204. float * arr = (float *) diff_tmp.data();
  205. for (int ir = 0; ir < n_rows; ++ir) {
  206. for (int ic = 0; ic < n_embd; ++ic) {
  207. float f = arr[ir*n_embd + ic];
  208. ggml_set_f32_nd(diff, ir, ic, 0, 0, f);
  209. }
  210. }
  211. v_diff.push_back(diff);
  212. print_debug_tensor(diff);
  213. // free memory of diff_tmp
  214. diff_tmp.resize(0);
  215. }
  216. }
  217. ~train_context() {
  218. for (auto ptr : v_final) free(ptr->data);
  219. for (auto ptr : v_diff) free(ptr->data);
  220. // no need to free v_diff_tmp, since we didn't use malloc
  221. ggml_free(ctx_ggml);
  222. }
  223. };
  224. struct tokenized_prompt {
  225. std::vector<llama_token> tokens_pos;
  226. std::vector<llama_token> tokens_neg;
  227. size_t max_seq_len;
  228. tokenized_prompt(llama_context * ctx, std::string pos, std::string neg) {
  229. const bool add_bos = llama_should_add_bos_token(llama_get_model(ctx));
  230. tokens_pos = ::llama_tokenize(ctx, pos, add_bos);
  231. tokens_neg = ::llama_tokenize(ctx, neg, add_bos);
  232. max_seq_len = std::max(tokens_pos.size(), tokens_neg.size());
  233. padding_seq(ctx, tokens_pos, max_seq_len);
  234. padding_seq(ctx, tokens_neg, max_seq_len);
  235. }
  236. void padding_seq(llama_context * ctx, std::vector<llama_token> & tokens, size_t len) {
  237. // TODO: customize padding token
  238. std::vector<llama_token> pad_tokens = ::llama_tokenize(ctx, " ", false);
  239. llama_token pad_tok = pad_tokens.back();
  240. while (tokens.size() < len) {
  241. tokens.push_back(pad_tok);
  242. }
  243. }
  244. };
  245. //////////////////////////////////////////////////
  246. template <typename T>
  247. static std::string to_string(const T & val) {
  248. std::stringstream ss;
  249. ss << val;
  250. return ss.str();
  251. }
  252. static std::vector<std::string> ctrlvec_load_prompt_file(std::string path, bool skip_empty_lines) {
  253. std::vector<std::string> output;
  254. std::ifstream file(path);
  255. if (!file.is_open()) {
  256. fprintf(stderr, "error: unable to open file: %s\n", path.c_str());
  257. exit(1);
  258. }
  259. std::string line;
  260. while (std::getline(file, line)) {
  261. bool is_skip = skip_empty_lines && line.empty();
  262. if (!is_skip) {
  263. string_process_escapes(line);
  264. output.push_back(line);
  265. }
  266. }
  267. file.close();
  268. return output;
  269. }
  270. //////////////////////////////////////////////////
  271. static bool cb_eval(struct ggml_tensor * t, bool ask, void * user_data) {
  272. auto * cb_data = (callback_data *) user_data;
  273. static const char * l_out_name = "l_out";
  274. const bool is_l_out = strncmp(t->name, l_out_name, strlen(l_out_name)) == 0;
  275. if (ask) {
  276. return is_l_out;
  277. }
  278. if (!is_l_out || t->ne[1] != cb_data->n_tokens) {
  279. return true;
  280. }
  281. // save the tensor to current context
  282. cb_data->save_tensor_for_layer(t);
  283. return true;
  284. }
  285. static bool get_hidden_layers(llama_context * ctx, std::vector<llama_token> & tokens) {
  286. llama_kv_cache_clear(ctx);
  287. if (llama_decode(ctx, llama_batch_get_one(tokens.data(), tokens.size(), 0, 0))) {
  288. fprintf(stderr, "%s : failed to eval\n", __func__);
  289. return false;
  290. }
  291. return true;
  292. }
  293. static void export_gguf(const std::vector<struct ggml_tensor *> & v_ctrl, const std::string fname, const std::string model_hint) {
  294. struct gguf_context * ctx = gguf_init_empty();
  295. const std::string arch = "controlvector";
  296. gguf_set_val_str(ctx, "general.architecture", arch.c_str());
  297. gguf_set_val_str(ctx, (arch + ".model_hint").c_str(), model_hint.c_str());
  298. gguf_set_val_i32(ctx, (arch + ".layer_count").c_str(), v_ctrl.size());
  299. for (size_t i = 0; i < v_ctrl.size(); ++i) {
  300. gguf_add_tensor(ctx, v_ctrl[i]);
  301. print_debug_tensor(v_ctrl[i]);
  302. printf("Added tensor: %s\n", v_ctrl[i]->name);
  303. }
  304. printf("%s: writing file...\n", __func__);
  305. gguf_write_to_file(ctx, fname.c_str(), false);
  306. printf("%s: wrote file '%s'\n", __func__, fname.c_str());
  307. gguf_free(ctx);
  308. }
  309. /**
  310. * Load prompt files and completion file.
  311. * Then format each pair of prompt + completion to make an entry.
  312. */
  313. static int prepare_entries(gpt_params & params, train_context & ctx_train) {
  314. // load prompts
  315. std::vector<std::string> positive_prompts = ctrlvec_load_prompt_file(params.cvector_positive_file, true);
  316. std::vector<std::string> negative_prompts = ctrlvec_load_prompt_file(params.cvector_negative_file, true);
  317. if (positive_prompts.size() != negative_prompts.size()) {
  318. fprintf(stderr, "number of positive and negative prompts must be equal\n");
  319. return 1;
  320. }
  321. if (positive_prompts.empty()) {
  322. fprintf(stderr, "must provide at least one prompt pair\n");
  323. return 1;
  324. }
  325. // create templated prompts
  326. std::vector<std::string> completions = ctrlvec_load_prompt_file(params.cvector_completions_file, false);
  327. auto format_template = [](std::string persona, std::string suffix) {
  328. // entry in positive/negative.txt must already be formatted i.e. "[INST] Act as if you're extremely happy. [/INST] "
  329. return persona + suffix;
  330. };
  331. for (size_t i = 0; i < positive_prompts.size(); ++i) {
  332. for (int j = 0; j < std::min((int) completions.size(), params.n_completions); ++j) {
  333. // TODO replicate the truncations done by the python implementation
  334. ctx_train.positive_entries.push_back(format_template(positive_prompts[i], completions[j]));
  335. ctx_train.negative_entries.push_back(format_template(negative_prompts[i], completions[j]));
  336. }
  337. }
  338. return 0;
  339. }
  340. int main(int argc, char ** argv) {
  341. gpt_params params;
  342. if (!gpt_params_parse(argc, argv, params)) {
  343. print_usage(argc, argv, params);
  344. return 1;
  345. }
  346. if (params.n_pca_iterations % params.n_pca_batch != 0) {
  347. fprintf(stderr, "PCA iterations must by multiply of PCA batch size\n");
  348. return 1;
  349. }
  350. callback_data cb_data;
  351. // pass the callback to the backend scheduler
  352. // it will be executed for each node during the graph computation
  353. params.cb_eval = cb_eval;
  354. params.cb_eval_user_data = &cb_data;
  355. params.warmup = false;
  356. print_build_info();
  357. llama_backend_init();
  358. llama_numa_init(params.numa);
  359. // load the model to get hparams
  360. llama_model * model;
  361. llama_context * ctx;
  362. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  363. // int n_ctx = llama_n_ctx(ctx);
  364. int n_layers = llama_n_layer(model);
  365. int n_embd = llama_n_embd(model);
  366. // get model hint param (a.k.a model arch name)
  367. char model_hint[128];
  368. llama_model_meta_val_str(model, "general.architecture", model_hint, 128);
  369. // init train_context
  370. train_context ctx_train(n_embd, n_layers);
  371. // load and prepare entries for training
  372. prepare_entries(params, ctx_train);
  373. // we have to pretokenize everything because otherwise we don't know how much overhead to allocate ctx_diffs_wrapped
  374. std::vector<tokenized_prompt> tokenized_prompts;
  375. size_t n_total_tokens = 0;
  376. for (size_t i = 0; i < ctx_train.positive_entries.size(); ++i) {
  377. tokenized_prompt t(ctx, ctx_train.positive_entries[i], ctx_train.negative_entries[i]);
  378. n_total_tokens += 2 * t.max_seq_len;
  379. tokenized_prompts.push_back(std::move(t));
  380. }
  381. std::cout << "n_total_tokens: " << n_total_tokens << std::endl;
  382. for(size_t i = 0; i < ctx_train.positive_entries.size(); ++i) {
  383. bool success = false;
  384. tokenized_prompt t = tokenized_prompts[i];
  385. cb_data.n_layers = n_layers;
  386. cb_data.n_tokens = t.max_seq_len;
  387. printf("Evaluating prompt[%d/%d]: \"%s\" - \"%s\" (%d tokens)\n",
  388. (int) i+1, (int) ctx_train.positive_entries.size(),
  389. tokens_to_str(ctx, t.tokens_pos.cbegin(), t.tokens_pos.cend()).c_str(),
  390. tokens_to_str(ctx, t.tokens_neg.cbegin(), t.tokens_neg.cend()).c_str(),
  391. (int) t.max_seq_len);
  392. cb_data.is_eval_pos = true;
  393. success = get_hidden_layers(ctx, t.tokens_pos);
  394. if (!success) break;
  395. cb_data.is_eval_pos = false;
  396. success = get_hidden_layers(ctx, t.tokens_neg);
  397. if (!success) break;
  398. // calculate diff and remove all zero rows
  399. auto v_diff_filtered = cb_data.calc_diff();
  400. // save & concat the filtered v_diff to ctx_train
  401. ctx_train.concat_diff_tmp(v_diff_filtered);
  402. // reset for next iteration
  403. cb_data.reset();
  404. }
  405. // done with the model, we can now free it to make gain some memory
  406. printf("Done evaluate prompts, unload model...\n");
  407. llama_free(ctx);
  408. llama_free_model(model);
  409. // prepare ctx_train for PCA
  410. ctx_train.build_v_diff();
  411. // run PCA
  412. PCA::pca_params pca_params;
  413. pca_params.n_threads = params.n_threads;
  414. pca_params.n_batch = params.n_pca_batch;
  415. pca_params.n_iterations = params.n_pca_iterations;
  416. PCA::run_pca(pca_params, ctx_train.v_diff, ctx_train.v_final);
  417. // write output vectors to gguf
  418. export_gguf(ctx_train.v_final, params.cvector_outfile, model_hint);
  419. llama_backend_free();
  420. return 0;
  421. }