1
0

embedding.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. if (gpt_params_parse(argc, argv, params) == false) {
  8. return 1;
  9. }
  10. params.embedding = true;
  11. if (params.n_ctx > 2048) {
  12. fprintf(stderr, "%s: warning: model does not support context sizes greater than 2048 tokens (%d specified);"
  13. "expect poor results\n", __func__, params.n_ctx);
  14. }
  15. fprintf(stderr, "%s: build = %d (%s)\n", __func__, BUILD_NUMBER, BUILD_COMMIT);
  16. if (params.seed < 0) {
  17. params.seed = time(NULL);
  18. }
  19. fprintf(stderr, "%s: seed = %d\n", __func__, params.seed);
  20. std::mt19937 rng(params.seed);
  21. if (params.random_prompt) {
  22. params.prompt = gpt_random_prompt(rng);
  23. }
  24. llama_init_backend();
  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. }