test-tokenizer-0.cpp 2.6 KB

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