test-tokenizer-0.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. { "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. std::vector<llama_token> res(test_kv.first.size());
  39. const int n = llama_tokenize(ctx, test_kv.first.c_str(), res.data(), res.size(), true);
  40. res.resize(n);
  41. bool correct = res.size() == test_kv.second.size();
  42. for (int i = 0; i < (int) res.size() && correct; ++i) {
  43. if (res[i] != test_kv.second[i]) {
  44. correct = false;
  45. }
  46. }
  47. if (!correct) {
  48. fprintf(stderr, "%s : failed test: '%s'\n", __func__, test_kv.first.c_str());
  49. fprintf(stderr, "%s : expected tokens: ", __func__);
  50. for (const auto & t : test_kv.second) {
  51. fprintf(stderr, "%6d, ", t);
  52. }
  53. fprintf(stderr, "\n");
  54. fprintf(stderr, "%s : got tokens: ", __func__);
  55. for (const auto & t : res) {
  56. fprintf(stderr, "%6d, ", t);
  57. }
  58. fprintf(stderr, "\n");
  59. return 3;
  60. }
  61. }
  62. llama_free(ctx);
  63. return 0;
  64. }