retrieval.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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, int seq_id) {
  68. for (size_t i = 0; i < tokens.size(); i++) {
  69. llama_batch_add(batch, tokens[i], i, { seq_id }, i == tokens.size() - 1);
  70. }
  71. }
  72. static void batch_decode(llama_context * ctx, llama_batch & batch, float * output, int n_seq, int n_embd) {
  73. // clear previous kv_cache values (irrelevant for embeddings)
  74. llama_kv_cache_clear(ctx);
  75. // run model
  76. fprintf(stderr, "%s: n_tokens = %d, n_seq = %d\n", __func__, batch.n_tokens, n_seq);
  77. if (llama_decode(ctx, batch) < 0) {
  78. fprintf(stderr, "%s : failed to decode\n", __func__);
  79. }
  80. for (int i = 0; i < batch.n_tokens; i++) {
  81. if (!batch.logits[i]) {
  82. continue;
  83. }
  84. // try to get sequence embeddings - supported only when pooling_type is not NONE
  85. const float * embd = llama_get_embeddings_seq(ctx, batch.seq_id[i][0]);
  86. if (embd == NULL) {
  87. embd = llama_get_embeddings_ith(ctx, i);
  88. if (embd == NULL) {
  89. fprintf(stderr, "%s: failed to get embeddings for token %d\n", __func__, i);
  90. continue;
  91. }
  92. }
  93. float * out = output + batch.seq_id[i][0] * n_embd;
  94. llama_embd_normalize(embd, out, n_embd);
  95. }
  96. }
  97. int main(int argc, char ** argv) {
  98. gpt_params params;
  99. if (!gpt_params_parse(argc, argv, params)) {
  100. print_usage(argc, argv, params);
  101. return 1;
  102. }
  103. // For BERT models, batch size must be equal to ubatch size
  104. params.n_ubatch = params.n_batch;
  105. params.embedding = true;
  106. if (params.chunk_size <= 0) {
  107. fprintf(stderr, "chunk_size must be positive\n");
  108. return 1;
  109. }
  110. if (params.context_files.empty()) {
  111. fprintf(stderr, "context_files must be specified\n");
  112. return 1;
  113. }
  114. print_build_info();
  115. printf("processing files:\n");
  116. for (auto & context_file : params.context_files) {
  117. printf("%s\n", context_file.c_str());
  118. }
  119. std::vector<chunk> chunks;
  120. for (auto & context_file : params.context_files) {
  121. std::vector<chunk> file_chunk = chunk_file(context_file, params.chunk_size, params.chunk_separator);
  122. chunks.insert(chunks.end(), file_chunk.begin(), file_chunk.end());
  123. }
  124. printf("Number of chunks: %ld\n", chunks.size());
  125. llama_backend_init();
  126. llama_numa_init(params.numa);
  127. llama_model * model;
  128. llama_context * ctx;
  129. // load the model
  130. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  131. if (model == NULL) {
  132. fprintf(stderr, "%s: error: unable to load model\n", __func__);
  133. return 1;
  134. }
  135. const int n_ctx_train = llama_n_ctx_train(model);
  136. const int n_ctx = llama_n_ctx(ctx);
  137. if (n_ctx > n_ctx_train) {
  138. fprintf(stderr, "%s: warning: model was trained on only %d context tokens (%d specified)\n",
  139. __func__, n_ctx_train, n_ctx);
  140. }
  141. // print system information
  142. {
  143. fprintf(stderr, "\n");
  144. fprintf(stderr, "%s\n", gpt_params_get_system_info(params).c_str());
  145. }
  146. // max batch size
  147. const uint64_t n_batch = params.n_batch;
  148. GGML_ASSERT(params.n_batch >= params.n_ctx);
  149. // tokenize the prompts and trim
  150. for (auto & chunk : chunks) {
  151. auto inp = ::llama_tokenize(ctx, chunk.textdata, true, false);
  152. if (inp.size() > n_batch) {
  153. fprintf(stderr, "%s: error: chunk size (%lld) exceeds batch size (%lld), increase batch size and re-run\n",
  154. __func__, (long long int) inp.size(), (long long int) n_batch);
  155. return 1;
  156. }
  157. // add eos if not present
  158. if (llama_token_eos(model) >= 0 && (inp.empty() || inp.back() != llama_token_eos(model))) {
  159. inp.push_back(llama_token_eos(model));
  160. }
  161. chunk.tokens = inp;
  162. }
  163. // tokenization stats
  164. if (params.verbose_prompt) {
  165. for (int i = 0; i < (int) chunks.size(); i++) {
  166. fprintf(stderr, "%s: prompt %d: '%s'\n", __func__, i, chunks[i].textdata.c_str());
  167. fprintf(stderr, "%s: number of tokens in prompt = %zu\n", __func__, chunks[i].tokens.size());
  168. for (int j = 0; j < (int) chunks[i].tokens.size(); j++) {
  169. fprintf(stderr, "%6d -> '%s'\n", chunks[i].tokens[j], llama_token_to_piece(ctx, chunks[i].tokens[j]).c_str());
  170. }
  171. fprintf(stderr, "\n\n");
  172. }
  173. }
  174. // initialize batch
  175. const int n_chunks = chunks.size();
  176. struct llama_batch batch = llama_batch_init(n_batch, 0, 1);
  177. // allocate output
  178. const int n_embd = llama_n_embd(model);
  179. std::vector<float> embeddings(n_chunks * n_embd, 0);
  180. float * emb = embeddings.data();
  181. // break into batches
  182. int p = 0; // number of prompts processed already
  183. int s = 0; // number of prompts in current batch
  184. for (int k = 0; k < n_chunks; k++) {
  185. // clamp to n_batch tokens
  186. auto & inp = chunks[k].tokens;
  187. const uint64_t n_toks = inp.size();
  188. // encode if at capacity
  189. if (batch.n_tokens + n_toks > n_batch) {
  190. float * out = emb + p * n_embd;
  191. batch_decode(ctx, batch, out, s, n_embd);
  192. llama_batch_clear(batch);
  193. p += s;
  194. s = 0;
  195. }
  196. // add to batch
  197. batch_add_seq(batch, inp, s);
  198. s += 1;
  199. }
  200. // final batch
  201. float * out = emb + p * n_embd;
  202. batch_decode(ctx, batch, out, s, n_embd);
  203. // save embeddings to chunks
  204. for (int i = 0; i < n_chunks; i++) {
  205. chunks[i].embedding = std::vector<float>(emb + i * n_embd, emb + (i + 1) * n_embd);
  206. // clear tokens as they are no longer needed
  207. chunks[i].tokens.clear();
  208. }
  209. // start loop, receive query and return top k similar chunks based on cosine similarity
  210. std::string query;
  211. while (true) {
  212. printf("Enter query: ");
  213. std::getline(std::cin, query);
  214. std::vector<int32_t> query_tokens = llama_tokenize(ctx, query, true);
  215. struct llama_batch query_batch = llama_batch_init(n_batch, 0, 1);
  216. batch_add_seq(query_batch, query_tokens, 0);
  217. std::vector<float> query_emb(n_embd, 0);
  218. batch_decode(ctx, query_batch, query_emb.data(), 1, n_embd);
  219. llama_batch_clear(query_batch);
  220. // compute cosine similarities
  221. {
  222. std::vector<std::pair<int, float>> similarities;
  223. for (int i = 0; i < n_chunks; i++) {
  224. float sim = llama_embd_similarity_cos(chunks[i].embedding.data(), query_emb.data(), n_embd);
  225. similarities.push_back(std::make_pair(i, sim));
  226. }
  227. // sort similarities
  228. std::sort(similarities.begin(), similarities.end(), [](const std::pair<int, float> & a, const std::pair<int, float> & b) {
  229. return a.second > b.second;
  230. });
  231. printf("Top %d similar chunks:\n", params.sparams.top_k);
  232. for (int i = 0; i < std::min(params.sparams.top_k, (int) chunks.size()); i++) {
  233. printf("filename: %s\n", chunks[similarities[i].first].filename.c_str());
  234. printf("filepos: %lld\n", (long long int) chunks[similarities[i].first].filepos);
  235. printf("similarity: %f\n", similarities[i].second);
  236. printf("textdata:\n%s\n", chunks[similarities[i].first].textdata.c_str());
  237. printf("--------------------\n");
  238. }
  239. }
  240. }
  241. // clean up
  242. llama_print_timings(ctx);
  243. llama_free(ctx);
  244. llama_free_model(model);
  245. llama_backend_free();
  246. }