1
0

embedding.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. // determine newline token
  44. auto llama_token_newline = ::llama_tokenize(ctx, "\n", false);
  45. if (params.verbose_prompt) {
  46. fprintf(stderr, "\n");
  47. fprintf(stderr, "%s: prompt: '%s'\n", __func__, params.prompt.c_str());
  48. fprintf(stderr, "%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  49. for (int i = 0; i < (int) embd_inp.size(); i++) {
  50. fprintf(stderr, "%6d -> '%s'\n", embd_inp[i], llama_token_to_str(ctx, embd_inp[i]));
  51. }
  52. fprintf(stderr, "\n");
  53. }
  54. if (params.embedding){
  55. if (embd_inp.size() > 0) {
  56. if (llama_eval(ctx, embd_inp.data(), embd_inp.size(), n_past, params.n_threads)) {
  57. fprintf(stderr, "%s : failed to eval\n", __func__);
  58. return 1;
  59. }
  60. }
  61. const int n_embd = llama_n_embd(ctx);
  62. const auto embeddings = llama_get_embeddings(ctx);
  63. for (int i = 0; i < n_embd; i++) {
  64. printf("%f ", embeddings[i]);
  65. }
  66. printf("\n");
  67. }
  68. llama_print_timings(ctx);
  69. llama_free(ctx);
  70. return 0;
  71. }