embedding.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include "common.h"
  2. #include "llama.h"
  3. #include "build-info.h"
  4. #include <ctime>
  5. int main(int argc, char ** argv) {
  6. gpt_params params;
  7. params.model = "models/llama-7B/ggml-model.bin";
  8. if (gpt_params_parse(argc, argv, params) == false) {
  9. return 1;
  10. }
  11. params.embedding = true;
  12. if (params.n_ctx > 2048) {
  13. fprintf(stderr, "%s: warning: model does not support context sizes greater than 2048 tokens (%d specified);"
  14. "expect poor results\n", __func__, params.n_ctx);
  15. }
  16. fprintf(stderr, "%s: build = %d (%s)\n", __func__, BUILD_NUMBER, BUILD_COMMIT);
  17. if (params.seed < 0) {
  18. params.seed = time(NULL);
  19. }
  20. fprintf(stderr, "%s: seed = %d\n", __func__, params.seed);
  21. std::mt19937 rng(params.seed);
  22. if (params.random_prompt) {
  23. params.prompt = gpt_random_prompt(rng);
  24. }
  25. llama_context * ctx;
  26. // load the model
  27. ctx = llama_init_from_gpt_params(params);
  28. if (ctx == NULL) {
  29. fprintf(stderr, "%s: error: unable to load model\n", __func__);
  30. return 1;
  31. }
  32. // print system information
  33. {
  34. fprintf(stderr, "\n");
  35. fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
  36. params.n_threads, std::thread::hardware_concurrency(), llama_print_system_info());
  37. }
  38. int n_past = 0;
  39. // Add a space in front of the first character to match OG llama tokenizer behavior
  40. params.prompt.insert(0, 1, ' ');
  41. // tokenize the prompt
  42. auto embd_inp = ::llama_tokenize(ctx, params.prompt, true);
  43. if (params.verbose_prompt) {
  44. fprintf(stderr, "\n");
  45. fprintf(stderr, "%s: prompt: '%s'\n", __func__, params.prompt.c_str());
  46. fprintf(stderr, "%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  47. for (int i = 0; i < (int) embd_inp.size(); i++) {
  48. fprintf(stderr, "%6d -> '%s'\n", embd_inp[i], llama_token_to_str(ctx, embd_inp[i]));
  49. }
  50. fprintf(stderr, "\n");
  51. }
  52. if (params.embedding){
  53. if (embd_inp.size() > 0) {
  54. if (llama_eval(ctx, embd_inp.data(), embd_inp.size(), n_past, params.n_threads)) {
  55. fprintf(stderr, "%s : failed to eval\n", __func__);
  56. return 1;
  57. }
  58. }
  59. const int n_embd = llama_n_embd(ctx);
  60. const auto embeddings = llama_get_embeddings(ctx);
  61. for (int i = 0; i < n_embd; i++) {
  62. printf("%f ", embeddings[i]);
  63. }
  64. printf("\n");
  65. }
  66. llama_print_timings(ctx);
  67. llama_free(ctx);
  68. return 0;
  69. }