1
0

embedding.cpp 11 KB

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