1
0

embedding.cpp 15 KB

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