embedding.cpp 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. #include "common.h"
  2. #include "llama.h"
  3. #include <ctime>
  4. #if defined(_MSC_VER)
  5. #pragma warning(disable: 4244 4267) // possible loss of data
  6. #endif
  7. static std::vector<std::string> split_lines(const std::string & s) {
  8. std::string line;
  9. std::vector<std::string> lines;
  10. std::stringstream ss(s);
  11. while (std::getline(ss, line)) {
  12. lines.push_back(line);
  13. }
  14. return lines;
  15. }
  16. static void batch_add_seq(llama_batch & batch, const std::vector<int32_t> & tokens, int seq_id) {
  17. for (size_t i = 0; i < tokens.size(); i++) {
  18. llama_batch_add(batch, tokens[i], i, { seq_id }, i == tokens.size() - 1);
  19. }
  20. }
  21. static void batch_decode(llama_context * ctx, llama_batch & batch, float * output, int n_seq, int n_embd) {
  22. // clear previous kv_cache values (irrelevant for embeddings)
  23. llama_kv_cache_clear(ctx);
  24. // run model
  25. fprintf(stderr, "%s: n_tokens = %d, n_seq = %d\n", __func__, batch.n_tokens, n_seq);
  26. if (llama_decode(ctx, batch) < 0) {
  27. fprintf(stderr, "%s : failed to decode\n", __func__);
  28. }
  29. for (int i = 0; i < batch.n_tokens; i++) {
  30. if (!batch.logits[i]) {
  31. continue;
  32. }
  33. // try to get sequence embeddings - supported only when pooling_type is not NONE
  34. const float * embd = llama_get_embeddings_seq(ctx, batch.seq_id[i][0]);
  35. if (embd == NULL) {
  36. embd = llama_get_embeddings_ith(ctx, i);
  37. if (embd == NULL) {
  38. fprintf(stderr, "%s: failed to get embeddings for token %d\n", __func__, i);
  39. continue;
  40. }
  41. }
  42. float * out = output + batch.seq_id[i][0] * n_embd;
  43. //TODO: I would also add a parameter here to enable normalization or not.
  44. /*fprintf(stdout, "unnormalized_embedding:");
  45. for (int hh = 0; hh < n_embd; hh++) {
  46. fprintf(stdout, "%9.6f ", embd[hh]);
  47. }
  48. fprintf(stdout, "\n");*/
  49. llama_embd_normalize(embd, out, n_embd);
  50. }
  51. }
  52. int main(int argc, char ** argv) {
  53. gpt_params params;
  54. if (!gpt_params_parse(argc, argv, params)) {
  55. gpt_params_print_usage(argc, argv, params);
  56. return 1;
  57. }
  58. params.embedding = true;
  59. // For non-causal models, batch size must be equal to ubatch size
  60. params.n_ubatch = params.n_batch;
  61. print_build_info();
  62. if (params.seed == LLAMA_DEFAULT_SEED) {
  63. params.seed = time(NULL);
  64. }
  65. fprintf(stderr, "%s: seed = %u\n", __func__, params.seed);
  66. std::mt19937 rng(params.seed);
  67. llama_backend_init();
  68. llama_numa_init(params.numa);
  69. llama_model * model;
  70. llama_context * ctx;
  71. // load the model
  72. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  73. if (model == NULL) {
  74. fprintf(stderr, "%s: error: unable to load model\n", __func__);
  75. return 1;
  76. }
  77. const int n_ctx_train = llama_n_ctx_train(model);
  78. const int n_ctx = llama_n_ctx(ctx);
  79. if (n_ctx > n_ctx_train) {
  80. fprintf(stderr, "%s: warning: model was trained on only %d context tokens (%d specified)\n",
  81. __func__, n_ctx_train, n_ctx);
  82. }
  83. // print system information
  84. {
  85. fprintf(stderr, "\n");
  86. fprintf(stderr, "%s\n", gpt_params_get_system_info(params).c_str());
  87. }
  88. // split the prompt into lines
  89. std::vector<std::string> prompts = split_lines(params.prompt);
  90. // max batch size
  91. const uint64_t n_batch = params.n_batch;
  92. GGML_ASSERT(params.n_batch >= params.n_ctx);
  93. // tokenize the prompts and trim
  94. std::vector<std::vector<int32_t>> inputs;
  95. for (const auto & prompt : prompts) {
  96. auto inp = ::llama_tokenize(ctx, prompt, true, false);
  97. if (inp.size() > n_batch) {
  98. fprintf(stderr, "%s: error: number of tokens in input line (%lld) exceeds batch size (%lld), increase batch size and re-run\n",
  99. __func__, (long long int) inp.size(), (long long int) n_batch);
  100. return 1;
  101. }
  102. inputs.push_back(inp);
  103. }
  104. // check if the last token is SEP
  105. // it should be automatically added by the tokenizer when 'tokenizer.ggml.add_eos_token' is set to 'true'
  106. for (auto & inp : inputs) {
  107. if (inp.empty() || inp.back() != llama_token_sep(model)) {
  108. fprintf(stderr, "%s: warning: last token in the prompt is not SEP\n", __func__);
  109. fprintf(stderr, "%s: 'tokenizer.ggml.add_eos_token' should be set to 'true' in the GGUF header\n", __func__);
  110. }
  111. }
  112. // tokenization stats
  113. if (params.verbose_prompt) {
  114. for (int i = 0; i < (int) inputs.size(); i++) {
  115. fprintf(stderr, "%s: prompt %d: '%s'\n", __func__, i, prompts[i].c_str());
  116. fprintf(stderr, "%s: number of tokens in prompt = %zu\n", __func__, inputs[i].size());
  117. for (int j = 0; j < (int) inputs[i].size(); j++) {
  118. fprintf(stderr, "%6d -> '%s'\n", inputs[i][j], llama_token_to_piece(ctx, inputs[i][j]).c_str());
  119. }
  120. fprintf(stderr, "\n\n");
  121. }
  122. }
  123. // initialize batch
  124. const int n_prompts = prompts.size();
  125. struct llama_batch batch = llama_batch_init(n_batch, 0, 1);
  126. // allocate output
  127. const int n_embd = llama_n_embd(model);
  128. std::vector<float> embeddings(n_prompts * n_embd, 0);
  129. float * emb = embeddings.data();
  130. // break into batches
  131. int p = 0; // number of prompts processed already
  132. int s = 0; // number of prompts in current batch
  133. for (int k = 0; k < n_prompts; k++) {
  134. // clamp to n_batch tokens
  135. auto & inp = inputs[k];
  136. const uint64_t n_toks = inp.size();
  137. // encode if at capacity
  138. if (batch.n_tokens + n_toks > n_batch) {
  139. float * out = emb + p * n_embd;
  140. batch_decode(ctx, batch, out, s, n_embd);
  141. llama_batch_clear(batch);
  142. p += s;
  143. s = 0;
  144. }
  145. // add to batch
  146. batch_add_seq(batch, inp, s);
  147. s += 1;
  148. }
  149. // final batch
  150. float * out = emb + p * n_embd;
  151. batch_decode(ctx, batch, out, s, n_embd);
  152. // print the first part of the embeddings or for a single prompt, the full embedding
  153. fprintf(stdout, "\n");
  154. for (int j = 0; j < n_prompts; j++) {
  155. fprintf(stdout, "embedding %d: ", j);
  156. for (int i = 0; i < (n_prompts > 1 ? std::min(16, n_embd) : n_embd); i++) {
  157. fprintf(stdout, "%9.6f ", emb[j * n_embd + i]);
  158. }
  159. fprintf(stdout, "\n");
  160. }
  161. // print cosine similarity matrix
  162. if (n_prompts > 1) {
  163. fprintf(stdout, "\n");
  164. printf("cosine similarity matrix:\n\n");
  165. for (int i = 0; i < n_prompts; i++) {
  166. for (int j = 0; j < n_prompts; j++) {
  167. float sim = llama_embd_similarity_cos(emb + i * n_embd, emb + j * n_embd, n_embd);
  168. fprintf(stdout, "%6.2f ", sim);
  169. }
  170. fprintf(stdout, "\n");
  171. }
  172. }
  173. // clean up
  174. llama_print_timings(ctx);
  175. llama_batch_free(batch);
  176. llama_free(ctx);
  177. llama_free_model(model);
  178. llama_backend_free();
  179. return 0;
  180. }