1
0

embedding.cpp 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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 normalize(const float * vec, float * out, int n) {
  22. float norm = 0;
  23. for (int i = 0; i < n; i++) {
  24. norm += vec[i] * vec[i];
  25. }
  26. norm = sqrt(norm);
  27. for (int i = 0; i < n; i++) {
  28. out[i] = vec[i] / norm;
  29. }
  30. }
  31. static void batch_decode(llama_context * ctx, llama_batch & batch, float * output, int n_seq, int n_embd) {
  32. // clear previous kv_cache values (irrelevant for embeddings)
  33. llama_kv_cache_clear(ctx);
  34. // run model
  35. fprintf(stderr, "%s: n_tokens = %d, n_seq = %d\n", __func__, batch.n_tokens, n_seq);
  36. if (llama_decode(ctx, batch) < 0) {
  37. fprintf(stderr, "%s : failed to decode\n", __func__);
  38. }
  39. // normalize on copy
  40. for (int i = 0; i < batch.n_tokens; i++) {
  41. if (!batch.logits[i]) {
  42. continue;
  43. }
  44. // try to get sequence embeddings - supported only when pooling_type is not NONE
  45. const float * embd = llama_get_embeddings_seq(ctx, batch.seq_id[i][0]);
  46. if (embd == NULL) {
  47. embd = llama_get_embeddings_ith(ctx, i);
  48. if (embd == NULL) {
  49. fprintf(stderr, "%s: failed to get embeddings for token %d\n", __func__, i);
  50. continue;
  51. }
  52. }
  53. float * out = output + batch.seq_id[i][0] * n_embd;
  54. normalize(embd, out, n_embd);
  55. }
  56. }
  57. int main(int argc, char ** argv) {
  58. gpt_params params;
  59. if (!gpt_params_parse(argc, argv, params)) {
  60. return 1;
  61. }
  62. params.embedding = true;
  63. print_build_info();
  64. if (params.seed == LLAMA_DEFAULT_SEED) {
  65. params.seed = time(NULL);
  66. }
  67. fprintf(stderr, "%s: seed = %u\n", __func__, params.seed);
  68. std::mt19937 rng(params.seed);
  69. if (params.random_prompt) {
  70. params.prompt = gpt_random_prompt(rng);
  71. }
  72. llama_backend_init();
  73. llama_numa_init(params.numa);
  74. llama_model * model;
  75. llama_context * ctx;
  76. // load the model
  77. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  78. if (model == NULL) {
  79. fprintf(stderr, "%s: error: unable to load model\n", __func__);
  80. return 1;
  81. }
  82. const int n_ctx_train = llama_n_ctx_train(model);
  83. const int n_ctx = llama_n_ctx(ctx);
  84. if (n_ctx > n_ctx_train) {
  85. fprintf(stderr, "%s: warning: model was trained on only %d context tokens (%d specified)\n",
  86. __func__, n_ctx_train, n_ctx);
  87. }
  88. // print system information
  89. {
  90. fprintf(stderr, "\n");
  91. fprintf(stderr, "%s\n", get_system_info(params).c_str());
  92. }
  93. // split the prompt into lines
  94. std::vector<std::string> prompts = split_lines(params.prompt);
  95. // max batch size
  96. const uint64_t n_batch = params.n_batch;
  97. GGML_ASSERT(params.n_batch == params.n_ctx);
  98. // tokenize the prompts and trim
  99. std::vector<std::vector<int32_t>> inputs;
  100. for (const auto & prompt : prompts) {
  101. auto inp = ::llama_tokenize(ctx, prompt, true);
  102. if (inp.size() > n_batch) {
  103. inp.resize(n_batch);
  104. }
  105. inputs.push_back(inp);
  106. }
  107. // tokenization stats
  108. if (params.verbose_prompt) {
  109. for (int i = 0; i < (int) inputs.size(); i++) {
  110. fprintf(stderr, "%s: prompt %d: '%s'\n", __func__, i, prompts[i].c_str());
  111. fprintf(stderr, "%s: number of tokens in prompt = %zu\n", __func__, inputs[i].size());
  112. for (int j = 0; j < (int) inputs[i].size(); j++) {
  113. fprintf(stderr, "%6d -> '%s'\n", inputs[i][j], llama_token_to_piece(ctx, inputs[i][j]).c_str());
  114. }
  115. fprintf(stderr, "\n\n");
  116. }
  117. }
  118. // initialize batch
  119. const int n_prompts = prompts.size();
  120. struct llama_batch batch = llama_batch_init(n_batch, 0, 1);
  121. // allocate output
  122. const int n_embd = llama_n_embd(model);
  123. std::vector<float> embeddings(n_prompts * n_embd, 0);
  124. float * emb = embeddings.data();
  125. // break into batches
  126. int p = 0; // number of prompts processed already
  127. int s = 0; // number of prompts in current batch
  128. for (int k = 0; k < n_prompts; k++) {
  129. // clamp to n_batch tokens
  130. auto & inp = inputs[k];
  131. const uint64_t n_toks = inp.size();
  132. // encode if at capacity
  133. if (batch.n_tokens + n_toks > n_batch) {
  134. float * out = emb + p * n_embd;
  135. batch_decode(ctx, batch, out, s, n_embd);
  136. llama_batch_clear(batch);
  137. p += s;
  138. s = 0;
  139. }
  140. // add to batch
  141. batch_add_seq(batch, inp, s);
  142. s += 1;
  143. }
  144. // final batch
  145. float * out = emb + p * n_embd;
  146. batch_decode(ctx, batch, out, s, n_embd);
  147. // print first 3 embeddings
  148. for (int j = 0; j < std::min(3, n_prompts); j++) {
  149. fprintf(stderr, "embedding %d: ", j);
  150. for (int i = 0; i < n_embd; i++) {
  151. fprintf(stderr, "%f ", emb[j * n_embd + i]);
  152. }
  153. fprintf(stderr, "\n\n");
  154. }
  155. fprintf(stderr, "\n");
  156. // clean up
  157. llama_print_timings(ctx);
  158. llama_free(ctx);
  159. llama_free_model(model);
  160. llama_backend_free();
  161. return 0;
  162. }