common.cpp 15 KB

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