tokenize.cpp 13 KB

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