1
0

embedding.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. #include "arg.h"
  2. #include "common.h"
  3. #include "log.h"
  4. #include "llama.h"
  5. #include <ctime>
  6. #include <algorithm>
  7. #if defined(_MSC_VER)
  8. #pragma warning(disable: 4244 4267) // possible loss of data
  9. #endif
  10. static std::vector<std::string> split_lines(const std::string & s, const std::string & separator = "\n") {
  11. std::vector<std::string> lines;
  12. size_t start = 0;
  13. size_t end = s.find(separator);
  14. while (end != std::string::npos) {
  15. lines.push_back(s.substr(start, end - start));
  16. start = end + separator.length();
  17. end = s.find(separator, start);
  18. }
  19. lines.push_back(s.substr(start)); // Add the last part
  20. return lines;
  21. }
  22. static void batch_add_seq(llama_batch & batch, const std::vector<int32_t> & tokens, llama_seq_id seq_id) {
  23. size_t n_tokens = tokens.size();
  24. for (size_t i = 0; i < n_tokens; i++) {
  25. common_batch_add(batch, tokens[i], i, { seq_id }, true);
  26. }
  27. }
  28. static void batch_decode(llama_context * ctx, llama_batch & batch, float * output, int n_seq, int n_embd, int embd_norm) {
  29. const enum llama_pooling_type pooling_type = llama_pooling_type(ctx);
  30. // clear previous kv_cache values (irrelevant for embeddings)
  31. llama_memory_clear(llama_get_memory(ctx), true);
  32. // run model
  33. LOG_INF("%s: n_tokens = %d, n_seq = %d\n", __func__, batch.n_tokens, n_seq);
  34. if (llama_decode(ctx, batch) < 0) {
  35. LOG_ERR("%s : failed to process\n", __func__);
  36. }
  37. for (int i = 0; i < batch.n_tokens; i++) {
  38. if (!batch.logits[i]) {
  39. continue;
  40. }
  41. const float * embd = nullptr;
  42. int embd_pos = 0;
  43. if (pooling_type == LLAMA_POOLING_TYPE_NONE) {
  44. // try to get token embeddings
  45. embd = llama_get_embeddings_ith(ctx, i);
  46. embd_pos = i;
  47. GGML_ASSERT(embd != NULL && "failed to get token embeddings");
  48. } else {
  49. // try to get sequence embeddings - supported only when pooling_type is not NONE
  50. embd = llama_get_embeddings_seq(ctx, batch.seq_id[i][0]);
  51. embd_pos = batch.seq_id[i][0];
  52. GGML_ASSERT(embd != NULL && "failed to get sequence embeddings");
  53. }
  54. float * out = output + embd_pos * n_embd;
  55. common_embd_normalize(embd, out, n_embd, embd_norm);
  56. }
  57. }
  58. int main(int argc, char ** argv) {
  59. common_params params;
  60. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_EMBEDDING)) {
  61. return 1;
  62. }
  63. common_init();
  64. params.embedding = true;
  65. // if the number of prompts that would be encoded is known in advance, it's more efficient to specify the
  66. // --parallel argument accordingly. for convenience, if not specified, we fallback to unified KV cache
  67. // in order to support any number of prompts
  68. if (params.n_parallel == 1) {
  69. LOG_INF("%s: n_parallel == 1 -> unified KV cache is enabled\n", __func__);
  70. params.kv_unified = true;
  71. }
  72. // utilize the full context
  73. if (params.n_batch < params.n_ctx) {
  74. LOG_WRN("%s: setting batch size to %d\n", __func__, params.n_ctx);
  75. params.n_batch = params.n_ctx;
  76. }
  77. // For non-causal models, batch size must be equal to ubatch size
  78. params.n_ubatch = params.n_batch;
  79. llama_backend_init();
  80. llama_numa_init(params.numa);
  81. // load the model
  82. common_init_result llama_init = common_init_from_params(params);
  83. llama_model * model = llama_init.model.get();
  84. llama_context * ctx = llama_init.context.get();
  85. if (model == NULL) {
  86. LOG_ERR("%s: unable to load model\n", __func__);
  87. return 1;
  88. }
  89. const llama_vocab * vocab = llama_model_get_vocab(model);
  90. const int n_ctx_train = llama_model_n_ctx_train(model);
  91. const int n_ctx = llama_n_ctx(ctx);
  92. const enum llama_pooling_type pooling_type = llama_pooling_type(ctx);
  93. if (llama_model_has_encoder(model) && llama_model_has_decoder(model)) {
  94. LOG_ERR("%s: computing embeddings in encoder-decoder models is not supported\n", __func__);
  95. return 1;
  96. }
  97. if (n_ctx > n_ctx_train) {
  98. LOG_WRN("%s: warning: model was trained on only %d context tokens (%d specified)\n",
  99. __func__, n_ctx_train, n_ctx);
  100. }
  101. // print system information
  102. {
  103. LOG_INF("\n");
  104. LOG_INF("%s\n", common_params_get_system_info(params).c_str());
  105. }
  106. // split the prompt into lines
  107. std::vector<std::string> prompts = split_lines(params.prompt, params.embd_sep);
  108. // max batch size
  109. const uint64_t n_batch = params.n_batch;
  110. // get added sep and eos token, if any
  111. const std::string added_sep_token = llama_vocab_get_add_sep(vocab) ? llama_vocab_get_text(vocab, llama_vocab_sep(vocab)) : "";
  112. const std::string added_eos_token = llama_vocab_get_add_eos(vocab) ? llama_vocab_get_text(vocab, llama_vocab_eos(vocab)) : "";
  113. // tokenize the prompts and trim
  114. std::vector<std::vector<int32_t>> inputs;
  115. for (const auto & prompt : prompts) {
  116. std::vector<llama_token> inp;
  117. // split classification pairs and insert expected separator tokens
  118. if (pooling_type == LLAMA_POOLING_TYPE_RANK && prompt.find(params.cls_sep) != std::string::npos) {
  119. std::vector<std::string> pairs = split_lines(prompt, params.cls_sep);
  120. std::string final_prompt;
  121. for (size_t i = 0; i < pairs.size(); i++) {
  122. final_prompt += pairs[i];
  123. if (i != pairs.size() - 1) {
  124. if (!added_eos_token.empty()) {
  125. final_prompt += added_eos_token;
  126. }
  127. if (!added_sep_token.empty()) {
  128. final_prompt += added_sep_token;
  129. }
  130. }
  131. }
  132. inp = common_tokenize(ctx, final_prompt, true, true);
  133. } else {
  134. inp = common_tokenize(ctx, prompt, true, true);
  135. }
  136. if (inp.size() > n_batch) {
  137. LOG_ERR("%s: number of tokens in input line (%lld) exceeds batch size (%lld), increase batch size and re-run\n",
  138. __func__, (long long int) inp.size(), (long long int) n_batch);
  139. return 1;
  140. }
  141. inputs.push_back(inp);
  142. }
  143. // check if the last token is SEP/EOS
  144. // it should be automatically added by the tokenizer when 'tokenizer.ggml.add_eos_token' is set to 'true'
  145. for (auto & inp : inputs) {
  146. if (inp.empty() || (inp.back() != llama_vocab_sep(vocab) && inp.back() != llama_vocab_eos(vocab))) {
  147. LOG_WRN("%s: last token in the prompt is not SEP or EOS\n", __func__);
  148. LOG_WRN("%s: 'tokenizer.ggml.add_eos_token' should be set to 'true' in the GGUF header\n", __func__);
  149. }
  150. }
  151. // tokenization stats
  152. if (params.verbose_prompt) {
  153. for (int i = 0; i < (int) inputs.size(); i++) {
  154. LOG_INF("%s: prompt %d: '%s'\n", __func__, i, prompts[i].c_str());
  155. LOG_INF("%s: number of tokens in prompt = %zu\n", __func__, inputs[i].size());
  156. for (int j = 0; j < (int) inputs[i].size(); j++) {
  157. LOG("%6d -> '%s'\n", inputs[i][j], common_token_to_piece(ctx, inputs[i][j]).c_str());
  158. }
  159. LOG("\n\n");
  160. }
  161. }
  162. // initialize batch
  163. const int n_prompts = prompts.size();
  164. struct llama_batch batch = llama_batch_init(n_batch, 0, 1);
  165. // count number of embeddings
  166. int n_embd_count = 0;
  167. if (pooling_type == LLAMA_POOLING_TYPE_NONE) {
  168. for (int k = 0; k < n_prompts; k++) {
  169. n_embd_count += inputs[k].size();
  170. }
  171. } else {
  172. n_embd_count = n_prompts;
  173. }
  174. // allocate output
  175. const int n_embd = llama_model_n_embd(model);
  176. std::vector<float> embeddings(n_embd_count * n_embd, 0);
  177. float * emb = embeddings.data();
  178. // break into batches
  179. int e = 0; // number of embeddings already stored
  180. int s = 0; // number of prompts in current batch
  181. for (int k = 0; k < n_prompts; k++) {
  182. // clamp to n_batch tokens
  183. auto & inp = inputs[k];
  184. const uint64_t n_toks = inp.size();
  185. // encode if at capacity
  186. if (batch.n_tokens + n_toks > n_batch) {
  187. float * out = emb + e * n_embd;
  188. batch_decode(ctx, batch, out, s, n_embd, params.embd_normalize);
  189. e += pooling_type == LLAMA_POOLING_TYPE_NONE ? batch.n_tokens : s;
  190. s = 0;
  191. common_batch_clear(batch);
  192. }
  193. // add to batch
  194. batch_add_seq(batch, inp, s);
  195. s += 1;
  196. }
  197. // final batch
  198. float * out = emb + e * n_embd;
  199. batch_decode(ctx, batch, out, s, n_embd, params.embd_normalize);
  200. if (params.embd_out.empty()) {
  201. LOG("\n");
  202. if (pooling_type == LLAMA_POOLING_TYPE_NONE) {
  203. for (int j = 0; j < n_embd_count; j++) {
  204. LOG("embedding %d: ", j);
  205. for (int i = 0; i < std::min(3, n_embd); i++) {
  206. if (params.embd_normalize == 0) {
  207. LOG("%6.0f ", emb[j * n_embd + i]);
  208. } else {
  209. LOG("%9.6f ", emb[j * n_embd + i]);
  210. }
  211. }
  212. LOG(" ... ");
  213. for (int i = n_embd - 3; i < n_embd; i++) {
  214. if (params.embd_normalize == 0) {
  215. LOG("%6.0f ", emb[j * n_embd + i]);
  216. } else {
  217. LOG("%9.6f ", emb[j * n_embd + i]);
  218. }
  219. }
  220. LOG("\n");
  221. }
  222. } else if (pooling_type == LLAMA_POOLING_TYPE_RANK) {
  223. const uint32_t n_cls_out = llama_model_n_cls_out(model);
  224. std::vector<std::string> cls_out_labels;
  225. for (uint32_t i = 0; i < n_cls_out; i++) {
  226. const char * label = llama_model_cls_label(model, i);
  227. const std::string label_i(label == nullptr ? "" : label);
  228. cls_out_labels.emplace_back(label_i.empty() ? std::to_string(i) : label_i);
  229. }
  230. for (int j = 0; j < n_embd_count; j++) {
  231. for (uint32_t i = 0; i < n_cls_out; i++) {
  232. // NOTE: if you change this log - update the tests in ci/run.sh
  233. if (n_cls_out == 1) {
  234. LOG("rerank score %d: %8.3f\n", j, emb[j * n_embd]);
  235. } else {
  236. LOG("rerank score %d: %8.3f [%s]\n", j, emb[j * n_embd + i], cls_out_labels[i].c_str());
  237. }
  238. }
  239. }
  240. } else {
  241. // print the first part of the embeddings or for a single prompt, the full embedding
  242. for (int j = 0; j < n_prompts; j++) {
  243. LOG("embedding %d: ", j);
  244. for (int i = 0; i < (n_prompts > 1 ? std::min(16, n_embd) : n_embd); i++) {
  245. if (params.embd_normalize == 0) {
  246. LOG("%6.0f ", emb[j * n_embd + i]);
  247. } else {
  248. LOG("%9.6f ", emb[j * n_embd + i]);
  249. }
  250. }
  251. LOG("\n");
  252. }
  253. // print cosine similarity matrix
  254. if (n_prompts > 1) {
  255. LOG("\n");
  256. LOG("cosine similarity matrix:\n\n");
  257. for (int i = 0; i < n_prompts; i++) {
  258. LOG("%6.6s ", prompts[i].c_str());
  259. }
  260. LOG("\n");
  261. for (int i = 0; i < n_prompts; i++) {
  262. for (int j = 0; j < n_prompts; j++) {
  263. float sim = common_embd_similarity_cos(emb + i * n_embd, emb + j * n_embd, n_embd);
  264. LOG("%6.2f ", sim);
  265. }
  266. LOG("%1.10s", prompts[i].c_str());
  267. LOG("\n");
  268. }
  269. }
  270. }
  271. }
  272. if (params.embd_out == "json" || params.embd_out == "json+" || params.embd_out == "array") {
  273. const bool notArray = params.embd_out != "array";
  274. LOG(notArray ? "{\n \"object\": \"list\",\n \"data\": [\n" : "[");
  275. for (int j = 0;;) { // at least one iteration (one prompt)
  276. if (notArray) LOG(" {\n \"object\": \"embedding\",\n \"index\": %d,\n \"embedding\": ",j);
  277. LOG("[");
  278. for (int i = 0;;) { // at least one iteration (n_embd > 0)
  279. LOG(params.embd_normalize == 0 ? "%1.0f" : "%1.7f", emb[j * n_embd + i]);
  280. i++;
  281. if (i < n_embd) LOG(","); else break;
  282. }
  283. LOG(notArray ? "]\n }" : "]");
  284. j++;
  285. if (j < n_embd_count) LOG(notArray ? ",\n" : ","); else break;
  286. }
  287. LOG(notArray ? "\n ]" : "]\n");
  288. if (params.embd_out == "json+" && n_prompts > 1) {
  289. LOG(",\n \"cosineSimilarity\": [\n");
  290. for (int i = 0;;) { // at least two iteration (n_embd_count > 1)
  291. LOG(" [");
  292. for (int j = 0;;) { // at least two iteration (n_embd_count > 1)
  293. float sim = common_embd_similarity_cos(emb + i * n_embd, emb + j * n_embd, n_embd);
  294. LOG("%6.2f", sim);
  295. j++;
  296. if (j < n_embd_count) LOG(", "); else break;
  297. }
  298. LOG(" ]");
  299. i++;
  300. if (i < n_embd_count) LOG(",\n"); else break;
  301. }
  302. LOG("\n ]");
  303. }
  304. if (notArray) LOG("\n}\n");
  305. }
  306. LOG("\n");
  307. llama_perf_context_print(ctx);
  308. // clean up
  309. llama_batch_free(batch);
  310. llama_backend_free();
  311. return 0;
  312. }