embedding.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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, const std::string & separator = "\n") {
  8. std::vector<std::string> lines;
  9. size_t start = 0;
  10. size_t end = s.find(separator);
  11. while (end != std::string::npos) {
  12. lines.push_back(s.substr(start, end - start));
  13. start = end + separator.length();
  14. end = s.find(separator, start);
  15. }
  16. lines.push_back(s.substr(start)); // Add the last part
  17. return lines;
  18. }
  19. static void batch_add_seq(llama_batch & batch, const std::vector<int32_t> & tokens, llama_seq_id seq_id) {
  20. size_t n_tokens = tokens.size();
  21. for (size_t i = 0; i < n_tokens; i++) {
  22. llama_batch_add(batch, tokens[i], i, { seq_id }, true);
  23. }
  24. }
  25. static void batch_decode(llama_context * ctx, llama_batch & batch, float * output, int n_seq, int n_embd, int embd_norm) {
  26. // clear previous kv_cache values (irrelevant for embeddings)
  27. llama_kv_cache_clear(ctx);
  28. // run model
  29. fprintf(stderr, "%s: n_tokens = %d, n_seq = %d\n", __func__, batch.n_tokens, n_seq);
  30. if (llama_decode(ctx, batch) < 0) {
  31. fprintf(stderr, "%s : failed to decode\n", __func__);
  32. }
  33. for (int i = 0; i < batch.n_tokens; i++) {
  34. if (!batch.logits[i]) {
  35. continue;
  36. }
  37. // try to get sequence embeddings - supported only when pooling_type is not NONE
  38. const float * embd = llama_get_embeddings_seq(ctx, batch.seq_id[i][0]);
  39. GGML_ASSERT(embd != NULL && "failed to get sequence embeddings");
  40. float * out = output + batch.seq_id[i][0] * n_embd;
  41. llama_embd_normalize(embd, out, n_embd, embd_norm);
  42. }
  43. }
  44. int main(int argc, char ** argv) {
  45. gpt_params params;
  46. if (!gpt_params_parse(argc, argv, params)) {
  47. gpt_params_print_usage(argc, argv, params);
  48. return 1;
  49. }
  50. params.embedding = true;
  51. // For non-causal models, batch size must be equal to ubatch size
  52. params.n_ubatch = params.n_batch;
  53. print_build_info();
  54. if (params.seed == LLAMA_DEFAULT_SEED) {
  55. params.seed = time(NULL);
  56. }
  57. fprintf(stderr, "%s: seed = %u\n", __func__, params.seed);
  58. std::mt19937 rng(params.seed);
  59. llama_backend_init();
  60. llama_numa_init(params.numa);
  61. llama_model * model;
  62. llama_context * ctx;
  63. // load the model
  64. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  65. if (model == NULL) {
  66. fprintf(stderr, "%s: error: unable to load model\n", __func__);
  67. return 1;
  68. }
  69. const int n_ctx_train = llama_n_ctx_train(model);
  70. const int n_ctx = llama_n_ctx(ctx);
  71. const enum llama_pooling_type pooling_type = llama_pooling_type(ctx);
  72. if (pooling_type == LLAMA_POOLING_TYPE_NONE) {
  73. fprintf(stderr, "%s: error: pooling type NONE not supported\n", __func__);
  74. return 1;
  75. }
  76. if (n_ctx > n_ctx_train) {
  77. fprintf(stderr, "%s: warning: model was trained on only %d context tokens (%d specified)\n",
  78. __func__, n_ctx_train, n_ctx);
  79. }
  80. // print system information
  81. {
  82. fprintf(stderr, "\n");
  83. fprintf(stderr, "%s\n", gpt_params_get_system_info(params).c_str());
  84. }
  85. // split the prompt into lines
  86. std::vector<std::string> prompts = split_lines(params.prompt, params.embd_sep);
  87. // max batch size
  88. const uint64_t n_batch = params.n_batch;
  89. GGML_ASSERT(params.n_batch >= params.n_ctx);
  90. // tokenize the prompts and trim
  91. std::vector<std::vector<int32_t>> inputs;
  92. for (const auto & prompt : prompts) {
  93. auto inp = ::llama_tokenize(ctx, prompt, true, false);
  94. if (inp.size() > n_batch) {
  95. fprintf(stderr, "%s: error: number of tokens in input line (%lld) exceeds batch size (%lld), increase batch size and re-run\n",
  96. __func__, (long long int) inp.size(), (long long int) n_batch);
  97. return 1;
  98. }
  99. inputs.push_back(inp);
  100. }
  101. // check if the last token is SEP
  102. // it should be automatically added by the tokenizer when 'tokenizer.ggml.add_eos_token' is set to 'true'
  103. for (auto & inp : inputs) {
  104. if (inp.empty() || inp.back() != llama_token_sep(model)) {
  105. fprintf(stderr, "%s: warning: last token in the prompt is not SEP\n", __func__);
  106. fprintf(stderr, "%s: 'tokenizer.ggml.add_eos_token' should be set to 'true' in the GGUF header\n", __func__);
  107. }
  108. }
  109. // tokenization stats
  110. if (params.verbose_prompt) {
  111. for (int i = 0; i < (int) inputs.size(); i++) {
  112. fprintf(stderr, "%s: prompt %d: '%s'\n", __func__, i, prompts[i].c_str());
  113. fprintf(stderr, "%s: number of tokens in prompt = %zu\n", __func__, inputs[i].size());
  114. for (int j = 0; j < (int) inputs[i].size(); j++) {
  115. fprintf(stderr, "%6d -> '%s'\n", inputs[i][j], llama_token_to_piece(ctx, inputs[i][j]).c_str());
  116. }
  117. fprintf(stderr, "\n\n");
  118. }
  119. }
  120. // initialize batch
  121. const int n_prompts = prompts.size();
  122. struct llama_batch batch = llama_batch_init(n_batch, 0, 1);
  123. // allocate output
  124. const int n_embd = llama_n_embd(model);
  125. std::vector<float> embeddings(n_prompts * n_embd, 0);
  126. float * emb = embeddings.data();
  127. // break into batches
  128. int p = 0; // number of prompts processed already
  129. int s = 0; // number of prompts in current batch
  130. for (int k = 0; k < n_prompts; k++) {
  131. // clamp to n_batch tokens
  132. auto & inp = inputs[k];
  133. const uint64_t n_toks = inp.size();
  134. // encode if at capacity
  135. if (batch.n_tokens + n_toks > n_batch) {
  136. float * out = emb + p * n_embd;
  137. batch_decode(ctx, batch, out, s, n_embd, params.embd_normalize);
  138. llama_batch_clear(batch);
  139. p += s;
  140. s = 0;
  141. }
  142. // add to batch
  143. batch_add_seq(batch, inp, s);
  144. s += 1;
  145. }
  146. // final batch
  147. float * out = emb + p * n_embd;
  148. batch_decode(ctx, batch, out, s, n_embd, params.embd_normalize);
  149. if (params.embd_out.empty()) {
  150. // print the first part of the embeddings or for a single prompt, the full embedding
  151. fprintf(stdout, "\n");
  152. for (int j = 0; j < n_prompts; j++) {
  153. fprintf(stdout, "embedding %d: ", j);
  154. for (int i = 0; i < (n_prompts > 1 ? std::min(16, n_embd) : n_embd); i++) {
  155. if (params.embd_normalize == 0) {
  156. fprintf(stdout, "%6.0f ", emb[j * n_embd + i]);
  157. } else {
  158. fprintf(stdout, "%9.6f ", emb[j * n_embd + i]);
  159. }
  160. }
  161. fprintf(stdout, "\n");
  162. }
  163. // print cosine similarity matrix
  164. if (n_prompts > 1) {
  165. fprintf(stdout, "\n");
  166. printf("cosine similarity matrix:\n\n");
  167. for (int i = 0; i < n_prompts; i++) {
  168. fprintf(stdout, "%6.6s ", prompts[i].c_str());
  169. }
  170. fprintf(stdout, "\n");
  171. for (int i = 0; i < n_prompts; i++) {
  172. for (int j = 0; j < n_prompts; j++) {
  173. float sim = llama_embd_similarity_cos(emb + i * n_embd, emb + j * n_embd, n_embd);
  174. fprintf(stdout, "%6.2f ", sim);
  175. }
  176. fprintf(stdout, "%1.10s", prompts[i].c_str());
  177. fprintf(stdout, "\n");
  178. }
  179. }
  180. }
  181. if (params.embd_out == "json" || params.embd_out == "json+" || params.embd_out == "array") {
  182. const bool notArray = params.embd_out != "array";
  183. fprintf(stdout, notArray ? "{\n \"object\": \"list\",\n \"data\": [\n" : "[");
  184. for (int j = 0;;) { // at least one iteration (one prompt)
  185. if (notArray) fprintf(stdout, " {\n \"object\": \"embedding\",\n \"index\": %d,\n \"embedding\": ",j);
  186. fprintf(stdout, "[");
  187. for (int i = 0;;) { // at least one iteration (n_embd > 0)
  188. fprintf(stdout, params.embd_normalize == 0 ? "%1.0f" : "%1.7f", emb[j * n_embd + i]);
  189. i++;
  190. if (i < n_embd) fprintf(stdout, ","); else break;
  191. }
  192. fprintf(stdout, notArray ? "]\n }" : "]");
  193. j++;
  194. if (j < n_prompts) fprintf(stdout, notArray ? ",\n" : ","); else break;
  195. }
  196. fprintf(stdout, notArray ? "\n ]" : "]\n");
  197. if (params.embd_out == "json+" && n_prompts > 1) {
  198. fprintf(stdout, ",\n \"cosineSimilarity\": [\n");
  199. for (int i = 0;;) { // at least two iteration (n_prompts > 1)
  200. fprintf(stdout, " [");
  201. for (int j = 0;;) { // at least two iteration (n_prompts > 1)
  202. float sim = llama_embd_similarity_cos(emb + i * n_embd, emb + j * n_embd, n_embd);
  203. fprintf(stdout, "%6.2f", sim);
  204. j++;
  205. if (j < n_prompts) fprintf(stdout, ", "); else break;
  206. }
  207. fprintf(stdout, " ]");
  208. i++;
  209. if (i < n_prompts) fprintf(stdout, ",\n"); else break;
  210. }
  211. fprintf(stdout, "\n ]");
  212. }
  213. if (notArray) fprintf(stdout, "\n}\n");
  214. }
  215. // clean up
  216. llama_print_timings(ctx);
  217. llama_batch_free(batch);
  218. llama_free(ctx);
  219. llama_free_model(model);
  220. llama_backend_free();
  221. return 0;
  222. }