retrieval.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. #include "common.h"
  2. #include "llama.h"
  3. #include <algorithm>
  4. #include <fstream>
  5. struct retrieval_params {
  6. std::vector<std::string> context_files; // context files to embed
  7. int32_t chunk_size = 64; // chunk size for context embedding
  8. std::string chunk_separator = "\n"; // chunk separator for context embedding
  9. };
  10. static void retrieval_params_print_usage(int argc, char ** argv, gpt_params & gpt_params, retrieval_params & params) {
  11. gpt_print_usage(argc, argv, gpt_params);
  12. printf("retrieval options:\n");
  13. printf(" --context-file FNAME file containing context to embed.\n");
  14. printf(" specify multiple files by providing --context-file option multiple times.\n");
  15. printf(" --chunk-size N minimum length of embedded text chunk (default:%d)\n", params.chunk_size);
  16. printf(" --chunk-separator STRING\n");
  17. printf(" string to separate chunks (default: \"\\n\")\n");
  18. printf("\n");
  19. }
  20. static void retrieval_params_parse(int argc, char ** argv, gpt_params & gpt_params, retrieval_params & retrieval_params) {
  21. int i = 1;
  22. std::string arg;
  23. while (i < argc) {
  24. arg = argv[i];
  25. bool invalid_gpt_param = false;
  26. if(gpt_params_find_arg(argc, argv, argv[i], gpt_params, i, invalid_gpt_param)) {
  27. if (invalid_gpt_param) {
  28. fprintf(stderr, "error: invalid argument: %s\n", arg.c_str());
  29. retrieval_params_print_usage(argc, argv, gpt_params, retrieval_params);
  30. exit(1);
  31. }
  32. // option was parsed by gpt_params_find_arg
  33. } else if (arg == "--context-file") {
  34. if (++i >= argc) {
  35. fprintf(stderr, "error: missing argument for --context-file\n");
  36. retrieval_params_print_usage(argc, argv, gpt_params, retrieval_params);
  37. exit(1);
  38. }
  39. std::ifstream file(argv[i]);
  40. if (!file) {
  41. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  42. retrieval_params_print_usage(argc, argv, gpt_params, retrieval_params);
  43. exit(1);
  44. }
  45. // store the external file name in params
  46. retrieval_params.context_files.push_back(argv[i]);
  47. } else if (arg == "--chunk-size") {
  48. if (++i >= argc) {
  49. fprintf(stderr, "error: missing argument for --chunk-size\n");
  50. retrieval_params_print_usage(argc, argv, gpt_params, retrieval_params);
  51. exit(1);
  52. }
  53. retrieval_params.chunk_size = std::stoi(argv[i]);
  54. } else if (arg == "--chunk-separator") {
  55. if (++i >= argc) {
  56. fprintf(stderr, "error: missing argument for --chunk-separator\n");
  57. retrieval_params_print_usage(argc, argv, gpt_params, retrieval_params);
  58. exit(1);
  59. }
  60. retrieval_params.chunk_separator = argv[i];
  61. } else {
  62. // unknown argument
  63. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  64. retrieval_params_print_usage(argc, argv, gpt_params, retrieval_params);
  65. exit(1);
  66. }
  67. i++;
  68. }
  69. }
  70. struct chunk {
  71. // filename
  72. std::string filename;
  73. // original file position
  74. size_t filepos;
  75. // original text data
  76. std::string textdata = "";
  77. // tokenized text data
  78. std::vector<llama_token> tokens;
  79. // embedding
  80. std::vector<float> embedding;
  81. };
  82. // chunk file data to chunks of size >= chunk_size
  83. // chunk_separator is the separator between chunks
  84. static std::vector<chunk> chunk_file(const std::string & filename, int chunk_size, const std::string & chunk_separator) {
  85. std::vector<chunk> chunks;
  86. std::ifstream f(filename.c_str());
  87. if (!f.is_open()) {
  88. fprintf(stderr, "Error: could not open file %s\n", filename.c_str());
  89. return chunks;
  90. }
  91. chunk current_chunk;
  92. char buffer[1024];
  93. int64_t filepos = 0;
  94. std::string current = "";
  95. while (f.read(buffer, 1024)) {
  96. current += std::string(buffer, f.gcount());
  97. size_t pos;
  98. while ((pos = current.find(chunk_separator)) != std::string::npos) {
  99. current_chunk.textdata += current.substr(0, pos + chunk_separator.size());
  100. if ((int) current_chunk.textdata.size() > chunk_size) {
  101. // save chunk
  102. current_chunk.filepos = filepos;
  103. current_chunk.filename = filename;
  104. chunks.push_back(current_chunk);
  105. // update filepos
  106. filepos += (int) current_chunk.textdata.size();
  107. // reset current_chunk
  108. current_chunk = chunk();
  109. }
  110. current = current.substr(pos + chunk_separator.size());
  111. }
  112. }
  113. // add leftover data to last chunk
  114. if (current_chunk.textdata.size() > 0) {
  115. if (chunks.empty()) {
  116. current_chunk.filepos = filepos;
  117. current_chunk.filename = filename;
  118. chunks.push_back(current_chunk);
  119. } else {
  120. chunks.back().textdata += current_chunk.textdata;
  121. }
  122. }
  123. f.close();
  124. return chunks;
  125. }
  126. static void batch_add_seq(llama_batch & batch, const std::vector<int32_t> & tokens, int seq_id) {
  127. for (size_t i = 0; i < tokens.size(); i++) {
  128. llama_batch_add(batch, tokens[i], i, { seq_id }, i == tokens.size() - 1);
  129. }
  130. }
  131. static void batch_decode(llama_context * ctx, llama_batch & batch, float * output, int n_seq, int n_embd) {
  132. // clear previous kv_cache values (irrelevant for embeddings)
  133. llama_kv_cache_clear(ctx);
  134. // run model
  135. fprintf(stderr, "%s: n_tokens = %d, n_seq = %d\n", __func__, batch.n_tokens, n_seq);
  136. if (llama_decode(ctx, batch) < 0) {
  137. fprintf(stderr, "%s : failed to decode\n", __func__);
  138. }
  139. for (int i = 0; i < batch.n_tokens; i++) {
  140. if (!batch.logits[i]) {
  141. continue;
  142. }
  143. // try to get sequence embeddings - supported only when pooling_type is not NONE
  144. const float * embd = llama_get_embeddings_seq(ctx, batch.seq_id[i][0]);
  145. if (embd == NULL) {
  146. embd = llama_get_embeddings_ith(ctx, i);
  147. if (embd == NULL) {
  148. fprintf(stderr, "%s: failed to get embeddings for token %d\n", __func__, i);
  149. continue;
  150. }
  151. }
  152. float * out = output + batch.seq_id[i][0] * n_embd;
  153. llama_embd_normalize(embd, out, n_embd);
  154. }
  155. }
  156. int main(int argc, char ** argv) {
  157. gpt_params params;
  158. retrieval_params retrieval_params;
  159. retrieval_params_parse(argc, argv, params, retrieval_params);
  160. // For BERT models, batch size must be equal to ubatch size
  161. params.n_ubatch = params.n_batch;
  162. if (retrieval_params.chunk_size <= 0) {
  163. fprintf(stderr, "chunk_size must be positive\n");
  164. return 1;
  165. }
  166. if (retrieval_params.context_files.empty()) {
  167. fprintf(stderr, "context_files must be specified\n");
  168. return 1;
  169. }
  170. params.embedding = true;
  171. print_build_info();
  172. printf("processing files:\n");
  173. for (auto & context_file : retrieval_params.context_files) {
  174. printf("%s\n", context_file.c_str());
  175. }
  176. std::vector<chunk> chunks;
  177. for (auto & context_file : retrieval_params.context_files) {
  178. std::vector<chunk> file_chunk = chunk_file(context_file, retrieval_params.chunk_size, retrieval_params.chunk_separator);
  179. chunks.insert(chunks.end(), file_chunk.begin(), file_chunk.end());
  180. }
  181. printf("Number of chunks: %ld\n", chunks.size());
  182. llama_backend_init();
  183. llama_numa_init(params.numa);
  184. llama_model * model;
  185. llama_context * ctx;
  186. // load the model
  187. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  188. if (model == NULL) {
  189. fprintf(stderr, "%s: error: unable to load model\n", __func__);
  190. return 1;
  191. }
  192. const int n_ctx_train = llama_n_ctx_train(model);
  193. const int n_ctx = llama_n_ctx(ctx);
  194. if (n_ctx > n_ctx_train) {
  195. fprintf(stderr, "%s: warning: model was trained on only %d context tokens (%d specified)\n",
  196. __func__, n_ctx_train, n_ctx);
  197. }
  198. // print system information
  199. {
  200. fprintf(stderr, "\n");
  201. fprintf(stderr, "%s\n", get_system_info(params).c_str());
  202. }
  203. // max batch size
  204. const uint64_t n_batch = params.n_batch;
  205. GGML_ASSERT(params.n_batch >= params.n_ctx);
  206. // tokenize the prompts and trim
  207. for (auto & chunk : chunks) {
  208. auto inp = ::llama_tokenize(ctx, chunk.textdata, true, false);
  209. if (inp.size() > n_batch) {
  210. fprintf(stderr, "%s: error: chunk size (%lld) exceeds batch size (%lld), increase batch size and re-run\n",
  211. __func__, (long long int) inp.size(), (long long int) n_batch);
  212. return 1;
  213. }
  214. // add eos if not present
  215. if (inp.empty() || inp.back() != llama_token_eos(model)) {
  216. inp.push_back(llama_token_eos(model));
  217. }
  218. chunk.tokens = inp;
  219. }
  220. // tokenization stats
  221. if (params.verbose_prompt) {
  222. for (int i = 0; i < (int) chunks.size(); i++) {
  223. fprintf(stderr, "%s: prompt %d: '%s'\n", __func__, i, chunks[i].textdata.c_str());
  224. fprintf(stderr, "%s: number of tokens in prompt = %zu\n", __func__, chunks[i].tokens.size());
  225. for (int j = 0; j < (int) chunks[i].tokens.size(); j++) {
  226. fprintf(stderr, "%6d -> '%s'\n", chunks[i].tokens[j], llama_token_to_piece(ctx, chunks[i].tokens[j]).c_str());
  227. }
  228. fprintf(stderr, "\n\n");
  229. }
  230. }
  231. // initialize batch
  232. const int n_chunks = chunks.size();
  233. struct llama_batch batch = llama_batch_init(n_batch, 0, 1);
  234. // allocate output
  235. const int n_embd = llama_n_embd(model);
  236. std::vector<float> embeddings(n_chunks * n_embd, 0);
  237. float * emb = embeddings.data();
  238. // break into batches
  239. int p = 0; // number of prompts processed already
  240. int s = 0; // number of prompts in current batch
  241. for (int k = 0; k < n_chunks; k++) {
  242. // clamp to n_batch tokens
  243. auto & inp = chunks[k].tokens;
  244. const uint64_t n_toks = inp.size();
  245. // encode if at capacity
  246. if (batch.n_tokens + n_toks > n_batch) {
  247. float * out = emb + p * n_embd;
  248. batch_decode(ctx, batch, out, s, n_embd);
  249. llama_batch_clear(batch);
  250. p += s;
  251. s = 0;
  252. }
  253. // add to batch
  254. batch_add_seq(batch, inp, s);
  255. s += 1;
  256. }
  257. // final batch
  258. float * out = emb + p * n_embd;
  259. batch_decode(ctx, batch, out, s, n_embd);
  260. // save embeddings to chunks
  261. for (int i = 0; i < n_chunks; i++) {
  262. chunks[i].embedding = std::vector<float>(emb + i * n_embd, emb + (i + 1) * n_embd);
  263. // clear tokens as they are no longer needed
  264. chunks[i].tokens.clear();
  265. }
  266. // start loop, receive query and return top k similar chunks based on cosine similarity
  267. std::string query;
  268. while (true) {
  269. printf("Enter query: ");
  270. std::getline(std::cin, query);
  271. std::vector<int32_t> query_tokens = llama_tokenize(ctx, query, true);
  272. struct llama_batch query_batch = llama_batch_init(n_batch, 0, 1);
  273. batch_add_seq(query_batch, query_tokens, 0);
  274. std::vector<float> query_emb(n_embd, 0);
  275. batch_decode(ctx, query_batch, query_emb.data(), 1, n_embd);
  276. llama_batch_clear(query_batch);
  277. // compute cosine similarities
  278. {
  279. std::vector<std::pair<int, float>> similarities;
  280. for (int i = 0; i < n_chunks; i++) {
  281. float sim = llama_embd_similarity_cos(chunks[i].embedding.data(), query_emb.data(), n_embd);
  282. similarities.push_back(std::make_pair(i, sim));
  283. }
  284. // sort similarities
  285. std::sort(similarities.begin(), similarities.end(), [](const std::pair<int, float> & a, const std::pair<int, float> & b) {
  286. return a.second > b.second;
  287. });
  288. printf("Top %d similar chunks:\n", params.sparams.top_k);
  289. for (int i = 0; i < std::min(params.sparams.top_k, (int) chunks.size()); i++) {
  290. printf("filename: %s\n", chunks[similarities[i].first].filename.c_str());
  291. printf("filepos: %lld\n", (long long int) chunks[similarities[i].first].filepos);
  292. printf("similarity: %f\n", similarities[i].second);
  293. printf("textdata:\n%s\n", chunks[similarities[i].first].textdata.c_str());
  294. printf("--------------------\n");
  295. }
  296. }
  297. }
  298. // clean up
  299. llama_print_timings(ctx);
  300. llama_free(ctx);
  301. llama_free_model(model);
  302. llama_backend_free();
  303. }