common.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. #include "common.h"
  2. #include <cassert>
  3. #include <cstring>
  4. #include <iostream>
  5. #include <fstream>
  6. #include <sstream>
  7. #include <string>
  8. #include <iterator>
  9. #include <algorithm>
  10. #include <regex>
  11. #if defined (_WIN32)
  12. #include <fcntl.h>
  13. #include <io.h>
  14. #pragma comment(lib,"kernel32.lib")
  15. extern "C" __declspec(dllimport) void* __stdcall GetStdHandle(unsigned long nStdHandle);
  16. extern "C" __declspec(dllimport) int __stdcall GetConsoleMode(void* hConsoleHandle, unsigned long* lpMode);
  17. extern "C" __declspec(dllimport) int __stdcall SetConsoleMode(void* hConsoleHandle, unsigned long dwMode);
  18. extern "C" __declspec(dllimport) int __stdcall SetConsoleCP(unsigned int wCodePageID);
  19. extern "C" __declspec(dllimport) int __stdcall SetConsoleOutputCP(unsigned int wCodePageID);
  20. extern "C" __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int CodePage, unsigned long dwFlags,
  21. const wchar_t * lpWideCharStr, int cchWideChar,
  22. char * lpMultiByteStr, int cbMultiByte,
  23. const char * lpDefaultChar, bool * lpUsedDefaultChar);
  24. #define CP_UTF8 65001
  25. #endif
  26. void split_args(const std::string & args_string, std::vector<std::string> & output_args)
  27. {
  28. std::string current_arg = "";
  29. bool in_quotes = false;
  30. char quote_type;
  31. for (char c : args_string) {
  32. if (c == '"' || c == '\'') {
  33. if (!in_quotes) {
  34. in_quotes = true;
  35. quote_type = c;
  36. } else if (quote_type == c) {
  37. in_quotes = false;
  38. } else {
  39. current_arg += c;
  40. }
  41. } else if (in_quotes) {
  42. current_arg += c;
  43. } else if (std::isspace(c)) {
  44. if (current_arg != "") {
  45. output_args.push_back(current_arg);
  46. current_arg = "";
  47. }
  48. } else {
  49. current_arg += c;
  50. }
  51. }
  52. if (current_arg != "") {
  53. output_args.push_back(current_arg);
  54. }
  55. }
  56. std::string unescape(const std::string & str) {
  57. return std::regex_replace(str, std::regex("\\\\n"), "\n");
  58. }
  59. bool gpt_params_parse(int argc, char ** argv, gpt_params & params) {
  60. // determine sensible default number of threads.
  61. // std::thread::hardware_concurrency may not be equal to the number of cores, or may return 0.
  62. #ifdef __linux__
  63. std::ifstream cpuinfo("/proc/cpuinfo");
  64. params.n_threads = std::count(std::istream_iterator<std::string>(cpuinfo),
  65. std::istream_iterator<std::string>(),
  66. std::string("processor"));
  67. #endif
  68. if (params.n_threads == 0) {
  69. params.n_threads = std::max(1, (int32_t) std::thread::hardware_concurrency());
  70. }
  71. bool invalid_param = false;
  72. std::string arg;
  73. gpt_params default_params;
  74. // get additional arguments from config files
  75. std::vector<std::string> args;
  76. for (int i = 1; i < argc; i++) {
  77. arg = argv[i];
  78. if (arg == "--config") {
  79. if (++i >= argc) {
  80. invalid_param = true;
  81. break;
  82. }
  83. std::ifstream file(argv[i]);
  84. if (!file) {
  85. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  86. invalid_param = true;
  87. break;
  88. }
  89. std::string args_string;
  90. std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(args_string));
  91. if (args_string.back() == '\n') {
  92. args_string.pop_back();
  93. }
  94. split_args(args_string, args);
  95. for (int j = 0; j < args.size(); j++) {
  96. args[j] = unescape(args[j]);
  97. }
  98. } else {
  99. args.emplace_back(argv[i]);
  100. }
  101. }
  102. // parse args
  103. int args_c = static_cast<int>(args.size());
  104. for (int i = 0; i < args_c && !invalid_param; i++) {
  105. arg = args[i];
  106. if (arg == "-s" || arg == "--seed") {
  107. if (++i >= args_c) {
  108. invalid_param = true;
  109. break;
  110. }
  111. params.seed = std::stoi(args[i]);
  112. } else if (arg == "-t" || arg == "--threads") {
  113. if (++i >= args_c) {
  114. invalid_param = true;
  115. break;
  116. }
  117. params.n_threads = std::stoi(args[i]);
  118. } else if (arg == "-p" || arg == "--prompt") {
  119. if (++i >= args_c) {
  120. invalid_param = true;
  121. break;
  122. }
  123. params.prompt = args[i];
  124. } else if (arg == "-f" || arg == "--file") {
  125. if (++i >= args_c) {
  126. invalid_param = true;
  127. break;
  128. }
  129. std::ifstream file(args[i]);
  130. if (!file) {
  131. fprintf(stderr, "error: failed to open file '%s'\n", args[i].c_str());
  132. invalid_param = true;
  133. break;
  134. }
  135. std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(params.prompt));
  136. if (params.prompt.back() == '\n') {
  137. params.prompt.pop_back();
  138. }
  139. } else if (arg == "-n" || arg == "--n_predict") {
  140. if (++i >= args_c) {
  141. invalid_param = true;
  142. break;
  143. }
  144. params.n_predict = std::stoi(args[i]);
  145. } else if (arg == "--top_k") {
  146. if (++i >= args_c) {
  147. invalid_param = true;
  148. break;
  149. }
  150. params.top_k = std::stoi(args[i]);
  151. } else if (arg == "-c" || arg == "--ctx_size") {
  152. if (++i >= args_c) {
  153. invalid_param = true;
  154. break;
  155. }
  156. params.n_ctx = std::stoi(args[i]);
  157. } else if (arg == "--memory_f32") {
  158. params.memory_f16 = false;
  159. } else if (arg == "--top_p") {
  160. if (++i >= args_c) {
  161. invalid_param = true;
  162. break;
  163. }
  164. params.top_p = std::stof(args[i]);
  165. } else if (arg == "--temp") {
  166. if (++i >= args_c) {
  167. invalid_param = true;
  168. break;
  169. }
  170. params.temp = std::stof(args[i]);
  171. } else if (arg == "--repeat_last_n") {
  172. if (++i >= args_c) {
  173. invalid_param = true;
  174. break;
  175. }
  176. params.repeat_last_n = std::stoi(args[i]);
  177. } else if (arg == "--repeat_penalty") {
  178. if (++i >= args_c) {
  179. invalid_param = true;
  180. break;
  181. }
  182. params.repeat_penalty = std::stof(args[i]);
  183. } else if (arg == "-b" || arg == "--batch_size") {
  184. if (++i >= args_c) {
  185. invalid_param = true;
  186. break;
  187. }
  188. params.n_batch = std::stoi(args[i]);
  189. params.n_batch = std::min(512, params.n_batch);
  190. } else if (arg == "--keep") {
  191. if (++i >= args_c) {
  192. invalid_param = true;
  193. break;
  194. }
  195. params.n_keep = std::stoi(args[i]);
  196. } else if (arg == "-m" || arg == "--model") {
  197. if (++i >= args_c) {
  198. invalid_param = true;
  199. break;
  200. }
  201. params.model = args[i];
  202. } else if (arg == "-i" || arg == "--interactive") {
  203. params.interactive = true;
  204. } else if (arg == "--embedding") {
  205. params.embedding = true;
  206. } else if (arg == "--clean-interface") {
  207. params.clean_interface = true;
  208. } else if (arg == "--interactive-start") {
  209. params.interactive = true;
  210. } else if (arg == "--interactive-first") {
  211. params.interactive_start = true;
  212. } else if (arg == "-ins" || arg == "--instruct") {
  213. fprintf(stderr, "\n\nWarning: instruct mode is deprecated! Use: \n"
  214. "--clean-interface "
  215. "--interactive-first "
  216. "--keep -1 "
  217. "--ins-prefix-bos "
  218. "--ins-prefix \"\\n\\n### Instruction:\\n\\n\" "
  219. "--ins-suffix \"\\n\\n### Response:\\n\\n\" "
  220. "-r \"### Instruction:\\n\\n\" "
  221. "\n\n");
  222. // params.instruct = true;
  223. params.clean_interface = true;
  224. params.interactive_start = true;
  225. params.n_keep = -1;
  226. params.instruct_prefix_bos = true;
  227. params.instruct_prefix = "\n\n### Instruction:\n\n";
  228. params.instruct_suffix = "\n\n### Response:\n\n";
  229. params.antiprompt.push_back("### Instruction:\n\n");
  230. } else if (arg == "--color") {
  231. params.use_color = true;
  232. } else if (arg == "--disable-multiline") {
  233. params.multiline_mode = false;
  234. } else if (arg == "--mlock") {
  235. params.use_mlock = true;
  236. } else if (arg == "--no-mmap") {
  237. params.use_mmap = false;
  238. } else if (arg == "--mtest") {
  239. params.mem_test = true;
  240. } else if (arg == "--verbose-prompt") {
  241. params.verbose_prompt = true;
  242. } else if (arg == "-r" || arg == "--reverse-prompt") {
  243. if (++i >= args_c) {
  244. invalid_param = true;
  245. break;
  246. }
  247. params.antiprompt.push_back(args[i]);
  248. } else if (arg == "--stop-prompt") {
  249. if (++i >= args_c) {
  250. invalid_param = true;
  251. break;
  252. }
  253. params.stopprompt.push_back(args[i]);
  254. } else if (arg == "--rm-trailing-space-workaround") {
  255. params.rm_trailing_space_workaround = true;
  256. } else if (arg == "--perplexity") {
  257. params.perplexity = true;
  258. } else if (arg == "--ignore-eos") {
  259. params.ignore_eos = true;
  260. } else if (arg == "--n_parts") {
  261. if (++i >= args_c) {
  262. invalid_param = true;
  263. break;
  264. }
  265. params.n_parts = std::stoi(args[i]);
  266. } else if (arg == "-h" || arg == "--help") {
  267. gpt_print_usage(argv[0], default_params);
  268. exit(0);
  269. } else if (arg == "--random-prompt") {
  270. params.random_prompt = true;
  271. } else if (arg == "--in-prefix") {
  272. if (++i >= args_c) {
  273. invalid_param = true;
  274. break;
  275. }
  276. params.input_prefix = args[i];
  277. } else if (arg == "--ins-prefix-bos") {
  278. params.instruct_prefix_bos = true;
  279. } else if (arg == "--ins-prefix") {
  280. if (++i >= args_c) {
  281. invalid_param = true;
  282. break;
  283. }
  284. params.instruct_prefix = args[i];
  285. } else if (arg == "--ins-suffix-bos") {
  286. params.instruct_suffix_bos = true;
  287. } else if (arg == "--ins-suffix") {
  288. if (++i >= args_c) {
  289. invalid_param = true;
  290. break;
  291. }
  292. params.instruct_suffix = args[i];
  293. } else {
  294. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  295. gpt_print_usage(argv[0], default_params);
  296. exit(1);
  297. }
  298. }
  299. if (invalid_param) {
  300. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  301. gpt_print_usage(argv[0], default_params);
  302. exit(1);
  303. }
  304. return true;
  305. }
  306. void gpt_print_usage(char * argv_0, const gpt_params & params) {
  307. fprintf(stderr, "usage: %s [options]\n", argv_0);
  308. fprintf(stderr, "\n");
  309. fprintf(stderr, "options:\n");
  310. fprintf(stderr, " -h, --help show this help message and exit\n");
  311. fprintf(stderr, " -i, --interactive run in interactive mode\n");
  312. fprintf(stderr, " --interactive-first run in interactive mode and wait for input right away\n");
  313. fprintf(stderr, " --clean-interface hides input prefix & suffix and displays '>' instead\n");
  314. fprintf(stderr, " -r PROMPT, --reverse-prompt PROMPT\n");
  315. fprintf(stderr, " run in interactive mode and poll user input upon seeing PROMPT (can be\n");
  316. fprintf(stderr, " specified more than once for multiple prompts).\n");
  317. fprintf(stderr, " --color colorise output to distinguish prompt and user input from generations\n");
  318. fprintf(stderr, " --disable-multiline disable multiline mode (use Ctrl+D on Linux/Mac and Ctrl+Z then Return on Windows to toggle multiline)\n");
  319. fprintf(stderr, " -s SEED, --seed SEED RNG seed (default: -1, use random seed for <= 0)\n");
  320. fprintf(stderr, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
  321. fprintf(stderr, " -p PROMPT, --prompt PROMPT\n");
  322. fprintf(stderr, " prompt to start generation with (default: empty)\n");
  323. fprintf(stderr, " --random-prompt start with a randomized prompt.\n");
  324. fprintf(stderr, " --in-prefix STRING string to prefix user inputs with (default: empty)\n");
  325. fprintf(stderr, " --ins-prefix STRING (instruct) prefix user inputs with tokenized string (default: empty)\n");
  326. fprintf(stderr, " --ins-prefix-bos (instruct) prepend bos token to instruct prefix.\n");
  327. fprintf(stderr, " --ins-suffix STRING (instruct) suffix user inputs with tokenized string (default: empty)\n");
  328. fprintf(stderr, " --ins-suffix-bos (instruct) prepend bos token to instruct suffix.\n");
  329. fprintf(stderr, " -f FNAME, --file FNAME\n");
  330. fprintf(stderr, " prompt file to start generation.\n");
  331. fprintf(stderr, " -n N, --n_predict N number of tokens to predict (default: %d, -1 = infinity)\n", params.n_predict);
  332. fprintf(stderr, " --top_k N top-k sampling (default: %d)\n", params.top_k);
  333. fprintf(stderr, " --top_p N top-p sampling (default: %.1f)\n", (double)params.top_p);
  334. fprintf(stderr, " --repeat_last_n N last n tokens to consider for penalize (default: %d)\n", params.repeat_last_n);
  335. fprintf(stderr, " --repeat_penalty N penalize repeat sequence of tokens (default: %.1f)\n", (double)params.repeat_penalty);
  336. fprintf(stderr, " -c N, --ctx_size N size of the prompt context (default: %d)\n", params.n_ctx);
  337. fprintf(stderr, " --ignore-eos ignore end of stream token and continue generating\n");
  338. fprintf(stderr, " --memory_f32 use f32 instead of f16 for memory key+value\n");
  339. fprintf(stderr, " --temp N temperature (default: %.1f)\n", (double)params.temp);
  340. fprintf(stderr, " --n_parts N number of model parts (default: -1 = determine from dimensions)\n");
  341. fprintf(stderr, " -b N, --batch_size N batch size for prompt processing (default: %d)\n", params.n_batch);
  342. fprintf(stderr, " --perplexity compute perplexity over the prompt\n");
  343. fprintf(stderr, " --keep number of tokens to keep from the initial prompt (default: %d, -1 = all)\n", params.n_keep);
  344. if (llama_mlock_supported()) {
  345. fprintf(stderr, " --mlock force system to keep model in RAM rather than swapping or compressing\n");
  346. }
  347. if (llama_mmap_supported()) {
  348. fprintf(stderr, " --no-mmap do not memory-map model (slower load but may reduce pageouts if not using mlock)\n");
  349. }
  350. fprintf(stderr, " --mtest compute maximum memory usage\n");
  351. fprintf(stderr, " --verbose-prompt print prompt before generation\n");
  352. fprintf(stderr, " -m FNAME, --model FNAME\n");
  353. fprintf(stderr, " model path (default: %s)\n", params.model.c_str());
  354. fprintf(stderr, "\n");
  355. }
  356. std::string gpt_random_prompt(std::mt19937 & rng) {
  357. const int r = rng() % 10;
  358. switch (r) {
  359. case 0: return "So";
  360. case 1: return "Once upon a time";
  361. case 2: return "When";
  362. case 3: return "The";
  363. case 4: return "After";
  364. case 5: return "If";
  365. case 6: return "import";
  366. case 7: return "He";
  367. case 8: return "She";
  368. case 9: return "They";
  369. default: return "To";
  370. }
  371. return "The";
  372. }
  373. // TODO: not great allocating this every time
  374. std::vector<llama_token> llama_tokenize(struct llama_context * ctx, const std::string & text, bool add_bos) {
  375. // initialize to prompt numer of chars, since n_tokens <= n_prompt_chars
  376. std::vector<llama_token> res(text.size() + (int)add_bos);
  377. int n = llama_tokenize(ctx, text.c_str(), res.data(), res.size(), add_bos);
  378. assert(n >= 0);
  379. res.resize(n);
  380. return res;
  381. }
  382. /* Keep track of current color of output, and emit ANSI code if it changes. */
  383. void set_console_color(console_state & con_st, console_color_t color) {
  384. if (con_st.use_color && con_st.color != color) {
  385. switch(color) {
  386. case CONSOLE_COLOR_DEFAULT:
  387. printf(ANSI_COLOR_RESET);
  388. break;
  389. case CONSOLE_COLOR_PROMPT:
  390. printf(ANSI_COLOR_YELLOW);
  391. break;
  392. case CONSOLE_COLOR_USER_INPUT:
  393. printf(ANSI_BOLD ANSI_COLOR_GREEN);
  394. break;
  395. }
  396. con_st.color = color;
  397. }
  398. }
  399. #if defined (_WIN32)
  400. void win32_console_init(bool enable_color) {
  401. unsigned long dwMode = 0;
  402. void* hConOut = GetStdHandle((unsigned long)-11); // STD_OUTPUT_HANDLE (-11)
  403. if (!hConOut || hConOut == (void*)-1 || !GetConsoleMode(hConOut, &dwMode)) {
  404. hConOut = GetStdHandle((unsigned long)-12); // STD_ERROR_HANDLE (-12)
  405. if (hConOut && (hConOut == (void*)-1 || !GetConsoleMode(hConOut, &dwMode))) {
  406. hConOut = 0;
  407. }
  408. }
  409. if (hConOut) {
  410. // Enable ANSI colors on Windows 10+
  411. if (enable_color && !(dwMode & 0x4)) {
  412. SetConsoleMode(hConOut, dwMode | 0x4); // ENABLE_VIRTUAL_TERMINAL_PROCESSING (0x4)
  413. }
  414. // Set console output codepage to UTF8
  415. SetConsoleOutputCP(CP_UTF8);
  416. }
  417. void* hConIn = GetStdHandle((unsigned long)-10); // STD_INPUT_HANDLE (-10)
  418. if (hConIn && hConIn != (void*)-1 && GetConsoleMode(hConIn, &dwMode)) {
  419. // Set console input codepage to UTF16
  420. _setmode(_fileno(stdin), _O_WTEXT);
  421. }
  422. }
  423. // Convert a wide Unicode string to an UTF8 string
  424. void win32_utf8_encode(const std::wstring & wstr, std::string & str) {
  425. int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
  426. std::string strTo(size_needed, 0);
  427. WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL);
  428. str = strTo;
  429. }
  430. #endif
  431. bool get_input_text(std::string & input_text, bool eof_toggled_multiline_mode) {
  432. bool another_line = true;
  433. bool is_eof_multiline_toggled = false;
  434. do {
  435. std::string line;
  436. #if defined(_WIN32)
  437. auto & stdcin = std::wcin;
  438. std::wstring wline;
  439. if (!std::getline(stdcin, wline)) {
  440. // input stream is bad or EOF received
  441. if (stdcin.bad()) {
  442. fprintf(stderr, "%s: error: input stream bad\n", __func__);
  443. return 1;
  444. }
  445. }
  446. win32_utf8_encode(wline, line);
  447. #else
  448. auto & stdcin = std::cin;
  449. if (!std::getline(stdcin, line)) {
  450. // input stream is bad or EOF received
  451. if (stdcin.bad()) {
  452. fprintf(stderr, "%s: error: input stream bad\n", __func__);
  453. return 1;
  454. }
  455. }
  456. #endif
  457. if (stdcin.eof()) {
  458. stdcin.clear();
  459. stdcin.seekg(0, std::ios::beg);
  460. if (!eof_toggled_multiline_mode) {
  461. another_line = false;
  462. } else {
  463. is_eof_multiline_toggled = !is_eof_multiline_toggled;
  464. if (is_eof_multiline_toggled) {
  465. input_text += line;
  466. continue;
  467. }
  468. }
  469. }
  470. if (!eof_toggled_multiline_mode) {
  471. if (line.empty() || line.back() != '\\') {
  472. another_line = false;
  473. } else {
  474. line.pop_back(); // Remove the continue character
  475. }
  476. } else {
  477. if (!is_eof_multiline_toggled) {
  478. another_line = false;
  479. }
  480. }
  481. input_text += line;
  482. if (another_line) {
  483. input_text += '\n'; // Append the line to the result
  484. }
  485. } while (another_line);
  486. return true;
  487. }