tokenize.cpp 13 KB

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