retrieval.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. #include "common.h"
  2. #include "llama.h"
  3. #include <algorithm>
  4. #include <fstream>
  5. static void print_usage(int, char ** argv) {
  6. LOG_TEE("\nexample usage:\n");
  7. 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]);
  8. LOG_TEE("\n");
  9. }
  10. struct chunk {
  11. // filename
  12. std::string filename;
  13. // original file position
  14. size_t filepos;
  15. // original text data
  16. std::string textdata = "";
  17. // tokenized text data
  18. std::vector<llama_token> tokens;
  19. // embedding
  20. std::vector<float> embedding;
  21. };
  22. // chunk file data to chunks of size >= chunk_size
  23. // chunk_separator is the separator between chunks
  24. static std::vector<chunk> chunk_file(const std::string & filename, int chunk_size, const std::string & chunk_separator) {
  25. std::vector<chunk> chunks;
  26. std::ifstream f(filename.c_str());
  27. if (!f.is_open()) {
  28. fprintf(stderr, "Error: could not open file %s\n", filename.c_str());
  29. return chunks;
  30. }
  31. chunk current_chunk;
  32. char buffer[1024];
  33. int64_t filepos = 0;
  34. std::string current = "";
  35. while (f.read(buffer, 1024)) {
  36. current += std::string(buffer, f.gcount());
  37. size_t pos;
  38. while ((pos = current.find(chunk_separator)) != std::string::npos) {
  39. current_chunk.textdata += current.substr(0, pos + chunk_separator.size());
  40. if ((int) current_chunk.textdata.size() > chunk_size) {
  41. // save chunk
  42. current_chunk.filepos = filepos;
  43. current_chunk.filename = filename;
  44. chunks.push_back(current_chunk);
  45. // update filepos
  46. filepos += (int) current_chunk.textdata.size();
  47. // reset current_chunk
  48. current_chunk = chunk();
  49. }
  50. current = current.substr(pos + chunk_separator.size());
  51. }
  52. }
  53. // add leftover data to last chunk
  54. if (current_chunk.textdata.size() > 0) {
  55. if (chunks.empty()) {
  56. current_chunk.filepos = filepos;
  57. current_chunk.filename = filename;
  58. chunks.push_back(current_chunk);
  59. } else {
  60. chunks.back().textdata += current_chunk.textdata;
  61. }
  62. }
  63. f.close();
  64. return chunks;
  65. }
  66. static void batch_add_seq(llama_batch & batch, const std::vector<int32_t> & tokens, llama_seq_id seq_id) {
  67. size_t n_tokens = tokens.size();
  68. for (size_t i = 0; i < n_tokens; i++) {
  69. llama_batch_add(batch, tokens[i], i, { seq_id }, true);
  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. auto options = gpt_params_parser_init(params, LLAMA_EXAMPLE_RETRIEVAL, print_usage);
  100. if (!gpt_params_parse(argc, argv, params, options)) {
  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. // load the model
  128. llama_init_result llama_init = llama_init_from_gpt_params(params);
  129. llama_model * model = llama_init.model;
  130. llama_context * ctx = llama_init.context;
  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. const enum llama_pooling_type pooling_type = llama_pooling_type(ctx);
  138. if (pooling_type == LLAMA_POOLING_TYPE_NONE) {
  139. fprintf(stderr, "%s: error: pooling type NONE not supported\n", __func__);
  140. return 1;
  141. }
  142. if (n_ctx > n_ctx_train) {
  143. fprintf(stderr, "%s: warning: model was trained on only %d context tokens (%d specified)\n",
  144. __func__, n_ctx_train, n_ctx);
  145. }
  146. // print system information
  147. {
  148. fprintf(stderr, "\n");
  149. fprintf(stderr, "%s\n", gpt_params_get_system_info(params).c_str());
  150. }
  151. // max batch size
  152. const uint64_t n_batch = params.n_batch;
  153. GGML_ASSERT(params.n_batch >= params.n_ctx);
  154. // tokenize the prompts and trim
  155. for (auto & chunk : chunks) {
  156. auto inp = ::llama_tokenize(ctx, chunk.textdata, true, false);
  157. if (inp.size() > n_batch) {
  158. fprintf(stderr, "%s: error: chunk size (%lld) exceeds batch size (%lld), increase batch size and re-run\n",
  159. __func__, (long long int) inp.size(), (long long int) n_batch);
  160. return 1;
  161. }
  162. // add eos if not present
  163. if (llama_token_eos(model) >= 0 && (inp.empty() || inp.back() != llama_token_eos(model))) {
  164. inp.push_back(llama_token_eos(model));
  165. }
  166. chunk.tokens = inp;
  167. }
  168. // tokenization stats
  169. if (params.verbose_prompt) {
  170. for (int i = 0; i < (int) chunks.size(); i++) {
  171. fprintf(stderr, "%s: prompt %d: '%s'\n", __func__, i, chunks[i].textdata.c_str());
  172. fprintf(stderr, "%s: number of tokens in prompt = %zu\n", __func__, chunks[i].tokens.size());
  173. for (int j = 0; j < (int) chunks[i].tokens.size(); j++) {
  174. fprintf(stderr, "%6d -> '%s'\n", chunks[i].tokens[j], llama_token_to_piece(ctx, chunks[i].tokens[j]).c_str());
  175. }
  176. fprintf(stderr, "\n\n");
  177. }
  178. }
  179. // initialize batch
  180. const int n_chunks = chunks.size();
  181. struct llama_batch batch = llama_batch_init(n_batch, 0, 1);
  182. // allocate output
  183. const int n_embd = llama_n_embd(model);
  184. std::vector<float> embeddings(n_chunks * n_embd, 0);
  185. float * emb = embeddings.data();
  186. // break into batches
  187. int p = 0; // number of prompts processed already
  188. int s = 0; // number of prompts in current batch
  189. for (int k = 0; k < n_chunks; k++) {
  190. // clamp to n_batch tokens
  191. auto & inp = chunks[k].tokens;
  192. const uint64_t n_toks = inp.size();
  193. // encode if at capacity
  194. if (batch.n_tokens + n_toks > n_batch) {
  195. float * out = emb + p * n_embd;
  196. batch_decode(ctx, batch, out, s, n_embd);
  197. llama_batch_clear(batch);
  198. p += s;
  199. s = 0;
  200. }
  201. // add to batch
  202. batch_add_seq(batch, inp, s);
  203. s += 1;
  204. }
  205. // final batch
  206. float * out = emb + p * n_embd;
  207. batch_decode(ctx, batch, out, s, n_embd);
  208. // save embeddings to chunks
  209. for (int i = 0; i < n_chunks; i++) {
  210. chunks[i].embedding = std::vector<float>(emb + i * n_embd, emb + (i + 1) * n_embd);
  211. // clear tokens as they are no longer needed
  212. chunks[i].tokens.clear();
  213. }
  214. struct llama_batch query_batch = llama_batch_init(n_batch, 0, 1);
  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. batch_add_seq(query_batch, query_tokens, 0);
  222. std::vector<float> query_emb(n_embd, 0);
  223. batch_decode(ctx, query_batch, query_emb.data(), 1, n_embd);
  224. llama_batch_clear(query_batch);
  225. // compute cosine similarities
  226. {
  227. std::vector<std::pair<int, float>> similarities;
  228. for (int i = 0; i < n_chunks; i++) {
  229. float sim = llama_embd_similarity_cos(chunks[i].embedding.data(), query_emb.data(), n_embd);
  230. similarities.push_back(std::make_pair(i, sim));
  231. }
  232. // sort similarities
  233. std::sort(similarities.begin(), similarities.end(), [](const std::pair<int, float> & a, const std::pair<int, float> & b) {
  234. return a.second > b.second;
  235. });
  236. printf("Top %d similar chunks:\n", params.sparams.top_k);
  237. for (int i = 0; i < std::min(params.sparams.top_k, (int) chunks.size()); i++) {
  238. printf("filename: %s\n", chunks[similarities[i].first].filename.c_str());
  239. printf("filepos: %lld\n", (long long int) chunks[similarities[i].first].filepos);
  240. printf("similarity: %f\n", similarities[i].second);
  241. printf("textdata:\n%s\n", chunks[similarities[i].first].textdata.c_str());
  242. printf("--------------------\n");
  243. }
  244. }
  245. }
  246. LOG_TEE("\n");
  247. llama_perf_print(ctx, LLAMA_PERF_TYPE_CONTEXT);
  248. // clean up
  249. llama_batch_free(query_batch);
  250. llama_free(ctx);
  251. llama_free_model(model);
  252. llama_backend_free();
  253. }