embedding.cpp 13 KB

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