test-tokenizer-0.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include "utils.h"
  2. #include "llama.h"
  3. #include <cstdio>
  4. #include <string>
  5. #include <map>
  6. static const std::map<std::string, std::vector<llama_token>> k_tests = {
  7. { "Hello World", { 1, 10994, 2787, }, },
  8. { " Hello World", { 1, 15043, 2787, }, },
  9. { " Hello World!", { 1, 15043, 2787, 29991, }, },
  10. { " this is 🦙.cpp", { 1, 445, 338, 29871, 243, 162, 169, 156, 29889, 8223, }, },
  11. { "w048 7tuijk dsdfhu", { 1, 29893, 29900, 29946, 29947, 29871, 29955, 9161, 13535, 18031, 2176, 6905, }, },
  12. { "нещо на Български", { 1, 821, 4851, 665, 1386, 29713, 1305, }, },
  13. };
  14. int main(int argc, char **argv) {
  15. if (argc < 2) {
  16. fprintf(stderr, "Usage: %s <vocab-file>\n", argv[0]);
  17. return 1;
  18. }
  19. const std::string fname = argv[1];
  20. fprintf(stderr, "%s : reading vocab from: '%s'\n", __func__, fname.c_str());
  21. llama_context * ctx;
  22. // load the vocab
  23. {
  24. auto lparams = llama_context_default_params();
  25. lparams.vocab_only = true;
  26. ctx = llama_init_from_file(fname.c_str(), lparams);
  27. if (ctx == NULL) {
  28. fprintf(stderr, "%s: error: failed to load vocab '%s'\n", __func__, fname.c_str());
  29. return 1;
  30. }
  31. }
  32. const int n_vocab = llama_n_vocab(ctx);
  33. if (n_vocab != 32000) {
  34. fprintf(stderr, "%s : expected 32000 tokens, got %d\n", __func__, n_vocab);
  35. return 2;
  36. }
  37. for (const auto & test_kv : k_tests) {
  38. const auto res = ::llama_tokenize(ctx, test_kv.first, true);
  39. bool correct = res.size() == test_kv.second.size();
  40. for (int i = 0; i < (int) res.size() && correct; ++i) {
  41. if (res[i] != test_kv.second[i]) {
  42. correct = false;
  43. }
  44. }
  45. if (!correct) {
  46. fprintf(stderr, "%s : failed test: '%s'\n", __func__, test_kv.first.c_str());
  47. fprintf(stderr, "%s : expected tokens: ", __func__);
  48. for (const auto & t : test_kv.second) {
  49. fprintf(stderr, "%6d, ", t);
  50. }
  51. fprintf(stderr, "\n");
  52. fprintf(stderr, "%s : got tokens: ", __func__);
  53. for (const auto & t : res) {
  54. fprintf(stderr, "%6d, ", t);
  55. }
  56. fprintf(stderr, "\n");
  57. return 3;
  58. }
  59. }
  60. return 0;
  61. }