embedding.cpp 12 KB

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