embedding.cpp 11 KB

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