tokenize.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. #include "common.h"
  2. //#include "log.h" // TODO: start using log.h
  3. #include "llama.h"
  4. #include <cstdio>
  5. #include <cstring>
  6. #include <fstream>
  7. #include <string>
  8. #include <vector>
  9. #include <iostream> // TODO: remove me
  10. #if defined(_WIN32)
  11. #define WIN32_LEAN_AND_MEAN
  12. #include <windows.h>
  13. #include <shellapi.h> // For CommandLineToArgvW
  14. #endif
  15. static void print_usage_information(const char * argv0) {
  16. printf("usage: %s [options]\n\n", argv0);
  17. printf("The tokenize program tokenizes a prompt using a given model,\n");
  18. printf("and prints the resulting tokens to standard output.\n\n");
  19. printf("It needs a model file, a prompt, and optionally other flags\n");
  20. printf("to control the behavior of the tokenizer.\n\n");
  21. printf(" The possible options are:\n");
  22. printf("\n");
  23. printf(" -h, --help print this help and exit\n");
  24. printf(" -m MODEL_PATH, --model MODEL_PATH path to model.\n");
  25. printf(" --ids if given, only print numerical token IDs, and not token strings.\n");
  26. printf(" The output format looks like [1, 2, 3], i.e. parseable by Python.\n");
  27. printf(" -f PROMPT_FNAME, --file PROMPT_FNAME read prompt from a file.\n");
  28. printf(" -p PROMPT, --prompt PROMPT read prompt from the argument.\n");
  29. printf(" --stdin read prompt from standard input.\n");
  30. printf(" --no-bos do not ever add a BOS token to the prompt, even if normally the model uses a BOS token.\n");
  31. printf(" --no-parse-special do not parse control tokens.\n");
  32. printf(" --log-disable disable logs. Makes stderr quiet when loading the model.\n");
  33. printf(" --show-count print the total number of tokens.\n");
  34. }
  35. static void llama_log_callback_null(ggml_log_level level, const char * text, void * user_data) {
  36. (void) level;
  37. (void) text;
  38. (void) user_data;
  39. }
  40. static std::string read_prompt_from_file(const char * filepath, bool & success) {
  41. success = false;
  42. std::ifstream in(filepath, std::ios::binary);
  43. if (!in) {
  44. fprintf(stderr, "%s: could not open file '%s' for reading: %s\n", __func__, filepath, strerror(errno));
  45. return std::string();
  46. }
  47. // do not assume the file is seekable (e.g. /dev/stdin)
  48. std::stringstream buffer;
  49. buffer << in.rdbuf();
  50. if (in.fail()) {
  51. fprintf(stderr, "%s: could not read the entire file '%s': %s\n", __func__, filepath, strerror(errno));
  52. return std::string();
  53. }
  54. success = true;
  55. return buffer.str();
  56. }
  57. //
  58. // Function: ingest_args(...) -> vector<string>
  59. //
  60. // Takes argc and argv arguments, and converts them to a vector of UTF-8 encoded
  61. // strings, as an STL vector<string>.
  62. //
  63. // In particular, it handles character encoding shenanigans on Windows.
  64. //
  65. // Note: raw_argc and raw_argv are not actually read at all on Windows.
  66. // On Windows we call GetCommandLineW to get the arguments in wchar_t
  67. // format, ignoring the regular argc/argv arguments to main().
  68. //
  69. // TODO: potential opportunity to roll common stuff into common/console.cpp
  70. // in relation to Windows wchar_t shenanigans.
  71. static std::vector<std::string> ingest_args(int raw_argc, char ** raw_argv) {
  72. std::vector<std::string> argv;
  73. // Handle Windows, if given non-ASCII arguments.
  74. // We convert wchar_t arguments into UTF-8 char* on this platform.
  75. // Lets you invoke 'tokenize' on Windows cmd.exe with non-ASCII characters
  76. // without throwing tantrums.
  77. #if defined(_WIN32)
  78. int argc;
  79. const LPWSTR cmdline_wargv = GetCommandLineW();
  80. LPWSTR * wargv = CommandLineToArgvW(cmdline_wargv, &argc);
  81. // silence unused arg warnings
  82. (void) raw_argc;
  83. (void) raw_argv;
  84. for (int i = 0; i < argc; ++i) {
  85. int length_needed = WideCharToMultiByte(CP_UTF8, 0, wargv[i], wcslen(wargv[i]), 0, 0, NULL, NULL);
  86. char * output_buf = (char *) calloc(length_needed+1, sizeof(char));
  87. GGML_ASSERT(output_buf);
  88. WideCharToMultiByte(CP_UTF8, 0, wargv[i], wcslen(wargv[i]), output_buf, length_needed, NULL, NULL);
  89. output_buf[length_needed] = '\0';
  90. argv.push_back(output_buf);
  91. free(output_buf);
  92. }
  93. LocalFree((HLOCAL) wargv);
  94. #else
  95. int argc = raw_argc;
  96. for (int i = 0; i < argc; ++i) {
  97. argv.push_back(raw_argv[i]);
  98. }
  99. #endif
  100. GGML_ASSERT((unsigned int) argc == argv.size());
  101. return argv;
  102. }
  103. //
  104. // Function: write_utf8_cstr_to_stdout(const char *) -> <writes to stdout>
  105. //
  106. // writes a string to standard output; taking into account that on Windows
  107. // to display correctly you have to use special handling. Works even if the
  108. // user has not set a unicode code page on a Windows cmd.exe.
  109. //
  110. // In case of invalid UTF-8, invalid_utf8 is set to true on Windows, and something
  111. // a human-readable is written instead.
  112. //
  113. // On non-Windows systems, simply printfs() the string.
  114. static void write_utf8_cstr_to_stdout(const char * str, bool & invalid_utf8) {
  115. invalid_utf8 = false;
  116. #if defined(_WIN32)
  117. // Are we in a console?
  118. HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
  119. DWORD dwMode = 0;
  120. // According to Microsoft docs:
  121. // "WriteConsole fails if it is used with a standard handle that is redirected to a file."
  122. // Also according to the docs, you can use GetConsoleMode to check for that.
  123. if (hConsole == INVALID_HANDLE_VALUE || !GetConsoleMode(hConsole, &dwMode)) {
  124. printf("%s", str);
  125. return;
  126. }
  127. // MultiByteToWideChar reports an error if str is empty, don't report
  128. // them as invalid_utf8.
  129. if (*str == 0) {
  130. return;
  131. }
  132. int length_needed = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, str, strlen(str), NULL, 0);
  133. if (length_needed == 0) {
  134. DWORD err = GetLastError();
  135. if (err == ERROR_NO_UNICODE_TRANSLATION) {
  136. invalid_utf8 = true;
  137. int len = strlen(str);
  138. printf("<");
  139. for (int i = 0; i < len; ++i) {
  140. if (i > 0) {
  141. printf(" ");
  142. }
  143. printf("%02x", (uint8_t) str[i]);
  144. }
  145. printf(">");
  146. return;
  147. }
  148. GGML_ABORT("MultiByteToWideChar() failed in an unexpected way.");
  149. }
  150. LPWSTR wstr = (LPWSTR) calloc(length_needed+1, sizeof(*wstr));
  151. GGML_ASSERT(wstr);
  152. MultiByteToWideChar(CP_UTF8, 0, str, strlen(str), wstr, length_needed);
  153. WriteConsoleW(hConsole, wstr, length_needed, NULL, NULL);
  154. free(wstr);
  155. #else
  156. // TODO: reporting invalid_utf8 would be useful on non-Windows too.
  157. // printf will silently just write bad unicode.
  158. printf("%s", str);
  159. #endif
  160. }
  161. int main(int raw_argc, char ** raw_argv) {
  162. const std::vector<std::string> argv = ingest_args(raw_argc, raw_argv);
  163. const int argc = argv.size();
  164. if (argc <= 1) {
  165. print_usage_information(argv[0].c_str());
  166. return 1;
  167. }
  168. //////
  169. // Read out all the command line arguments.
  170. //////
  171. // variables where to put any arguments we see.
  172. bool printing_ids = false;
  173. bool no_bos = false;
  174. bool no_parse_special = false;
  175. bool disable_logging = false;
  176. bool show_token_count = false;
  177. const char * model_path = NULL;
  178. const char * prompt_path = NULL;
  179. const char * prompt_arg = NULL;
  180. // track which arguments were explicitly given
  181. // used for sanity checking down the line
  182. bool model_path_set = false;
  183. bool prompt_path_set = false;
  184. bool prompt_set = false;
  185. bool stdin_set = false;
  186. int iarg = 1;
  187. for (; iarg < argc; ++iarg) {
  188. std::string arg{argv[iarg]};
  189. if (arg == "-h" || arg == "--help") {
  190. print_usage_information(argv[0].c_str());
  191. return 0;
  192. }
  193. else if (arg == "--ids") {
  194. printing_ids = true;
  195. }
  196. else if (arg == "-m" || arg == "--model") {
  197. if (model_path_set) {
  198. fprintf(stderr, "Error: -m or --model specified multiple times.\n");
  199. return 1;
  200. }
  201. model_path = argv[++iarg].c_str();
  202. model_path_set = true;
  203. }
  204. else if (arg == "--no-bos") {
  205. no_bos = true;
  206. }
  207. else if (arg == "--no-parse-special") {
  208. no_parse_special = true;
  209. }
  210. else if (arg == "-p" || arg == "--prompt") {
  211. if (prompt_set) {
  212. fprintf(stderr, "Error: -p or --prompt specified multiple times.\n");
  213. return 1;
  214. }
  215. prompt_arg = argv[++iarg].c_str();
  216. prompt_set = true;
  217. }
  218. else if (arg == "-f" || arg == "--file") {
  219. if (prompt_path_set) {
  220. fprintf(stderr, "Error: -f or --file specified multiple times.\n");
  221. return 1;
  222. }
  223. prompt_path = argv[++iarg].c_str();
  224. prompt_path_set = true;
  225. }
  226. else if (arg == "--stdin") {
  227. stdin_set = true;
  228. }
  229. else if (arg == "--log-disable") {
  230. disable_logging = true;
  231. }
  232. else if (arg == "--show-count") {
  233. show_token_count = true;
  234. }
  235. else {
  236. fprintf(stderr, "Error: unknown option '%s'\n", argv[iarg].c_str());
  237. return 1;
  238. }
  239. }
  240. //////
  241. // Sanity check the command line arguments.
  242. //////
  243. // Check that we have the required stuff set.
  244. if (model_path_set && model_path == NULL) {
  245. fprintf(stderr, "Error: --model requires an argument.\n");
  246. return 1;
  247. }
  248. if (!model_path_set) {
  249. fprintf(stderr, "Error: must specify --model.\n");
  250. return 1;
  251. }
  252. if (prompt_path_set && prompt_path == NULL) {
  253. fprintf(stderr, "Error: --file requires an argument.\n");
  254. return 1;
  255. }
  256. if (prompt_set && prompt_arg == NULL) {
  257. fprintf(stderr, "Error: --prompt requires an argument.\n");
  258. return 1;
  259. }
  260. const int prompts_set = !!(prompt_path_set) + !!(prompt_set) + !!(stdin_set);
  261. if (prompts_set > 1) {
  262. fprintf(stderr, "Error: --stdin, --file and --prompt are mutually exclusive.\n");
  263. return 1;
  264. }
  265. // Must have some prompt.
  266. if (prompts_set == 0) {
  267. fprintf(stderr, "Error: must specify one of: --stdin, --file or --prompt.\n");
  268. return 1;
  269. }
  270. GGML_ASSERT(model_path);
  271. GGML_ASSERT(prompt_path || prompt_arg || stdin_set);
  272. //////
  273. // Figure out where will the prompt come from.
  274. //////
  275. std::string prompt;
  276. if (prompt_path_set) {
  277. bool success = false;
  278. prompt = read_prompt_from_file(prompt_path, success);
  279. if (!success) {
  280. return 1;
  281. }
  282. } else if (prompt_set) {
  283. prompt = prompt_arg;
  284. } else {
  285. GGML_ASSERT(stdin_set);
  286. // we read stdin *after* loading model (early exit if model cannot
  287. // be loaded, which can be a nicer user experience)
  288. }
  289. //////
  290. // Start actually doing the tokenizing stuff.
  291. //////
  292. if (disable_logging) {
  293. llama_log_set(llama_log_callback_null, NULL);
  294. }
  295. llama_backend_init();
  296. llama_model_params model_params = llama_model_default_params();
  297. model_params.vocab_only = true;
  298. llama_model * model = llama_load_model_from_file(model_path, model_params);
  299. if (!model) {
  300. fprintf(stderr, "Error: could not load model from file '%s'.\n", model_path);
  301. return 1;
  302. }
  303. llama_context_params ctx_params = llama_context_default_params();
  304. llama_context * ctx = llama_new_context_with_model(model, ctx_params);
  305. if (!ctx) {
  306. fprintf(stderr, "Error: could not create context.\n");
  307. return 1;
  308. }
  309. // read entire prompt from stdin?
  310. if (stdin_set) {
  311. GGML_ASSERT(!prompt_path_set && !prompt_set);
  312. std::stringstream stdin_buffer;
  313. stdin_buffer << std::cin.rdbuf();
  314. if (std::cin.fail()) {
  315. fprintf(stderr, "Error: could not read the entire standard input.\n");
  316. return 1;
  317. }
  318. prompt = stdin_buffer.str();
  319. }
  320. const bool model_wants_add_bos = llama_add_bos_token(model);
  321. const bool add_bos = model_wants_add_bos && !no_bos;
  322. const bool parse_special = !no_parse_special;
  323. std::vector<llama_token> tokens;
  324. tokens = ::llama_tokenize(model, prompt, add_bos, parse_special);
  325. if (printing_ids) {
  326. printf("[");
  327. }
  328. for (int i = 0; i < (int) tokens.size(); i++) {
  329. if (printing_ids) {
  330. if (i > 0) {
  331. printf(", ");
  332. }
  333. printf("%d", tokens[i]);
  334. } else {
  335. bool invalid_utf8 = false;
  336. printf("%6d -> '", tokens[i]);
  337. write_utf8_cstr_to_stdout(llama_token_to_piece(ctx, tokens[i]).c_str(), invalid_utf8);
  338. if (invalid_utf8) {
  339. printf("' (utf-8 decode failure)\n");
  340. } else {
  341. printf("'\n");
  342. }
  343. }
  344. }
  345. if (printing_ids) {
  346. printf("]\n");
  347. }
  348. if (show_token_count) {
  349. printf("Total number of tokens: %ld\n", tokens.size());
  350. }
  351. // silence valgrind
  352. llama_free(ctx);
  353. llama_free_model(model);
  354. return 0;
  355. }