common.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. #include "common.h"
  2. #include <cassert>
  3. #include <cstring>
  4. #include <fstream>
  5. #include <string>
  6. #include <iterator>
  7. #include <algorithm>
  8. #include <sstream>
  9. #include <iostream>
  10. #if defined (_WIN32)
  11. #include <fcntl.h>
  12. #include <io.h>
  13. #pragma comment(lib,"kernel32.lib")
  14. extern "C" __declspec(dllimport) void* __stdcall GetStdHandle(unsigned long nStdHandle);
  15. extern "C" __declspec(dllimport) int __stdcall GetConsoleMode(void* hConsoleHandle, unsigned long* lpMode);
  16. extern "C" __declspec(dllimport) int __stdcall SetConsoleMode(void* hConsoleHandle, unsigned long dwMode);
  17. extern "C" __declspec(dllimport) int __stdcall SetConsoleCP(unsigned int wCodePageID);
  18. extern "C" __declspec(dllimport) int __stdcall SetConsoleOutputCP(unsigned int wCodePageID);
  19. extern "C" __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int CodePage, unsigned long dwFlags,
  20. const wchar_t * lpWideCharStr, int cchWideChar,
  21. char * lpMultiByteStr, int cbMultiByte,
  22. const char * lpDefaultChar, bool * lpUsedDefaultChar);
  23. #define CP_UTF8 65001
  24. #endif
  25. bool gpt_params_parse(int argc, char ** argv, gpt_params & params) {
  26. // determine sensible default number of threads.
  27. // std::thread::hardware_concurrency may not be equal to the number of cores, or may return 0.
  28. #ifdef __linux__
  29. std::ifstream cpuinfo("/proc/cpuinfo");
  30. params.n_threads = std::count(std::istream_iterator<std::string>(cpuinfo),
  31. std::istream_iterator<std::string>(),
  32. std::string("processor"));
  33. #endif
  34. if (params.n_threads == 0) {
  35. params.n_threads = std::max(1, (int32_t) std::thread::hardware_concurrency());
  36. }
  37. bool invalid_param = false;
  38. std::string arg;
  39. gpt_params default_params;
  40. for (int i = 1; i < argc; i++) {
  41. arg = argv[i];
  42. if (arg == "-s" || arg == "--seed") {
  43. if (++i >= argc) {
  44. invalid_param = true;
  45. break;
  46. }
  47. params.seed = std::stoi(argv[i]);
  48. } else if (arg == "-t" || arg == "--threads") {
  49. if (++i >= argc) {
  50. invalid_param = true;
  51. break;
  52. }
  53. params.n_threads = std::stoi(argv[i]);
  54. } else if (arg == "-p" || arg == "--prompt") {
  55. if (++i >= argc) {
  56. invalid_param = true;
  57. break;
  58. }
  59. params.prompt = argv[i];
  60. } else if (arg == "--session") {
  61. if (++i >= argc) {
  62. invalid_param = true;
  63. break;
  64. }
  65. params.path_session = argv[i];
  66. } else if (arg == "-f" || arg == "--file") {
  67. if (++i >= argc) {
  68. invalid_param = true;
  69. break;
  70. }
  71. std::ifstream file(argv[i]);
  72. if (!file) {
  73. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  74. invalid_param = true;
  75. break;
  76. }
  77. std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(params.prompt));
  78. if (params.prompt.back() == '\n') {
  79. params.prompt.pop_back();
  80. }
  81. } else if (arg == "-n" || arg == "--n_predict") {
  82. if (++i >= argc) {
  83. invalid_param = true;
  84. break;
  85. }
  86. params.n_predict = std::stoi(argv[i]);
  87. } else if (arg == "--top_k") {
  88. if (++i >= argc) {
  89. invalid_param = true;
  90. break;
  91. }
  92. params.top_k = std::stoi(argv[i]);
  93. } else if (arg == "-c" || arg == "--ctx_size") {
  94. if (++i >= argc) {
  95. invalid_param = true;
  96. break;
  97. }
  98. params.n_ctx = std::stoi(argv[i]);
  99. } else if (arg == "--memory_f32") {
  100. params.memory_f16 = false;
  101. } else if (arg == "--top_p") {
  102. if (++i >= argc) {
  103. invalid_param = true;
  104. break;
  105. }
  106. params.top_p = std::stof(argv[i]);
  107. } else if (arg == "--temp") {
  108. if (++i >= argc) {
  109. invalid_param = true;
  110. break;
  111. }
  112. params.temp = std::stof(argv[i]);
  113. } else if (arg == "--tfs") {
  114. if (++i >= argc) {
  115. invalid_param = true;
  116. break;
  117. }
  118. params.tfs_z = std::stof(argv[i]);
  119. } else if (arg == "--typical") {
  120. if (++i >= argc) {
  121. invalid_param = true;
  122. break;
  123. }
  124. params.typical_p = std::stof(argv[i]);
  125. } else if (arg == "--repeat_last_n") {
  126. if (++i >= argc) {
  127. invalid_param = true;
  128. break;
  129. }
  130. params.repeat_last_n = std::stoi(argv[i]);
  131. } else if (arg == "--repeat_penalty") {
  132. if (++i >= argc) {
  133. invalid_param = true;
  134. break;
  135. }
  136. params.repeat_penalty = std::stof(argv[i]);
  137. } else if (arg == "--frequency_penalty") {
  138. if (++i >= argc) {
  139. invalid_param = true;
  140. break;
  141. }
  142. params.frequency_penalty = std::stof(argv[i]);
  143. } else if (arg == "--presence_penalty") {
  144. if (++i >= argc) {
  145. invalid_param = true;
  146. break;
  147. }
  148. params.presence_penalty = std::stof(argv[i]);
  149. } else if (arg == "--mirostat") {
  150. if (++i >= argc) {
  151. invalid_param = true;
  152. break;
  153. }
  154. params.mirostat = std::stoi(argv[i]);
  155. } else if (arg == "--mirostat_lr") {
  156. if (++i >= argc) {
  157. invalid_param = true;
  158. break;
  159. }
  160. params.mirostat_eta = std::stof(argv[i]);
  161. } else if (arg == "--mirostat_ent") {
  162. if (++i >= argc) {
  163. invalid_param = true;
  164. break;
  165. }
  166. params.mirostat_tau = std::stof(argv[i]);
  167. } else if (arg == "-b" || arg == "--batch_size") {
  168. if (++i >= argc) {
  169. invalid_param = true;
  170. break;
  171. }
  172. params.n_batch = std::stoi(argv[i]);
  173. params.n_batch = std::min(512, params.n_batch);
  174. } else if (arg == "--keep") {
  175. if (++i >= argc) {
  176. invalid_param = true;
  177. break;
  178. }
  179. params.n_keep = std::stoi(argv[i]);
  180. } else if (arg == "-m" || arg == "--model") {
  181. if (++i >= argc) {
  182. invalid_param = true;
  183. break;
  184. }
  185. params.model = argv[i];
  186. } else if (arg == "--lora") {
  187. if (++i >= argc) {
  188. invalid_param = true;
  189. break;
  190. }
  191. params.lora_adapter = argv[i];
  192. params.use_mmap = false;
  193. } else if (arg == "--lora-base") {
  194. if (++i >= argc) {
  195. invalid_param = true;
  196. break;
  197. }
  198. params.lora_base = argv[i];
  199. } else if (arg == "-i" || arg == "--interactive") {
  200. params.interactive = true;
  201. } else if (arg == "--embedding") {
  202. params.embedding = true;
  203. } else if (arg == "--interactive-first") {
  204. params.interactive_first = true;
  205. } else if (arg == "-ins" || arg == "--instruct") {
  206. params.instruct = true;
  207. } else if (arg == "--color") {
  208. params.use_color = true;
  209. } else if (arg == "--mlock") {
  210. params.use_mlock = true;
  211. } else if (arg == "--no-mmap") {
  212. params.use_mmap = false;
  213. } else if (arg == "--mtest") {
  214. params.mem_test = true;
  215. } else if (arg == "--verbose-prompt") {
  216. params.verbose_prompt = true;
  217. } else if (arg == "-r" || arg == "--reverse-prompt") {
  218. if (++i >= argc) {
  219. invalid_param = true;
  220. break;
  221. }
  222. params.antiprompt.push_back(argv[i]);
  223. } else if (arg == "--perplexity") {
  224. params.perplexity = true;
  225. } else if (arg == "--ignore-eos") {
  226. params.logit_bias[llama_token_eos()] = -INFINITY;
  227. } else if (arg == "--no-penalize-nl") {
  228. params.penalize_nl = false;
  229. } else if (arg == "-l" || arg == "--logit-bias") {
  230. if (++i >= argc) {
  231. invalid_param = true;
  232. break;
  233. }
  234. std::stringstream ss(argv[i]);
  235. llama_token key;
  236. char sign;
  237. std::string value_str;
  238. try {
  239. if (ss >> key && ss >> sign && std::getline(ss, value_str) && (sign == '+' || sign == '-')) {
  240. params.logit_bias[key] = std::stof(value_str) * ((sign == '-') ? -1.0f : 1.0f);
  241. } else {
  242. throw std::exception();
  243. }
  244. } catch (const std::exception &e) {
  245. invalid_param = true;
  246. break;
  247. }
  248. } else if (arg == "--n_parts") {
  249. if (++i >= argc) {
  250. invalid_param = true;
  251. break;
  252. }
  253. params.n_parts = std::stoi(argv[i]);
  254. } else if (arg == "-h" || arg == "--help") {
  255. gpt_print_usage(argc, argv, default_params);
  256. exit(0);
  257. } else if (arg == "--random-prompt") {
  258. params.random_prompt = true;
  259. } else if (arg == "--in-prefix") {
  260. if (++i >= argc) {
  261. invalid_param = true;
  262. break;
  263. }
  264. params.input_prefix = argv[i];
  265. } else {
  266. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  267. gpt_print_usage(argc, argv, default_params);
  268. exit(1);
  269. }
  270. }
  271. if (invalid_param) {
  272. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  273. gpt_print_usage(argc, argv, default_params);
  274. exit(1);
  275. }
  276. return true;
  277. }
  278. void gpt_print_usage(int /*argc*/, char ** argv, const gpt_params & params) {
  279. fprintf(stderr, "usage: %s [options]\n", argv[0]);
  280. fprintf(stderr, "\n");
  281. fprintf(stderr, "options:\n");
  282. fprintf(stderr, " -h, --help show this help message and exit\n");
  283. fprintf(stderr, " -i, --interactive run in interactive mode\n");
  284. fprintf(stderr, " --interactive-first run in interactive mode and wait for input right away\n");
  285. fprintf(stderr, " -ins, --instruct run in instruction mode (use with Alpaca models)\n");
  286. fprintf(stderr, " -r PROMPT, --reverse-prompt PROMPT\n");
  287. fprintf(stderr, " run in interactive mode and poll user input upon seeing PROMPT (can be\n");
  288. fprintf(stderr, " specified more than once for multiple prompts).\n");
  289. fprintf(stderr, " --color colorise output to distinguish prompt and user input from generations\n");
  290. fprintf(stderr, " -s SEED, --seed SEED RNG seed (default: -1, use random seed for <= 0)\n");
  291. fprintf(stderr, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
  292. fprintf(stderr, " -p PROMPT, --prompt PROMPT\n");
  293. fprintf(stderr, " prompt to start generation with (default: empty)\n");
  294. fprintf(stderr, " --session FNAME file to cache model state in (may be large!) (default: none)\n");
  295. fprintf(stderr, " --random-prompt start with a randomized prompt.\n");
  296. fprintf(stderr, " --in-prefix STRING string to prefix user inputs with (default: empty)\n");
  297. fprintf(stderr, " -f FNAME, --file FNAME\n");
  298. fprintf(stderr, " prompt file to start generation.\n");
  299. fprintf(stderr, " -n N, --n_predict N number of tokens to predict (default: %d, -1 = infinity)\n", params.n_predict);
  300. fprintf(stderr, " --top_k N top-k sampling (default: %d, 0 = disabled)\n", params.top_k);
  301. fprintf(stderr, " --top_p N top-p sampling (default: %.1f, 1.0 = disabled)\n", (double)params.top_p);
  302. fprintf(stderr, " --tfs N tail free sampling, parameter z (default: %.1f, 1.0 = disabled)\n", (double)params.tfs_z);
  303. fprintf(stderr, " --typical N locally typical sampling, parameter p (default: %.1f, 1.0 = disabled)\n", (double)params.typical_p);
  304. fprintf(stderr, " --repeat_last_n N last n tokens to consider for penalize (default: %d, 0 = disabled, -1 = ctx_size)\n", params.repeat_last_n);
  305. fprintf(stderr, " --repeat_penalty N penalize repeat sequence of tokens (default: %.1f, 1.0 = disabled)\n", (double)params.repeat_penalty);
  306. fprintf(stderr, " --presence_penalty N repeat alpha presence penalty (default: %.1f, 0.0 = disabled)\n", (double)params.presence_penalty);
  307. fprintf(stderr, " --frequency_penalty N repeat alpha frequency penalty (default: %.1f, 0.0 = disabled)\n", (double)params.frequency_penalty);
  308. fprintf(stderr, " --mirostat N use Mirostat sampling.\n");
  309. fprintf(stderr, " Top K, Nucleus, Tail Free and Locally Typical samplers are ignored if used.\n");
  310. fprintf(stderr, " (default: %d, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)\n", params.mirostat);
  311. fprintf(stderr, " --mirostat_lr N Mirostat learning rate, parameter eta (default: %.1f)\n", (double)params.mirostat_eta);
  312. fprintf(stderr, " --mirostat_ent N Mirostat target entropy, parameter tau (default: %.1f)\n", (double)params.mirostat_tau);
  313. fprintf(stderr, " -l TOKEN_ID(+/-)BIAS, --logit-bias TOKEN_ID(+/-)BIAS\n");
  314. fprintf(stderr, " modifies the likelihood of token appearing in the completion,\n");
  315. fprintf(stderr, " i.e. `--logit-bias 15043+1` to increase likelihood of token ' Hello',\n");
  316. fprintf(stderr, " or `--logit-bias 15043-1` to decrease likelihood of token ' Hello'\n");
  317. fprintf(stderr, " -c N, --ctx_size N size of the prompt context (default: %d)\n", params.n_ctx);
  318. fprintf(stderr, " --ignore-eos ignore end of stream token and continue generating (implies --logit-bias 2-inf)\n");
  319. fprintf(stderr, " --no-penalize-nl do not penalize newline token\n");
  320. fprintf(stderr, " --memory_f32 use f32 instead of f16 for memory key+value\n");
  321. fprintf(stderr, " --temp N temperature (default: %.1f)\n", (double)params.temp);
  322. fprintf(stderr, " --n_parts N number of model parts (default: -1 = determine from dimensions)\n");
  323. fprintf(stderr, " -b N, --batch_size N batch size for prompt processing (default: %d)\n", params.n_batch);
  324. fprintf(stderr, " --perplexity compute perplexity over the prompt\n");
  325. fprintf(stderr, " --keep number of tokens to keep from the initial prompt (default: %d, -1 = all)\n", params.n_keep);
  326. if (llama_mlock_supported()) {
  327. fprintf(stderr, " --mlock force system to keep model in RAM rather than swapping or compressing\n");
  328. }
  329. if (llama_mmap_supported()) {
  330. fprintf(stderr, " --no-mmap do not memory-map model (slower load but may reduce pageouts if not using mlock)\n");
  331. }
  332. fprintf(stderr, " --mtest compute maximum memory usage\n");
  333. fprintf(stderr, " --verbose-prompt print prompt before generation\n");
  334. fprintf(stderr, " --lora FNAME apply LoRA adapter (implies --no-mmap)\n");
  335. fprintf(stderr, " --lora-base FNAME optional model to use as a base for the layers modified by the LoRA adapter\n");
  336. fprintf(stderr, " -m FNAME, --model FNAME\n");
  337. fprintf(stderr, " model path (default: %s)\n", params.model.c_str());
  338. fprintf(stderr, "\n");
  339. }
  340. std::string gpt_random_prompt(std::mt19937 & rng) {
  341. const int r = rng() % 10;
  342. switch (r) {
  343. case 0: return "So";
  344. case 1: return "Once upon a time";
  345. case 2: return "When";
  346. case 3: return "The";
  347. case 4: return "After";
  348. case 5: return "If";
  349. case 6: return "import";
  350. case 7: return "He";
  351. case 8: return "She";
  352. case 9: return "They";
  353. default: return "To";
  354. }
  355. return "The";
  356. }
  357. // TODO: not great allocating this every time
  358. std::vector<llama_token> llama_tokenize(struct llama_context * ctx, const std::string & text, bool add_bos) {
  359. // initialize to prompt numer of chars, since n_tokens <= n_prompt_chars
  360. std::vector<llama_token> res(text.size() + (int)add_bos);
  361. int n = llama_tokenize(ctx, text.c_str(), res.data(), res.size(), add_bos);
  362. assert(n >= 0);
  363. res.resize(n);
  364. return res;
  365. }
  366. /* Keep track of current color of output, and emit ANSI code if it changes. */
  367. void set_console_color(console_state & con_st, console_color_t color) {
  368. if (con_st.use_color && con_st.color != color) {
  369. switch(color) {
  370. case CONSOLE_COLOR_DEFAULT:
  371. printf(ANSI_COLOR_RESET);
  372. break;
  373. case CONSOLE_COLOR_PROMPT:
  374. printf(ANSI_COLOR_YELLOW);
  375. break;
  376. case CONSOLE_COLOR_USER_INPUT:
  377. printf(ANSI_BOLD ANSI_COLOR_GREEN);
  378. break;
  379. }
  380. con_st.color = color;
  381. }
  382. }
  383. #if defined (_WIN32)
  384. void win32_console_init(bool enable_color) {
  385. unsigned long dwMode = 0;
  386. void* hConOut = GetStdHandle((unsigned long)-11); // STD_OUTPUT_HANDLE (-11)
  387. if (!hConOut || hConOut == (void*)-1 || !GetConsoleMode(hConOut, &dwMode)) {
  388. hConOut = GetStdHandle((unsigned long)-12); // STD_ERROR_HANDLE (-12)
  389. if (hConOut && (hConOut == (void*)-1 || !GetConsoleMode(hConOut, &dwMode))) {
  390. hConOut = 0;
  391. }
  392. }
  393. if (hConOut) {
  394. // Enable ANSI colors on Windows 10+
  395. if (enable_color && !(dwMode & 0x4)) {
  396. SetConsoleMode(hConOut, dwMode | 0x4); // ENABLE_VIRTUAL_TERMINAL_PROCESSING (0x4)
  397. }
  398. // Set console output codepage to UTF8
  399. SetConsoleOutputCP(CP_UTF8);
  400. }
  401. void* hConIn = GetStdHandle((unsigned long)-10); // STD_INPUT_HANDLE (-10)
  402. if (hConIn && hConIn != (void*)-1 && GetConsoleMode(hConIn, &dwMode)) {
  403. // Set console input codepage to UTF16
  404. _setmode(_fileno(stdin), _O_WTEXT);
  405. }
  406. }
  407. // Convert a wide Unicode string to an UTF8 string
  408. void win32_utf8_encode(const std::wstring & wstr, std::string & str) {
  409. int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
  410. std::string strTo(size_needed, 0);
  411. WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL);
  412. str = strTo;
  413. }
  414. #endif