embedding.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. const struct llama_model * model = llama_get_model(ctx);
  31. // clear previous kv_cache values (irrelevant for embeddings)
  32. llama_kv_cache_clear(ctx);
  33. // run model
  34. LOG_INF("%s: n_tokens = %d, n_seq = %d\n", __func__, batch.n_tokens, n_seq);
  35. if (llama_model_has_encoder(model) && !llama_model_has_decoder(model)) {
  36. // encoder-only model
  37. if (llama_encode(ctx, batch) < 0) {
  38. LOG_ERR("%s : failed to encode\n", __func__);
  39. }
  40. } else if (!llama_model_has_encoder(model) && llama_model_has_decoder(model)) {
  41. // decoder-only model
  42. if (llama_decode(ctx, batch) < 0) {
  43. LOG_ERR("%s : failed to decode\n", __func__);
  44. }
  45. }
  46. for (int i = 0; i < batch.n_tokens; i++) {
  47. if (!batch.logits[i]) {
  48. continue;
  49. }
  50. const float * embd = nullptr;
  51. int embd_pos = 0;
  52. if (pooling_type == LLAMA_POOLING_TYPE_NONE) {
  53. // try to get token embeddings
  54. embd = llama_get_embeddings_ith(ctx, i);
  55. embd_pos = i;
  56. GGML_ASSERT(embd != NULL && "failed to get token embeddings");
  57. } else {
  58. // try to get sequence embeddings - supported only when pooling_type is not NONE
  59. embd = llama_get_embeddings_seq(ctx, batch.seq_id[i][0]);
  60. embd_pos = batch.seq_id[i][0];
  61. GGML_ASSERT(embd != NULL && "failed to get sequence embeddings");
  62. }
  63. float * out = output + embd_pos * n_embd;
  64. common_embd_normalize(embd, out, n_embd, embd_norm);
  65. }
  66. }
  67. int main(int argc, char ** argv) {
  68. common_params params;
  69. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_EMBEDDING)) {
  70. return 1;
  71. }
  72. common_init();
  73. params.embedding = true;
  74. // For non-causal models, batch size must be equal to ubatch size
  75. params.n_ubatch = params.n_batch;
  76. llama_backend_init();
  77. llama_numa_init(params.numa);
  78. // load the model
  79. common_init_result llama_init = common_init_from_params(params);
  80. llama_model * model = llama_init.model.get();
  81. llama_context * ctx = llama_init.context.get();
  82. if (model == NULL) {
  83. LOG_ERR("%s: unable to load model\n", __func__);
  84. return 1;
  85. }
  86. const llama_vocab * vocab = llama_model_get_vocab(model);
  87. const int n_ctx_train = llama_model_n_ctx_train(model);
  88. const int n_ctx = llama_n_ctx(ctx);
  89. const enum llama_pooling_type pooling_type = llama_pooling_type(ctx);
  90. if (llama_model_has_encoder(model) && llama_model_has_decoder(model)) {
  91. LOG_ERR("%s: computing embeddings in encoder-decoder models is not supported\n", __func__);
  92. return 1;
  93. }
  94. if (n_ctx > n_ctx_train) {
  95. LOG_WRN("%s: warning: model was trained on only %d context tokens (%d specified)\n",
  96. __func__, n_ctx_train, n_ctx);
  97. }
  98. // print system information
  99. {
  100. LOG_INF("\n");
  101. LOG_INF("%s\n", common_params_get_system_info(params).c_str());
  102. }
  103. // split the prompt into lines
  104. std::vector<std::string> prompts = split_lines(params.prompt, params.embd_sep);
  105. // max batch size
  106. const uint64_t n_batch = params.n_batch;
  107. GGML_ASSERT(params.n_batch >= params.n_ctx);
  108. // tokenize the prompts and trim
  109. std::vector<std::vector<int32_t>> inputs;
  110. for (const auto & prompt : prompts) {
  111. auto inp = common_tokenize(ctx, prompt, true, true);
  112. if (inp.size() > n_batch) {
  113. LOG_ERR("%s: number of tokens in input line (%lld) exceeds batch size (%lld), increase batch size and re-run\n",
  114. __func__, (long long int) inp.size(), (long long int) n_batch);
  115. return 1;
  116. }
  117. inputs.push_back(inp);
  118. }
  119. // check if the last token is SEP
  120. // it should be automatically added by the tokenizer when 'tokenizer.ggml.add_eos_token' is set to 'true'
  121. for (auto & inp : inputs) {
  122. if (inp.empty() || inp.back() != llama_vocab_sep(vocab)) {
  123. LOG_WRN("%s: last token in the prompt is not SEP\n", __func__);
  124. LOG_WRN("%s: 'tokenizer.ggml.add_eos_token' should be set to 'true' in the GGUF header\n", __func__);
  125. }
  126. }
  127. // tokenization stats
  128. if (params.verbose_prompt) {
  129. for (int i = 0; i < (int) inputs.size(); i++) {
  130. LOG_INF("%s: prompt %d: '%s'\n", __func__, i, prompts[i].c_str());
  131. LOG_INF("%s: number of tokens in prompt = %zu\n", __func__, inputs[i].size());
  132. for (int j = 0; j < (int) inputs[i].size(); j++) {
  133. LOG("%6d -> '%s'\n", inputs[i][j], common_token_to_piece(ctx, inputs[i][j]).c_str());
  134. }
  135. LOG("\n\n");
  136. }
  137. }
  138. // initialize batch
  139. const int n_prompts = prompts.size();
  140. struct llama_batch batch = llama_batch_init(n_batch, 0, 1);
  141. // count number of embeddings
  142. int n_embd_count = 0;
  143. if (pooling_type == LLAMA_POOLING_TYPE_NONE) {
  144. for (int k = 0; k < n_prompts; k++) {
  145. n_embd_count += inputs[k].size();
  146. }
  147. } else {
  148. n_embd_count = n_prompts;
  149. }
  150. // allocate output
  151. const int n_embd = llama_model_n_embd(model);
  152. std::vector<float> embeddings(n_embd_count * n_embd, 0);
  153. float * emb = embeddings.data();
  154. // break into batches
  155. int e = 0; // number of embeddings already stored
  156. int s = 0; // number of prompts in current batch
  157. for (int k = 0; k < n_prompts; k++) {
  158. // clamp to n_batch tokens
  159. auto & inp = inputs[k];
  160. const uint64_t n_toks = inp.size();
  161. // encode if at capacity
  162. if (batch.n_tokens + n_toks > n_batch) {
  163. float * out = emb + e * n_embd;
  164. batch_decode(ctx, batch, out, s, n_embd, params.embd_normalize);
  165. e += pooling_type == LLAMA_POOLING_TYPE_NONE ? batch.n_tokens : s;
  166. s = 0;
  167. common_batch_clear(batch);
  168. }
  169. // add to batch
  170. batch_add_seq(batch, inp, s);
  171. s += 1;
  172. }
  173. // final batch
  174. float * out = emb + e * n_embd;
  175. batch_decode(ctx, batch, out, s, n_embd, params.embd_normalize);
  176. if (params.embd_out.empty()) {
  177. LOG("\n");
  178. if (pooling_type == LLAMA_POOLING_TYPE_NONE) {
  179. for (int j = 0; j < n_embd_count; j++) {
  180. LOG("embedding %d: ", j);
  181. for (int i = 0; i < std::min(3, n_embd); i++) {
  182. if (params.embd_normalize == 0) {
  183. LOG("%6.0f ", emb[j * n_embd + i]);
  184. } else {
  185. LOG("%9.6f ", emb[j * n_embd + i]);
  186. }
  187. }
  188. LOG(" ... ");
  189. for (int i = n_embd - 3; i < n_embd; i++) {
  190. if (params.embd_normalize == 0) {
  191. LOG("%6.0f ", emb[j * n_embd + i]);
  192. } else {
  193. LOG("%9.6f ", emb[j * n_embd + i]);
  194. }
  195. }
  196. LOG("\n");
  197. }
  198. } else if (pooling_type == LLAMA_POOLING_TYPE_RANK) {
  199. for (int j = 0; j < n_embd_count; j++) {
  200. // NOTE: if you change this log - update the tests in ci/run.sh
  201. LOG("rerank score %d: %8.3f\n", j, emb[j * n_embd]);
  202. }
  203. } else {
  204. // print the first part of the embeddings or for a single prompt, the full embedding
  205. for (int j = 0; j < n_prompts; j++) {
  206. LOG("embedding %d: ", j);
  207. for (int i = 0; i < (n_prompts > 1 ? std::min(16, n_embd) : n_embd); i++) {
  208. if (params.embd_normalize == 0) {
  209. LOG("%6.0f ", emb[j * n_embd + i]);
  210. } else {
  211. LOG("%9.6f ", emb[j * n_embd + i]);
  212. }
  213. }
  214. LOG("\n");
  215. }
  216. // print cosine similarity matrix
  217. if (n_prompts > 1) {
  218. LOG("\n");
  219. LOG("cosine similarity matrix:\n\n");
  220. for (int i = 0; i < n_prompts; i++) {
  221. LOG("%6.6s ", prompts[i].c_str());
  222. }
  223. LOG("\n");
  224. for (int i = 0; i < n_prompts; i++) {
  225. for (int j = 0; j < n_prompts; j++) {
  226. float sim = common_embd_similarity_cos(emb + i * n_embd, emb + j * n_embd, n_embd);
  227. LOG("%6.2f ", sim);
  228. }
  229. LOG("%1.10s", prompts[i].c_str());
  230. LOG("\n");
  231. }
  232. }
  233. }
  234. }
  235. if (params.embd_out == "json" || params.embd_out == "json+" || params.embd_out == "array") {
  236. const bool notArray = params.embd_out != "array";
  237. LOG(notArray ? "{\n \"object\": \"list\",\n \"data\": [\n" : "[");
  238. for (int j = 0;;) { // at least one iteration (one prompt)
  239. if (notArray) LOG(" {\n \"object\": \"embedding\",\n \"index\": %d,\n \"embedding\": ",j);
  240. LOG("[");
  241. for (int i = 0;;) { // at least one iteration (n_embd > 0)
  242. LOG(params.embd_normalize == 0 ? "%1.0f" : "%1.7f", emb[j * n_embd + i]);
  243. i++;
  244. if (i < n_embd) LOG(","); else break;
  245. }
  246. LOG(notArray ? "]\n }" : "]");
  247. j++;
  248. if (j < n_embd_count) LOG(notArray ? ",\n" : ","); else break;
  249. }
  250. LOG(notArray ? "\n ]" : "]\n");
  251. if (params.embd_out == "json+" && n_prompts > 1) {
  252. LOG(",\n \"cosineSimilarity\": [\n");
  253. for (int i = 0;;) { // at least two iteration (n_embd_count > 1)
  254. LOG(" [");
  255. for (int j = 0;;) { // at least two iteration (n_embd_count > 1)
  256. float sim = common_embd_similarity_cos(emb + i * n_embd, emb + j * n_embd, n_embd);
  257. LOG("%6.2f", sim);
  258. j++;
  259. if (j < n_embd_count) LOG(", "); else break;
  260. }
  261. LOG(" ]");
  262. i++;
  263. if (i < n_embd_count) LOG(",\n"); else break;
  264. }
  265. LOG("\n ]");
  266. }
  267. if (notArray) LOG("\n}\n");
  268. }
  269. LOG("\n");
  270. llama_perf_context_print(ctx);
  271. // clean up
  272. llama_batch_free(batch);
  273. llama_backend_free();
  274. return 0;
  275. }