retrieval.cpp 10 KB

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