embedding.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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_kv_self_clear(ctx);
  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. // tokenize the prompts and trim
  104. std::vector<std::vector<int32_t>> inputs;
  105. for (const auto & prompt : prompts) {
  106. auto inp = common_tokenize(ctx, prompt, true, true);
  107. if (inp.size() > n_batch) {
  108. LOG_ERR("%s: number of tokens in input line (%lld) exceeds batch size (%lld), increase batch size and re-run\n",
  109. __func__, (long long int) inp.size(), (long long int) n_batch);
  110. return 1;
  111. }
  112. inputs.push_back(inp);
  113. }
  114. // check if the last token is SEP
  115. // it should be automatically added by the tokenizer when 'tokenizer.ggml.add_eos_token' is set to 'true'
  116. for (auto & inp : inputs) {
  117. if (inp.empty() || inp.back() != llama_vocab_sep(vocab)) {
  118. LOG_WRN("%s: last token in the prompt is not SEP\n", __func__);
  119. LOG_WRN("%s: 'tokenizer.ggml.add_eos_token' should be set to 'true' in the GGUF header\n", __func__);
  120. }
  121. }
  122. // tokenization stats
  123. if (params.verbose_prompt) {
  124. for (int i = 0; i < (int) inputs.size(); i++) {
  125. LOG_INF("%s: prompt %d: '%s'\n", __func__, i, prompts[i].c_str());
  126. LOG_INF("%s: number of tokens in prompt = %zu\n", __func__, inputs[i].size());
  127. for (int j = 0; j < (int) inputs[i].size(); j++) {
  128. LOG("%6d -> '%s'\n", inputs[i][j], common_token_to_piece(ctx, inputs[i][j]).c_str());
  129. }
  130. LOG("\n\n");
  131. }
  132. }
  133. // initialize batch
  134. const int n_prompts = prompts.size();
  135. struct llama_batch batch = llama_batch_init(n_batch, 0, 1);
  136. // count number of embeddings
  137. int n_embd_count = 0;
  138. if (pooling_type == LLAMA_POOLING_TYPE_NONE) {
  139. for (int k = 0; k < n_prompts; k++) {
  140. n_embd_count += inputs[k].size();
  141. }
  142. } else {
  143. n_embd_count = n_prompts;
  144. }
  145. // allocate output
  146. const int n_embd = llama_model_n_embd(model);
  147. std::vector<float> embeddings(n_embd_count * n_embd, 0);
  148. float * emb = embeddings.data();
  149. // break into batches
  150. int e = 0; // number of embeddings already stored
  151. int s = 0; // number of prompts in current batch
  152. for (int k = 0; k < n_prompts; k++) {
  153. // clamp to n_batch tokens
  154. auto & inp = inputs[k];
  155. const uint64_t n_toks = inp.size();
  156. // encode if at capacity
  157. if (batch.n_tokens + n_toks > n_batch) {
  158. float * out = emb + e * n_embd;
  159. batch_decode(ctx, batch, out, s, n_embd, params.embd_normalize);
  160. e += pooling_type == LLAMA_POOLING_TYPE_NONE ? batch.n_tokens : s;
  161. s = 0;
  162. common_batch_clear(batch);
  163. }
  164. // add to batch
  165. batch_add_seq(batch, inp, s);
  166. s += 1;
  167. }
  168. // final batch
  169. float * out = emb + e * n_embd;
  170. batch_decode(ctx, batch, out, s, n_embd, params.embd_normalize);
  171. if (params.embd_out.empty()) {
  172. LOG("\n");
  173. if (pooling_type == LLAMA_POOLING_TYPE_NONE) {
  174. for (int j = 0; j < n_embd_count; j++) {
  175. LOG("embedding %d: ", j);
  176. for (int i = 0; i < std::min(3, n_embd); i++) {
  177. if (params.embd_normalize == 0) {
  178. LOG("%6.0f ", emb[j * n_embd + i]);
  179. } else {
  180. LOG("%9.6f ", emb[j * n_embd + i]);
  181. }
  182. }
  183. LOG(" ... ");
  184. for (int i = n_embd - 3; i < n_embd; i++) {
  185. if (params.embd_normalize == 0) {
  186. LOG("%6.0f ", emb[j * n_embd + i]);
  187. } else {
  188. LOG("%9.6f ", emb[j * n_embd + i]);
  189. }
  190. }
  191. LOG("\n");
  192. }
  193. } else if (pooling_type == LLAMA_POOLING_TYPE_RANK) {
  194. for (int j = 0; j < n_embd_count; j++) {
  195. // NOTE: if you change this log - update the tests in ci/run.sh
  196. LOG("rerank score %d: %8.3f\n", j, emb[j * n_embd]);
  197. }
  198. } else {
  199. // print the first part of the embeddings or for a single prompt, the full embedding
  200. for (int j = 0; j < n_prompts; j++) {
  201. LOG("embedding %d: ", j);
  202. for (int i = 0; i < (n_prompts > 1 ? std::min(16, n_embd) : n_embd); i++) {
  203. if (params.embd_normalize == 0) {
  204. LOG("%6.0f ", emb[j * n_embd + i]);
  205. } else {
  206. LOG("%9.6f ", emb[j * n_embd + i]);
  207. }
  208. }
  209. LOG("\n");
  210. }
  211. // print cosine similarity matrix
  212. if (n_prompts > 1) {
  213. LOG("\n");
  214. LOG("cosine similarity matrix:\n\n");
  215. for (int i = 0; i < n_prompts; i++) {
  216. LOG("%6.6s ", prompts[i].c_str());
  217. }
  218. LOG("\n");
  219. for (int i = 0; i < n_prompts; i++) {
  220. for (int j = 0; j < n_prompts; j++) {
  221. float sim = common_embd_similarity_cos(emb + i * n_embd, emb + j * n_embd, n_embd);
  222. LOG("%6.2f ", sim);
  223. }
  224. LOG("%1.10s", prompts[i].c_str());
  225. LOG("\n");
  226. }
  227. }
  228. }
  229. }
  230. if (params.embd_out == "json" || params.embd_out == "json+" || params.embd_out == "array") {
  231. const bool notArray = params.embd_out != "array";
  232. LOG(notArray ? "{\n \"object\": \"list\",\n \"data\": [\n" : "[");
  233. for (int j = 0;;) { // at least one iteration (one prompt)
  234. if (notArray) LOG(" {\n \"object\": \"embedding\",\n \"index\": %d,\n \"embedding\": ",j);
  235. LOG("[");
  236. for (int i = 0;;) { // at least one iteration (n_embd > 0)
  237. LOG(params.embd_normalize == 0 ? "%1.0f" : "%1.7f", emb[j * n_embd + i]);
  238. i++;
  239. if (i < n_embd) LOG(","); else break;
  240. }
  241. LOG(notArray ? "]\n }" : "]");
  242. j++;
  243. if (j < n_embd_count) LOG(notArray ? ",\n" : ","); else break;
  244. }
  245. LOG(notArray ? "\n ]" : "]\n");
  246. if (params.embd_out == "json+" && n_prompts > 1) {
  247. LOG(",\n \"cosineSimilarity\": [\n");
  248. for (int i = 0;;) { // at least two iteration (n_embd_count > 1)
  249. LOG(" [");
  250. for (int j = 0;;) { // at least two iteration (n_embd_count > 1)
  251. float sim = common_embd_similarity_cos(emb + i * n_embd, emb + j * n_embd, n_embd);
  252. LOG("%6.2f", sim);
  253. j++;
  254. if (j < n_embd_count) LOG(", "); else break;
  255. }
  256. LOG(" ]");
  257. i++;
  258. if (i < n_embd_count) LOG(",\n"); else break;
  259. }
  260. LOG("\n ]");
  261. }
  262. if (notArray) LOG("\n}\n");
  263. }
  264. LOG("\n");
  265. llama_perf_context_print(ctx);
  266. // clean up
  267. llama_batch_free(batch);
  268. llama_backend_free();
  269. return 0;
  270. }