embedding.cpp 11 KB

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