embedding.cpp 11 KB

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