retrieval.cpp 10.0 KB

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