tokenize.cpp 13 KB

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