common.cpp 21 KB

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