embedding.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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. // plain, pipe-friendly output: one embedding per line
  59. static void print_raw_embeddings(const float * emb,
  60. int n_embd_count,
  61. int n_embd,
  62. const llama_model * model,
  63. enum llama_pooling_type pooling_type,
  64. int embd_normalize) {
  65. const uint32_t n_cls_out = llama_model_n_cls_out(model);
  66. const bool is_rank = (pooling_type == LLAMA_POOLING_TYPE_RANK);
  67. const int cols = is_rank ? std::min<int>(n_embd, (int) n_cls_out) : n_embd;
  68. for (int j = 0; j < n_embd_count; ++j) {
  69. for (int i = 0; i < cols; ++i) {
  70. if (embd_normalize == 0) {
  71. LOG("%1.0f%s", emb[j * n_embd + i], (i + 1 < cols ? " " : ""));
  72. } else {
  73. LOG("%1.7f%s", emb[j * n_embd + i], (i + 1 < cols ? " " : ""));
  74. }
  75. }
  76. LOG("\n");
  77. }
  78. }
  79. int main(int argc, char ** argv) {
  80. common_params params;
  81. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_EMBEDDING)) {
  82. return 1;
  83. }
  84. common_init();
  85. params.embedding = true;
  86. // get max number of sequences per batch
  87. const int n_seq_max = llama_max_parallel_sequences();
  88. // if the number of prompts that would be encoded is known in advance, it's more efficient to specify the
  89. // --parallel argument accordingly. for convenience, if not specified, we fallback to unified KV cache
  90. // in order to support any number of prompts
  91. if (params.n_parallel == 1) {
  92. LOG_INF("%s: n_parallel == 1 -> unified KV cache is enabled\n", __func__);
  93. params.kv_unified = true;
  94. params.n_parallel = n_seq_max;
  95. }
  96. // utilize the full context
  97. if (params.n_batch < params.n_ctx) {
  98. LOG_WRN("%s: setting batch size to %d\n", __func__, params.n_ctx);
  99. params.n_batch = params.n_ctx;
  100. }
  101. // for non-causal models, batch size must be equal to ubatch size
  102. if (params.attention_type != LLAMA_ATTENTION_TYPE_CAUSAL) {
  103. params.n_ubatch = params.n_batch;
  104. }
  105. llama_backend_init();
  106. llama_numa_init(params.numa);
  107. // load the model
  108. common_init_result llama_init = common_init_from_params(params);
  109. llama_model * model = llama_init.model.get();
  110. llama_context * ctx = llama_init.context.get();
  111. if (model == NULL) {
  112. LOG_ERR("%s: unable to load model\n", __func__);
  113. return 1;
  114. }
  115. const llama_vocab * vocab = llama_model_get_vocab(model);
  116. const int n_ctx_train = llama_model_n_ctx_train(model);
  117. const int n_ctx = llama_n_ctx(ctx);
  118. const enum llama_pooling_type pooling_type = llama_pooling_type(ctx);
  119. if (llama_model_has_encoder(model) && llama_model_has_decoder(model)) {
  120. LOG_ERR("%s: computing embeddings in encoder-decoder models is not supported\n", __func__);
  121. return 1;
  122. }
  123. if (n_ctx > n_ctx_train) {
  124. LOG_WRN("%s: warning: model was trained on only %d context tokens (%d specified)\n",
  125. __func__, n_ctx_train, n_ctx);
  126. }
  127. // print system information
  128. {
  129. LOG_INF("\n");
  130. LOG_INF("%s\n", common_params_get_system_info(params).c_str());
  131. }
  132. // split the prompt into lines
  133. std::vector<std::string> prompts = split_lines(params.prompt, params.embd_sep);
  134. // max batch size
  135. const uint64_t n_batch = params.n_batch;
  136. // get added sep and eos token, if any
  137. const std::string added_sep_token = llama_vocab_get_add_sep(vocab) ? llama_vocab_get_text(vocab, llama_vocab_sep(vocab)) : "";
  138. const std::string added_eos_token = llama_vocab_get_add_eos(vocab) ? llama_vocab_get_text(vocab, llama_vocab_eos(vocab)) : "";
  139. const char * rerank_prompt = llama_model_chat_template(model, "rerank");
  140. // tokenize the prompts and trim
  141. std::vector<std::vector<int32_t>> inputs;
  142. for (const auto & prompt : prompts) {
  143. std::vector<llama_token> inp;
  144. // split classification pairs and insert expected separator tokens
  145. if (pooling_type == LLAMA_POOLING_TYPE_RANK && prompt.find(params.cls_sep) != std::string::npos) {
  146. std::vector<std::string> pairs = split_lines(prompt, params.cls_sep);
  147. if (rerank_prompt != nullptr) {
  148. const std::string query = pairs[0];
  149. const std::string doc = pairs[1];
  150. std::string final_prompt = rerank_prompt;
  151. string_replace_all(final_prompt, "{query}" , query);
  152. string_replace_all(final_prompt, "{document}", doc );
  153. inp = common_tokenize(vocab, final_prompt, true, true);
  154. } else {
  155. std::string final_prompt;
  156. for (size_t i = 0; i < pairs.size(); i++) {
  157. final_prompt += pairs[i];
  158. if (i != pairs.size() - 1) {
  159. if (!added_eos_token.empty()) {
  160. final_prompt += added_eos_token;
  161. }
  162. if (!added_sep_token.empty()) {
  163. final_prompt += added_sep_token;
  164. }
  165. }
  166. }
  167. inp = common_tokenize(ctx, final_prompt, true, true);
  168. }
  169. } else {
  170. inp = common_tokenize(ctx, prompt, true, true);
  171. }
  172. if (inp.size() > n_batch) {
  173. LOG_ERR("%s: number of tokens in input line (%lld) exceeds batch size (%lld), increase batch size and re-run\n",
  174. __func__, (long long int) inp.size(), (long long int) n_batch);
  175. return 1;
  176. }
  177. inputs.push_back(inp);
  178. }
  179. // check if the last token is SEP/EOS
  180. // it should be automatically added by the tokenizer when 'tokenizer.ggml.add_eos_token' is set to 'true'
  181. for (auto & inp : inputs) {
  182. if (inp.empty() || (inp.back() != llama_vocab_sep(vocab) && inp.back() != llama_vocab_eos(vocab))) {
  183. LOG_WRN("%s: last token in the prompt is not SEP or EOS\n", __func__);
  184. LOG_WRN("%s: 'tokenizer.ggml.add_eos_token' should be set to 'true' in the GGUF header\n", __func__);
  185. }
  186. }
  187. // tokenization stats
  188. if (params.verbose_prompt) {
  189. for (int i = 0; i < (int) inputs.size(); i++) {
  190. LOG_INF("%s: prompt %d: '%s'\n", __func__, i, prompts[i].c_str());
  191. LOG_INF("%s: number of tokens in prompt = %zu\n", __func__, inputs[i].size());
  192. for (int j = 0; j < (int) inputs[i].size(); j++) {
  193. LOG("%6d -> '%s'\n", inputs[i][j], common_token_to_piece(ctx, inputs[i][j]).c_str());
  194. }
  195. LOG("\n\n");
  196. }
  197. }
  198. // initialize batch
  199. const int n_prompts = prompts.size();
  200. struct llama_batch batch = llama_batch_init(n_batch, 0, 1);
  201. // count number of embeddings
  202. int n_embd_count = 0;
  203. if (pooling_type == LLAMA_POOLING_TYPE_NONE) {
  204. for (int k = 0; k < n_prompts; k++) {
  205. n_embd_count += inputs[k].size();
  206. }
  207. } else {
  208. n_embd_count = n_prompts;
  209. }
  210. // allocate output
  211. const int n_embd = llama_model_n_embd(model);
  212. std::vector<float> embeddings(n_embd_count * n_embd, 0);
  213. float * emb = embeddings.data();
  214. // break into batches
  215. int e = 0; // number of embeddings already stored
  216. int s = 0; // number of prompts in current batch
  217. for (int k = 0; k < n_prompts; k++) {
  218. // clamp to n_batch tokens
  219. auto & inp = inputs[k];
  220. const uint64_t n_toks = inp.size();
  221. // encode if at capacity
  222. if (batch.n_tokens + n_toks > n_batch || s >= n_seq_max) {
  223. float * out = emb + e * n_embd;
  224. batch_decode(ctx, batch, out, s, n_embd, params.embd_normalize);
  225. e += pooling_type == LLAMA_POOLING_TYPE_NONE ? batch.n_tokens : s;
  226. s = 0;
  227. common_batch_clear(batch);
  228. }
  229. // add to batch
  230. batch_add_seq(batch, inp, s);
  231. s += 1;
  232. }
  233. // final batch
  234. float * out = emb + e * n_embd;
  235. batch_decode(ctx, batch, out, s, n_embd, params.embd_normalize);
  236. if (params.embd_out.empty()) {
  237. LOG("\n");
  238. if (pooling_type == LLAMA_POOLING_TYPE_NONE) {
  239. for (int j = 0; j < n_embd_count; j++) {
  240. LOG("embedding %d: ", j);
  241. for (int i = 0; i < std::min(3, n_embd); i++) {
  242. if (params.embd_normalize == 0) {
  243. LOG("%6.0f ", emb[j * n_embd + i]);
  244. } else {
  245. LOG("%9.6f ", emb[j * n_embd + i]);
  246. }
  247. }
  248. LOG(" ... ");
  249. for (int i = n_embd - 3; i < n_embd; i++) {
  250. if (params.embd_normalize == 0) {
  251. LOG("%6.0f ", emb[j * n_embd + i]);
  252. } else {
  253. LOG("%9.6f ", emb[j * n_embd + i]);
  254. }
  255. }
  256. LOG("\n");
  257. }
  258. } else if (pooling_type == LLAMA_POOLING_TYPE_RANK) {
  259. const uint32_t n_cls_out = llama_model_n_cls_out(model);
  260. std::vector<std::string> cls_out_labels;
  261. for (uint32_t i = 0; i < n_cls_out; i++) {
  262. const char * label = llama_model_cls_label(model, i);
  263. const std::string label_i(label == nullptr ? "" : label);
  264. cls_out_labels.emplace_back(label_i.empty() ? std::to_string(i) : label_i);
  265. }
  266. for (int j = 0; j < n_embd_count; j++) {
  267. for (uint32_t i = 0; i < n_cls_out; i++) {
  268. // NOTE: if you change this log - update the tests in ci/run.sh
  269. if (n_cls_out == 1) {
  270. LOG("rerank score %d: %8.3f\n", j, emb[j * n_embd]);
  271. } else {
  272. LOG("rerank score %d: %8.3f [%s]\n", j, emb[j * n_embd + i], cls_out_labels[i].c_str());
  273. }
  274. }
  275. }
  276. } else {
  277. // print the first part of the embeddings or for a single prompt, the full embedding
  278. for (int j = 0; j < n_prompts; j++) {
  279. LOG("embedding %d: ", j);
  280. for (int i = 0; i < (n_prompts > 1 ? std::min(16, n_embd) : n_embd); i++) {
  281. if (params.embd_normalize == 0) {
  282. LOG("%6.0f ", emb[j * n_embd + i]);
  283. } else {
  284. LOG("%9.6f ", emb[j * n_embd + i]);
  285. }
  286. }
  287. LOG("\n");
  288. }
  289. // print cosine similarity matrix
  290. if (n_prompts > 1) {
  291. LOG("\n");
  292. LOG("cosine similarity matrix:\n\n");
  293. for (int i = 0; i < n_prompts; i++) {
  294. LOG("%6.6s ", prompts[i].c_str());
  295. }
  296. LOG("\n");
  297. for (int i = 0; i < n_prompts; i++) {
  298. for (int j = 0; j < n_prompts; j++) {
  299. float sim = common_embd_similarity_cos(emb + i * n_embd, emb + j * n_embd, n_embd);
  300. LOG("%6.2f ", sim);
  301. }
  302. LOG("%1.10s", prompts[i].c_str());
  303. LOG("\n");
  304. }
  305. }
  306. }
  307. }
  308. if (params.embd_out == "json" || params.embd_out == "json+" || params.embd_out == "array") {
  309. const bool notArray = params.embd_out != "array";
  310. LOG(notArray ? "{\n \"object\": \"list\",\n \"data\": [\n" : "[");
  311. for (int j = 0;;) { // at least one iteration (one prompt)
  312. if (notArray) LOG(" {\n \"object\": \"embedding\",\n \"index\": %d,\n \"embedding\": ",j);
  313. LOG("[");
  314. for (int i = 0;;) { // at least one iteration (n_embd > 0)
  315. LOG(params.embd_normalize == 0 ? "%1.0f" : "%1.7f", emb[j * n_embd + i]);
  316. i++;
  317. if (i < n_embd) LOG(","); else break;
  318. }
  319. LOG(notArray ? "]\n }" : "]");
  320. j++;
  321. if (j < n_embd_count) LOG(notArray ? ",\n" : ","); else break;
  322. }
  323. LOG(notArray ? "\n ]" : "]\n");
  324. if (params.embd_out == "json+" && n_prompts > 1) {
  325. LOG(",\n \"cosineSimilarity\": [\n");
  326. for (int i = 0;;) { // at least two iteration (n_embd_count > 1)
  327. LOG(" [");
  328. for (int j = 0;;) { // at least two iteration (n_embd_count > 1)
  329. float sim = common_embd_similarity_cos(emb + i * n_embd, emb + j * n_embd, n_embd);
  330. LOG("%6.2f", sim);
  331. j++;
  332. if (j < n_embd_count) LOG(", "); else break;
  333. }
  334. LOG(" ]");
  335. i++;
  336. if (i < n_embd_count) LOG(",\n"); else break;
  337. }
  338. LOG("\n ]");
  339. }
  340. if (notArray) LOG("\n}\n");
  341. } else if (params.embd_out == "raw") {
  342. print_raw_embeddings(emb, n_embd_count, n_embd, model, pooling_type, params.embd_normalize);
  343. }
  344. LOG("\n");
  345. llama_perf_context_print(ctx);
  346. // clean up
  347. llama_batch_free(batch);
  348. llama_backend_free();
  349. return 0;
  350. }