1
0

common.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  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. #include <unordered_set>
  11. #include <regex>
  12. #if defined(__APPLE__) && defined(__MACH__)
  13. #include <sys/types.h>
  14. #include <sys/sysctl.h>
  15. #endif
  16. #if defined(_WIN32)
  17. #define WIN32_LEAN_AND_MEAN
  18. #define NOMINMAX
  19. #include <windows.h>
  20. #include <fcntl.h>
  21. #include <io.h>
  22. #else
  23. #include <sys/ioctl.h>
  24. #include <unistd.h>
  25. #include <wchar.h>
  26. #endif
  27. #if defined(_MSC_VER)
  28. #pragma warning(disable: 4244 4267) // possible loss of data
  29. #endif
  30. int32_t get_num_physical_cores() {
  31. #ifdef __linux__
  32. // enumerate the set of thread siblings, num entries is num cores
  33. std::unordered_set<std::string> siblings;
  34. for (uint32_t cpu=0; cpu < UINT32_MAX; ++cpu) {
  35. std::ifstream thread_siblings("/sys/devices/system/cpu"
  36. + std::to_string(cpu) + "/topology/thread_siblings");
  37. if (!thread_siblings.is_open()) {
  38. break; // no more cpus
  39. }
  40. std::string line;
  41. if (std::getline(thread_siblings, line)) {
  42. siblings.insert(line);
  43. }
  44. }
  45. if (siblings.size() > 0) {
  46. return static_cast<int32_t>(siblings.size());
  47. }
  48. #elif defined(__APPLE__) && defined(__MACH__)
  49. int32_t num_physical_cores;
  50. size_t len = sizeof(num_physical_cores);
  51. int result = sysctlbyname("hw.perflevel0.physicalcpu", &num_physical_cores, &len, NULL, 0);
  52. if (result == 0) {
  53. return num_physical_cores;
  54. }
  55. result = sysctlbyname("hw.physicalcpu", &num_physical_cores, &len, NULL, 0);
  56. if (result == 0) {
  57. return num_physical_cores;
  58. }
  59. #elif defined(_WIN32)
  60. //TODO: Implement
  61. #endif
  62. unsigned int n_threads = std::thread::hardware_concurrency();
  63. return n_threads > 0 ? (n_threads <= 4 ? n_threads : n_threads / 2) : 4;
  64. }
  65. void process_escapes(std::string& input) {
  66. std::size_t input_len = input.length();
  67. std::size_t output_idx = 0;
  68. for (std::size_t input_idx = 0; input_idx < input_len; ++input_idx) {
  69. if (input[input_idx] == '\\' && input_idx + 1 < input_len) {
  70. switch (input[++input_idx]) {
  71. case 'n': input[output_idx++] = '\n'; break;
  72. case 'r': input[output_idx++] = '\r'; break;
  73. case 't': input[output_idx++] = '\t'; break;
  74. case '\'': input[output_idx++] = '\''; break;
  75. case '\"': input[output_idx++] = '\"'; break;
  76. case '\\': input[output_idx++] = '\\'; break;
  77. default: input[output_idx++] = '\\';
  78. input[output_idx++] = input[input_idx]; break;
  79. }
  80. } else {
  81. input[output_idx++] = input[input_idx];
  82. }
  83. }
  84. input.resize(output_idx);
  85. }
  86. bool gpt_params_parse(int argc, char ** argv, gpt_params & params) {
  87. bool invalid_param = false;
  88. bool escape_prompt = false;
  89. std::string arg;
  90. gpt_params default_params;
  91. const std::string arg_prefix = "--";
  92. for (int i = 1; i < argc; i++) {
  93. arg = argv[i];
  94. if (arg.compare(0, arg_prefix.size(), arg_prefix) == 0) {
  95. std::replace(arg.begin(), arg.end(), '_', '-');
  96. }
  97. if (arg == "-s" || arg == "--seed") {
  98. if (++i >= argc) {
  99. invalid_param = true;
  100. break;
  101. }
  102. params.seed = std::stoul(argv[i]);
  103. } else if (arg == "-t" || arg == "--threads") {
  104. if (++i >= argc) {
  105. invalid_param = true;
  106. break;
  107. }
  108. params.n_threads = std::stoi(argv[i]);
  109. } else if (arg == "-p" || arg == "--prompt") {
  110. if (++i >= argc) {
  111. invalid_param = true;
  112. break;
  113. }
  114. params.prompt = argv[i];
  115. } else if (arg == "-e") {
  116. escape_prompt = true;
  117. } else if (arg == "--prompt-cache") {
  118. if (++i >= argc) {
  119. invalid_param = true;
  120. break;
  121. }
  122. params.path_prompt_cache = argv[i];
  123. } else if (arg == "--prompt-cache-all") {
  124. params.prompt_cache_all = true;
  125. } else if (arg == "--prompt-cache-ro") {
  126. params.prompt_cache_ro = true;
  127. } else if (arg == "-f" || arg == "--file") {
  128. if (++i >= argc) {
  129. invalid_param = true;
  130. break;
  131. }
  132. std::ifstream file(argv[i]);
  133. if (!file) {
  134. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  135. invalid_param = true;
  136. break;
  137. }
  138. std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(params.prompt));
  139. if (params.prompt.back() == '\n') {
  140. params.prompt.pop_back();
  141. }
  142. } else if (arg == "-n" || arg == "--n-predict") {
  143. if (++i >= argc) {
  144. invalid_param = true;
  145. break;
  146. }
  147. params.n_predict = std::stoi(argv[i]);
  148. } else if (arg == "--top-k") {
  149. if (++i >= argc) {
  150. invalid_param = true;
  151. break;
  152. }
  153. params.top_k = std::stoi(argv[i]);
  154. } else if (arg == "-c" || arg == "--ctx-size") {
  155. if (++i >= argc) {
  156. invalid_param = true;
  157. break;
  158. }
  159. params.n_ctx = std::stoi(argv[i]);
  160. } else if (arg == "--memory-f32") {
  161. params.memory_f16 = false;
  162. } else if (arg == "--top-p") {
  163. if (++i >= argc) {
  164. invalid_param = true;
  165. break;
  166. }
  167. params.top_p = std::stof(argv[i]);
  168. } else if (arg == "--temp") {
  169. if (++i >= argc) {
  170. invalid_param = true;
  171. break;
  172. }
  173. params.temp = std::stof(argv[i]);
  174. } else if (arg == "--tfs") {
  175. if (++i >= argc) {
  176. invalid_param = true;
  177. break;
  178. }
  179. params.tfs_z = std::stof(argv[i]);
  180. } else if (arg == "--typical") {
  181. if (++i >= argc) {
  182. invalid_param = true;
  183. break;
  184. }
  185. params.typical_p = std::stof(argv[i]);
  186. } else if (arg == "--repeat-last-n") {
  187. if (++i >= argc) {
  188. invalid_param = true;
  189. break;
  190. }
  191. params.repeat_last_n = std::stoi(argv[i]);
  192. } else if (arg == "--repeat-penalty") {
  193. if (++i >= argc) {
  194. invalid_param = true;
  195. break;
  196. }
  197. params.repeat_penalty = std::stof(argv[i]);
  198. } else if (arg == "--frequency-penalty") {
  199. if (++i >= argc) {
  200. invalid_param = true;
  201. break;
  202. }
  203. params.frequency_penalty = std::stof(argv[i]);
  204. } else if (arg == "--presence-penalty") {
  205. if (++i >= argc) {
  206. invalid_param = true;
  207. break;
  208. }
  209. params.presence_penalty = std::stof(argv[i]);
  210. } else if (arg == "--mirostat") {
  211. if (++i >= argc) {
  212. invalid_param = true;
  213. break;
  214. }
  215. params.mirostat = std::stoi(argv[i]);
  216. } else if (arg == "--mirostat-lr") {
  217. if (++i >= argc) {
  218. invalid_param = true;
  219. break;
  220. }
  221. params.mirostat_eta = std::stof(argv[i]);
  222. } else if (arg == "--mirostat-ent") {
  223. if (++i >= argc) {
  224. invalid_param = true;
  225. break;
  226. }
  227. params.mirostat_tau = std::stof(argv[i]);
  228. } else if (arg == "--cfg-negative-prompt") {
  229. if (++i >= argc) {
  230. invalid_param = true;
  231. break;
  232. }
  233. params.cfg_negative_prompt = argv[i];
  234. } else if (arg == "--cfg-scale") {
  235. if (++i >= argc) {
  236. invalid_param = true;
  237. break;
  238. }
  239. params.cfg_scale = std::stof(argv[i]);
  240. } else if (arg == "--cfg-smooth-factor") {
  241. if (++i >= argc) {
  242. invalid_param = true;
  243. break;
  244. }
  245. params.cfg_smooth_factor = std::stof(argv[i]);
  246. } else if (arg == "-b" || arg == "--batch-size") {
  247. if (++i >= argc) {
  248. invalid_param = true;
  249. break;
  250. }
  251. params.n_batch = std::stoi(argv[i]);
  252. params.n_batch = std::min(512, params.n_batch);
  253. } else if (arg == "--keep") {
  254. if (++i >= argc) {
  255. invalid_param = true;
  256. break;
  257. }
  258. params.n_keep = std::stoi(argv[i]);
  259. } else if (arg == "-m" || arg == "--model") {
  260. if (++i >= argc) {
  261. invalid_param = true;
  262. break;
  263. }
  264. params.model = argv[i];
  265. } else if (arg == "-a" || arg == "--alias") {
  266. if (++i >= argc) {
  267. invalid_param = true;
  268. break;
  269. }
  270. params.model_alias = argv[i];
  271. } else if (arg == "--lora") {
  272. if (++i >= argc) {
  273. invalid_param = true;
  274. break;
  275. }
  276. params.lora_adapter = argv[i];
  277. } else if (arg == "--lora-base") {
  278. if (++i >= argc) {
  279. invalid_param = true;
  280. break;
  281. }
  282. params.lora_base = argv[i];
  283. } else if (arg == "-i" || arg == "--interactive") {
  284. params.interactive = true;
  285. } else if (arg == "--embedding") {
  286. params.embedding = true;
  287. } else if (arg == "--interactive-first") {
  288. params.interactive_first = true;
  289. } else if (arg == "-ins" || arg == "--instruct") {
  290. params.instruct = true;
  291. } else if (arg == "--multiline-input") {
  292. params.multiline_input = true;
  293. } else if (arg == "--color") {
  294. params.use_color = true;
  295. } else if (arg == "--mlock") {
  296. params.use_mlock = true;
  297. } else if (arg == "--gpu-layers" || arg == "-ngl" || arg == "--n-gpu-layers") {
  298. if (++i >= argc) {
  299. invalid_param = true;
  300. break;
  301. }
  302. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  303. params.n_gpu_layers = std::stoi(argv[i]);
  304. #else
  305. fprintf(stderr, "warning: not compiled with GPU offload support, --n-gpu-layers option will be ignored\n");
  306. fprintf(stderr, "warning: see main README.md for information on enabling GPU BLAS support\n");
  307. #endif
  308. } else if (arg == "--main-gpu" || arg == "-mg") {
  309. if (++i >= argc) {
  310. invalid_param = true;
  311. break;
  312. }
  313. #ifdef GGML_USE_CUBLAS
  314. params.main_gpu = std::stoi(argv[i]);
  315. #else
  316. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set a main GPU.\n");
  317. #endif
  318. } else if (arg == "--tensor-split" || arg == "-ts") {
  319. if (++i >= argc) {
  320. invalid_param = true;
  321. break;
  322. }
  323. #ifdef GGML_USE_CUBLAS
  324. std::string arg_next = argv[i];
  325. // split string by , and /
  326. const std::regex regex{R"([,/]+)"};
  327. std::sregex_token_iterator it{arg_next.begin(), arg_next.end(), regex, -1};
  328. std::vector<std::string> split_arg{it, {}};
  329. GGML_ASSERT(split_arg.size() <= LLAMA_MAX_DEVICES);
  330. for (size_t i = 0; i < LLAMA_MAX_DEVICES; ++i) {
  331. if (i < split_arg.size()) {
  332. params.tensor_split[i] = std::stof(split_arg[i]);
  333. } else {
  334. params.tensor_split[i] = 0.0f;
  335. }
  336. }
  337. #else
  338. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set a tensor split.\n");
  339. #endif // GGML_USE_CUBLAS
  340. } else if (arg == "--low-vram" || arg == "-lv") {
  341. #ifdef GGML_USE_CUBLAS
  342. params.low_vram = true;
  343. #else
  344. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set lower vram usage.\n");
  345. #endif // GGML_USE_CUBLAS
  346. } else if (arg == "--no-mmap") {
  347. params.use_mmap = false;
  348. } else if (arg == "--mtest") {
  349. params.mem_test = true;
  350. } else if (arg == "--numa") {
  351. params.numa = true;
  352. } else if (arg == "--export") {
  353. params.export_cgraph = true;
  354. } else if (arg == "--verbose-prompt") {
  355. params.verbose_prompt = true;
  356. } else if (arg == "-r" || arg == "--reverse-prompt") {
  357. if (++i >= argc) {
  358. invalid_param = true;
  359. break;
  360. }
  361. params.antiprompt.push_back(argv[i]);
  362. } else if (arg == "--perplexity") {
  363. params.perplexity = true;
  364. } else if (arg == "--ignore-eos") {
  365. params.logit_bias[llama_token_eos()] = -INFINITY;
  366. } else if (arg == "--no-penalize-nl") {
  367. params.penalize_nl = false;
  368. } else if (arg == "-l" || arg == "--logit-bias") {
  369. if (++i >= argc) {
  370. invalid_param = true;
  371. break;
  372. }
  373. std::stringstream ss(argv[i]);
  374. llama_token key;
  375. char sign;
  376. std::string value_str;
  377. try {
  378. if (ss >> key && ss >> sign && std::getline(ss, value_str) && (sign == '+' || sign == '-')) {
  379. params.logit_bias[key] = std::stof(value_str) * ((sign == '-') ? -1.0f : 1.0f);
  380. } else {
  381. throw std::exception();
  382. }
  383. } catch (const std::exception&) {
  384. invalid_param = true;
  385. break;
  386. }
  387. } else if (arg == "-h" || arg == "--help") {
  388. gpt_print_usage(argc, argv, default_params);
  389. exit(0);
  390. } else if (arg == "--random-prompt") {
  391. params.random_prompt = true;
  392. } else if (arg == "--in-prefix") {
  393. if (++i >= argc) {
  394. invalid_param = true;
  395. break;
  396. }
  397. params.input_prefix = argv[i];
  398. } else if (arg == "--in-suffix") {
  399. if (++i >= argc) {
  400. invalid_param = true;
  401. break;
  402. }
  403. params.input_suffix = argv[i];
  404. } else {
  405. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  406. gpt_print_usage(argc, argv, default_params);
  407. exit(1);
  408. }
  409. }
  410. if (invalid_param) {
  411. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  412. gpt_print_usage(argc, argv, default_params);
  413. exit(1);
  414. }
  415. if (params.prompt_cache_all &&
  416. (params.interactive || params.interactive_first ||
  417. params.instruct)) {
  418. fprintf(stderr, "error: --prompt-cache-all not supported in interactive mode yet\n");
  419. gpt_print_usage(argc, argv, default_params);
  420. exit(1);
  421. }
  422. if (escape_prompt) {
  423. process_escapes(params.prompt);
  424. process_escapes(params.input_prefix);
  425. process_escapes(params.input_suffix);
  426. }
  427. return true;
  428. }
  429. void gpt_print_usage(int /*argc*/, char ** argv, const gpt_params & params) {
  430. fprintf(stderr, "usage: %s [options]\n", argv[0]);
  431. fprintf(stderr, "\n");
  432. fprintf(stderr, "options:\n");
  433. fprintf(stderr, " -h, --help show this help message and exit\n");
  434. fprintf(stderr, " -i, --interactive run in interactive mode\n");
  435. fprintf(stderr, " --interactive-first run in interactive mode and wait for input right away\n");
  436. fprintf(stderr, " -ins, --instruct run in instruction mode (use with Alpaca models)\n");
  437. fprintf(stderr, " --multiline-input allows you to write or paste multiple lines without ending each in '\\'\n");
  438. fprintf(stderr, " -r PROMPT, --reverse-prompt PROMPT\n");
  439. fprintf(stderr, " halt generation at PROMPT, return control in interactive mode\n");
  440. fprintf(stderr, " (can be specified more than once for multiple prompts).\n");
  441. fprintf(stderr, " --color colorise output to distinguish prompt and user input from generations\n");
  442. fprintf(stderr, " -s SEED, --seed SEED RNG seed (default: -1, use random seed for < 0)\n");
  443. fprintf(stderr, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
  444. fprintf(stderr, " -p PROMPT, --prompt PROMPT\n");
  445. fprintf(stderr, " prompt to start generation with (default: empty)\n");
  446. fprintf(stderr, " -e process prompt escapes sequences (\\n, \\r, \\t, \\', \\\", \\\\)\n");
  447. fprintf(stderr, " --prompt-cache FNAME file to cache prompt state for faster startup (default: none)\n");
  448. fprintf(stderr, " --prompt-cache-all if specified, saves user input and generations to cache as well.\n");
  449. fprintf(stderr, " not supported with --interactive or other interactive options\n");
  450. fprintf(stderr, " --prompt-cache-ro if specified, uses the prompt cache but does not update it.\n");
  451. fprintf(stderr, " --random-prompt start with a randomized prompt.\n");
  452. fprintf(stderr, " --in-prefix STRING string to prefix user inputs with (default: empty)\n");
  453. fprintf(stderr, " --in-suffix STRING string to suffix after user inputs with (default: empty)\n");
  454. fprintf(stderr, " -f FNAME, --file FNAME\n");
  455. fprintf(stderr, " prompt file to start generation.\n");
  456. fprintf(stderr, " -n N, --n-predict N number of tokens to predict (default: %d, -1 = infinity)\n", params.n_predict);
  457. fprintf(stderr, " --top-k N top-k sampling (default: %d, 0 = disabled)\n", params.top_k);
  458. fprintf(stderr, " --top-p N top-p sampling (default: %.1f, 1.0 = disabled)\n", (double)params.top_p);
  459. fprintf(stderr, " --tfs N tail free sampling, parameter z (default: %.1f, 1.0 = disabled)\n", (double)params.tfs_z);
  460. fprintf(stderr, " --typical N locally typical sampling, parameter p (default: %.1f, 1.0 = disabled)\n", (double)params.typical_p);
  461. 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);
  462. fprintf(stderr, " --repeat-penalty N penalize repeat sequence of tokens (default: %.1f, 1.0 = disabled)\n", (double)params.repeat_penalty);
  463. fprintf(stderr, " --presence-penalty N repeat alpha presence penalty (default: %.1f, 0.0 = disabled)\n", (double)params.presence_penalty);
  464. fprintf(stderr, " --frequency-penalty N repeat alpha frequency penalty (default: %.1f, 0.0 = disabled)\n", (double)params.frequency_penalty);
  465. fprintf(stderr, " --mirostat N use Mirostat sampling.\n");
  466. fprintf(stderr, " Top K, Nucleus, Tail Free and Locally Typical samplers are ignored if used.\n");
  467. fprintf(stderr, " (default: %d, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)\n", params.mirostat);
  468. fprintf(stderr, " --mirostat-lr N Mirostat learning rate, parameter eta (default: %.1f)\n", (double)params.mirostat_eta);
  469. fprintf(stderr, " --mirostat-ent N Mirostat target entropy, parameter tau (default: %.1f)\n", (double)params.mirostat_tau);
  470. fprintf(stderr, " -l TOKEN_ID(+/-)BIAS, --logit-bias TOKEN_ID(+/-)BIAS\n");
  471. fprintf(stderr, " modifies the likelihood of token appearing in the completion,\n");
  472. fprintf(stderr, " i.e. `--logit-bias 15043+1` to increase likelihood of token ' Hello',\n");
  473. fprintf(stderr, " or `--logit-bias 15043-1` to decrease likelihood of token ' Hello'\n");
  474. fprintf(stderr, " --cfg-negative-prompt PROMPT \n");
  475. fprintf(stderr, " negative prompt to use for guidance. (default: empty)\n");
  476. fprintf(stderr, " --cfg-scale N strength of guidance (default: %f, 1.0 = disable)\n", params.cfg_scale);
  477. fprintf(stderr, " --cfg-smooth-factor N smooth factor between old and new logits (default: %f, 1.0 = no smoothing)\n", params.cfg_smooth_factor);
  478. fprintf(stderr, " -c N, --ctx-size N size of the prompt context (default: %d)\n", params.n_ctx);
  479. fprintf(stderr, " --ignore-eos ignore end of stream token and continue generating (implies --logit-bias 2-inf)\n");
  480. fprintf(stderr, " --no-penalize-nl do not penalize newline token\n");
  481. fprintf(stderr, " --memory-f32 use f32 instead of f16 for memory key+value (default: disabled)\n");
  482. fprintf(stderr, " not recommended: doubles context memory required and no measurable increase in quality\n");
  483. fprintf(stderr, " --temp N temperature (default: %.1f)\n", (double)params.temp);
  484. fprintf(stderr, " -b N, --batch-size N batch size for prompt processing (default: %d)\n", params.n_batch);
  485. fprintf(stderr, " --perplexity compute perplexity over the prompt\n");
  486. fprintf(stderr, " --keep number of tokens to keep from the initial prompt (default: %d, -1 = all)\n", params.n_keep);
  487. if (llama_mlock_supported()) {
  488. fprintf(stderr, " --mlock force system to keep model in RAM rather than swapping or compressing\n");
  489. }
  490. if (llama_mmap_supported()) {
  491. fprintf(stderr, " --no-mmap do not memory-map model (slower load but may reduce pageouts if not using mlock)\n");
  492. }
  493. fprintf(stderr, " --numa attempt optimizations that help on some NUMA systems\n");
  494. fprintf(stderr, " if run without this previously, it is recommended to drop the system page cache before using this\n");
  495. fprintf(stderr, " see https://github.com/ggerganov/llama.cpp/issues/1437\n");
  496. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  497. fprintf(stderr, " -ngl N, --n-gpu-layers N\n");
  498. fprintf(stderr, " number of layers to store in VRAM\n");
  499. fprintf(stderr, " -ts SPLIT --tensor-split SPLIT\n");
  500. fprintf(stderr, " how to split tensors across multiple GPUs, comma-separated list of proportions, e.g. 3,1\n");
  501. fprintf(stderr, " -mg i, --main-gpu i the GPU to use for scratch and small tensors\n" );
  502. fprintf(stderr, " -lv, --low-vram don't allocate VRAM scratch buffer\n" );
  503. #endif
  504. fprintf(stderr, " --mtest compute maximum memory usage\n");
  505. fprintf(stderr, " --export export the computation graph to 'llama.ggml'\n");
  506. fprintf(stderr, " --verbose-prompt print prompt before generation\n");
  507. fprintf(stderr, " --lora FNAME apply LoRA adapter\n");
  508. fprintf(stderr, " --lora-base FNAME optional model to use as a base for the layers modified by the LoRA adapter\n");
  509. fprintf(stderr, " -m FNAME, --model FNAME\n");
  510. fprintf(stderr, " model path (default: %s)\n", params.model.c_str());
  511. fprintf(stderr, "\n");
  512. }
  513. std::string gpt_random_prompt(std::mt19937 & rng) {
  514. const int r = rng() % 10;
  515. switch (r) {
  516. case 0: return "So";
  517. case 1: return "Once upon a time";
  518. case 2: return "When";
  519. case 3: return "The";
  520. case 4: return "After";
  521. case 5: return "If";
  522. case 6: return "import";
  523. case 7: return "He";
  524. case 8: return "She";
  525. case 9: return "They";
  526. default: return "To";
  527. }
  528. return "The";
  529. }
  530. // TODO: not great allocating this every time
  531. std::vector<llama_token> llama_tokenize(struct llama_context * ctx, const std::string & text, bool add_bos) {
  532. // initialize to prompt numer of chars, since n_tokens <= n_prompt_chars
  533. std::vector<llama_token> res(text.size() + (int) add_bos);
  534. const int n = llama_tokenize(ctx, text.c_str(), res.data(), res.size(), add_bos);
  535. assert(n >= 0);
  536. res.resize(n);
  537. return res;
  538. }
  539. struct llama_context_params llama_context_params_from_gpt_params(const gpt_params & params) {
  540. auto lparams = llama_context_default_params();
  541. lparams.n_ctx = params.n_ctx;
  542. lparams.n_batch = params.n_batch;
  543. lparams.n_gpu_layers = params.n_gpu_layers;
  544. lparams.main_gpu = params.main_gpu;
  545. memcpy(lparams.tensor_split, params.tensor_split, LLAMA_MAX_DEVICES*sizeof(float));
  546. lparams.low_vram = params.low_vram;
  547. lparams.seed = params.seed;
  548. lparams.f16_kv = params.memory_f16;
  549. lparams.use_mmap = params.use_mmap;
  550. lparams.use_mlock = params.use_mlock;
  551. lparams.logits_all = params.perplexity;
  552. lparams.embedding = params.embedding;
  553. return lparams;
  554. }
  555. std::tuple<struct llama_model *, struct llama_context *> llama_init_from_gpt_params(const gpt_params & params) {
  556. auto lparams = llama_context_params_from_gpt_params(params);
  557. llama_model * model = llama_load_model_from_file(params.model.c_str(), lparams);
  558. if (model == NULL) {
  559. fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, params.model.c_str());
  560. return std::make_tuple(nullptr, nullptr);
  561. }
  562. llama_context * lctx = llama_new_context_with_model(model, lparams);
  563. if (lctx == NULL) {
  564. fprintf(stderr, "%s: error: failed to create context with model '%s'\n", __func__, params.model.c_str());
  565. llama_free_model(model);
  566. return std::make_tuple(nullptr, nullptr);
  567. }
  568. if (!params.lora_adapter.empty()) {
  569. int err = llama_model_apply_lora_from_file(model,
  570. params.lora_adapter.c_str(),
  571. params.lora_base.empty() ? NULL : params.lora_base.c_str(),
  572. params.n_threads);
  573. if (err != 0) {
  574. fprintf(stderr, "%s: error: failed to apply lora adapter\n", __func__);
  575. llama_free(lctx);
  576. llama_free_model(model);
  577. return std::make_tuple(nullptr, nullptr);
  578. }
  579. }
  580. return std::make_tuple(model, lctx);
  581. }
  582. void console_init(console_state & con_st) {
  583. #if defined(_WIN32)
  584. // Windows-specific console initialization
  585. DWORD dwMode = 0;
  586. con_st.hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
  587. if (con_st.hConsole == INVALID_HANDLE_VALUE || !GetConsoleMode(con_st.hConsole, &dwMode)) {
  588. con_st.hConsole = GetStdHandle(STD_ERROR_HANDLE);
  589. if (con_st.hConsole != INVALID_HANDLE_VALUE && (!GetConsoleMode(con_st.hConsole, &dwMode))) {
  590. con_st.hConsole = NULL;
  591. }
  592. }
  593. if (con_st.hConsole) {
  594. // Enable ANSI colors on Windows 10+
  595. if (con_st.use_color && !(dwMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING)) {
  596. SetConsoleMode(con_st.hConsole, dwMode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
  597. }
  598. // Set console output codepage to UTF8
  599. SetConsoleOutputCP(CP_UTF8);
  600. }
  601. HANDLE hConIn = GetStdHandle(STD_INPUT_HANDLE);
  602. if (hConIn != INVALID_HANDLE_VALUE && GetConsoleMode(hConIn, &dwMode)) {
  603. // Set console input codepage to UTF16
  604. _setmode(_fileno(stdin), _O_WTEXT);
  605. // Turn off ICANON (ENABLE_LINE_INPUT) and ECHO (ENABLE_ECHO_INPUT)
  606. dwMode &= ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
  607. SetConsoleMode(hConIn, dwMode);
  608. }
  609. #else
  610. // POSIX-specific console initialization
  611. struct termios new_termios;
  612. tcgetattr(STDIN_FILENO, &con_st.prev_state);
  613. new_termios = con_st.prev_state;
  614. new_termios.c_lflag &= ~(ICANON | ECHO);
  615. new_termios.c_cc[VMIN] = 1;
  616. new_termios.c_cc[VTIME] = 0;
  617. tcsetattr(STDIN_FILENO, TCSANOW, &new_termios);
  618. con_st.tty = fopen("/dev/tty", "w+");
  619. if (con_st.tty != nullptr) {
  620. con_st.out = con_st.tty;
  621. }
  622. setlocale(LC_ALL, "");
  623. #endif
  624. }
  625. void console_cleanup(console_state & con_st) {
  626. // Reset console color
  627. console_set_color(con_st, CONSOLE_COLOR_DEFAULT);
  628. #if !defined(_WIN32)
  629. if (con_st.tty != nullptr) {
  630. con_st.out = stdout;
  631. fclose(con_st.tty);
  632. con_st.tty = nullptr;
  633. }
  634. // Restore the terminal settings on POSIX systems
  635. tcsetattr(STDIN_FILENO, TCSANOW, &con_st.prev_state);
  636. #endif
  637. }
  638. /* Keep track of current color of output, and emit ANSI code if it changes. */
  639. void console_set_color(console_state & con_st, console_color_t color) {
  640. if (con_st.use_color && con_st.color != color) {
  641. fflush(stdout);
  642. switch(color) {
  643. case CONSOLE_COLOR_DEFAULT:
  644. fprintf(con_st.out, ANSI_COLOR_RESET);
  645. break;
  646. case CONSOLE_COLOR_PROMPT:
  647. fprintf(con_st.out, ANSI_COLOR_YELLOW);
  648. break;
  649. case CONSOLE_COLOR_USER_INPUT:
  650. fprintf(con_st.out, ANSI_BOLD ANSI_COLOR_GREEN);
  651. break;
  652. case CONSOLE_COLOR_ERROR:
  653. fprintf(con_st.out, ANSI_BOLD ANSI_COLOR_RED);
  654. break;
  655. }
  656. con_st.color = color;
  657. fflush(con_st.out);
  658. }
  659. }
  660. char32_t getchar32() {
  661. #if defined(_WIN32)
  662. HANDLE hConsole = GetStdHandle(STD_INPUT_HANDLE);
  663. wchar_t high_surrogate = 0;
  664. while (true) {
  665. INPUT_RECORD record;
  666. DWORD count;
  667. if (!ReadConsoleInputW(hConsole, &record, 1, &count) || count == 0) {
  668. return WEOF;
  669. }
  670. if (record.EventType == KEY_EVENT && record.Event.KeyEvent.bKeyDown) {
  671. wchar_t wc = record.Event.KeyEvent.uChar.UnicodeChar;
  672. if (wc == 0) {
  673. continue;
  674. }
  675. if ((wc >= 0xD800) && (wc <= 0xDBFF)) { // Check if wc is a high surrogate
  676. high_surrogate = wc;
  677. continue;
  678. } else if ((wc >= 0xDC00) && (wc <= 0xDFFF)) { // Check if wc is a low surrogate
  679. if (high_surrogate != 0) { // Check if we have a high surrogate
  680. return ((high_surrogate - 0xD800) << 10) + (wc - 0xDC00) + 0x10000;
  681. }
  682. }
  683. high_surrogate = 0; // Reset the high surrogate
  684. return static_cast<char32_t>(wc);
  685. }
  686. }
  687. #else
  688. wchar_t wc = getwchar();
  689. if (static_cast<wint_t>(wc) == WEOF) {
  690. return WEOF;
  691. }
  692. #if WCHAR_MAX == 0xFFFF
  693. if ((wc >= 0xD800) && (wc <= 0xDBFF)) { // Check if wc is a high surrogate
  694. wchar_t low_surrogate = getwchar();
  695. if ((low_surrogate >= 0xDC00) && (low_surrogate <= 0xDFFF)) { // Check if the next wchar is a low surrogate
  696. return (static_cast<char32_t>(wc & 0x03FF) << 10) + (low_surrogate & 0x03FF) + 0x10000;
  697. }
  698. }
  699. if ((wc >= 0xD800) && (wc <= 0xDFFF)) { // Invalid surrogate pair
  700. return 0xFFFD; // Return the replacement character U+FFFD
  701. }
  702. #endif
  703. return static_cast<char32_t>(wc);
  704. #endif
  705. }
  706. void pop_cursor(console_state & con_st) {
  707. #if defined(_WIN32)
  708. if (con_st.hConsole != NULL) {
  709. CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
  710. GetConsoleScreenBufferInfo(con_st.hConsole, &bufferInfo);
  711. COORD newCursorPosition = bufferInfo.dwCursorPosition;
  712. if (newCursorPosition.X == 0) {
  713. newCursorPosition.X = bufferInfo.dwSize.X - 1;
  714. newCursorPosition.Y -= 1;
  715. } else {
  716. newCursorPosition.X -= 1;
  717. }
  718. SetConsoleCursorPosition(con_st.hConsole, newCursorPosition);
  719. return;
  720. }
  721. #endif
  722. putc('\b', con_st.out);
  723. }
  724. int estimateWidth(char32_t codepoint) {
  725. #if defined(_WIN32)
  726. return 1;
  727. #else
  728. return wcwidth(codepoint);
  729. #endif
  730. }
  731. int put_codepoint(console_state & con_st, const char* utf8_codepoint, size_t length, int expectedWidth) {
  732. #if defined(_WIN32)
  733. CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
  734. if (!GetConsoleScreenBufferInfo(con_st.hConsole, &bufferInfo)) {
  735. // go with the default
  736. return expectedWidth;
  737. }
  738. COORD initialPosition = bufferInfo.dwCursorPosition;
  739. DWORD nNumberOfChars = length;
  740. WriteConsole(con_st.hConsole, utf8_codepoint, nNumberOfChars, &nNumberOfChars, NULL);
  741. CONSOLE_SCREEN_BUFFER_INFO newBufferInfo;
  742. GetConsoleScreenBufferInfo(con_st.hConsole, &newBufferInfo);
  743. // Figure out our real position if we're in the last column
  744. if (utf8_codepoint[0] != 0x09 && initialPosition.X == newBufferInfo.dwSize.X - 1) {
  745. DWORD nNumberOfChars;
  746. WriteConsole(con_st.hConsole, &" \b", 2, &nNumberOfChars, NULL);
  747. GetConsoleScreenBufferInfo(con_st.hConsole, &newBufferInfo);
  748. }
  749. int width = newBufferInfo.dwCursorPosition.X - initialPosition.X;
  750. if (width < 0) {
  751. width += newBufferInfo.dwSize.X;
  752. }
  753. return width;
  754. #else
  755. // we can trust expectedWidth if we've got one
  756. if (expectedWidth >= 0 || con_st.tty == nullptr) {
  757. fwrite(utf8_codepoint, length, 1, con_st.out);
  758. return expectedWidth;
  759. }
  760. fputs("\033[6n", con_st.tty); // Query cursor position
  761. int x1, x2, y1, y2;
  762. int results = 0;
  763. results = fscanf(con_st.tty, "\033[%d;%dR", &y1, &x1);
  764. fwrite(utf8_codepoint, length, 1, con_st.tty);
  765. fputs("\033[6n", con_st.tty); // Query cursor position
  766. results += fscanf(con_st.tty, "\033[%d;%dR", &y2, &x2);
  767. if (results != 4) {
  768. return expectedWidth;
  769. }
  770. int width = x2 - x1;
  771. if (width < 0) {
  772. // Calculate the width considering text wrapping
  773. struct winsize w;
  774. ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
  775. width += w.ws_col;
  776. }
  777. return width;
  778. #endif
  779. }
  780. void replace_last(console_state & con_st, char ch) {
  781. #if defined(_WIN32)
  782. pop_cursor(con_st);
  783. put_codepoint(con_st, &ch, 1, 1);
  784. #else
  785. fprintf(con_st.out, "\b%c", ch);
  786. #endif
  787. }
  788. void append_utf8(char32_t ch, std::string & out) {
  789. if (ch <= 0x7F) {
  790. out.push_back(static_cast<unsigned char>(ch));
  791. } else if (ch <= 0x7FF) {
  792. out.push_back(static_cast<unsigned char>(0xC0 | ((ch >> 6) & 0x1F)));
  793. out.push_back(static_cast<unsigned char>(0x80 | (ch & 0x3F)));
  794. } else if (ch <= 0xFFFF) {
  795. out.push_back(static_cast<unsigned char>(0xE0 | ((ch >> 12) & 0x0F)));
  796. out.push_back(static_cast<unsigned char>(0x80 | ((ch >> 6) & 0x3F)));
  797. out.push_back(static_cast<unsigned char>(0x80 | (ch & 0x3F)));
  798. } else if (ch <= 0x10FFFF) {
  799. out.push_back(static_cast<unsigned char>(0xF0 | ((ch >> 18) & 0x07)));
  800. out.push_back(static_cast<unsigned char>(0x80 | ((ch >> 12) & 0x3F)));
  801. out.push_back(static_cast<unsigned char>(0x80 | ((ch >> 6) & 0x3F)));
  802. out.push_back(static_cast<unsigned char>(0x80 | (ch & 0x3F)));
  803. } else {
  804. // Invalid Unicode code point
  805. }
  806. }
  807. // Helper function to remove the last UTF-8 character from a string
  808. void pop_back_utf8_char(std::string & line) {
  809. if (line.empty()) {
  810. return;
  811. }
  812. size_t pos = line.length() - 1;
  813. // Find the start of the last UTF-8 character (checking up to 4 bytes back)
  814. for (size_t i = 0; i < 3 && pos > 0; ++i, --pos) {
  815. if ((line[pos] & 0xC0) != 0x80) break; // Found the start of the character
  816. }
  817. line.erase(pos);
  818. }
  819. bool console_readline(console_state & con_st, std::string & line) {
  820. console_set_color(con_st, CONSOLE_COLOR_USER_INPUT);
  821. if (con_st.out != stdout) {
  822. fflush(stdout);
  823. }
  824. line.clear();
  825. std::vector<int> widths;
  826. bool is_special_char = false;
  827. bool end_of_stream = false;
  828. char32_t input_char;
  829. while (true) {
  830. fflush(con_st.out); // Ensure all output is displayed before waiting for input
  831. input_char = getchar32();
  832. if (input_char == '\r' || input_char == '\n') {
  833. break;
  834. }
  835. if (input_char == (char32_t) WEOF || input_char == 0x04 /* Ctrl+D*/) {
  836. end_of_stream = true;
  837. break;
  838. }
  839. if (is_special_char) {
  840. console_set_color(con_st, CONSOLE_COLOR_USER_INPUT);
  841. replace_last(con_st, line.back());
  842. is_special_char = false;
  843. }
  844. if (input_char == '\033') { // Escape sequence
  845. char32_t code = getchar32();
  846. if (code == '[' || code == 0x1B) {
  847. // Discard the rest of the escape sequence
  848. while ((code = getchar32()) != (char32_t) WEOF) {
  849. if ((code >= 'A' && code <= 'Z') || (code >= 'a' && code <= 'z') || code == '~') {
  850. break;
  851. }
  852. }
  853. }
  854. } else if (input_char == 0x08 || input_char == 0x7F) { // Backspace
  855. if (!widths.empty()) {
  856. int count;
  857. do {
  858. count = widths.back();
  859. widths.pop_back();
  860. // Move cursor back, print space, and move cursor back again
  861. for (int i = 0; i < count; i++) {
  862. replace_last(con_st, ' ');
  863. pop_cursor(con_st);
  864. }
  865. pop_back_utf8_char(line);
  866. } while (count == 0 && !widths.empty());
  867. }
  868. } else {
  869. int offset = line.length();
  870. append_utf8(input_char, line);
  871. int width = put_codepoint(con_st, line.c_str() + offset, line.length() - offset, estimateWidth(input_char));
  872. if (width < 0) {
  873. width = 0;
  874. }
  875. widths.push_back(width);
  876. }
  877. if (!line.empty() && (line.back() == '\\' || line.back() == '/')) {
  878. console_set_color(con_st, CONSOLE_COLOR_PROMPT);
  879. replace_last(con_st, line.back());
  880. is_special_char = true;
  881. }
  882. }
  883. bool has_more = con_st.multiline_input;
  884. if (is_special_char) {
  885. replace_last(con_st, ' ');
  886. pop_cursor(con_st);
  887. char last = line.back();
  888. line.pop_back();
  889. if (last == '\\') {
  890. line += '\n';
  891. fputc('\n', con_st.out);
  892. has_more = !has_more;
  893. } else {
  894. // llama will just eat the single space, it won't act as a space
  895. if (line.length() == 1 && line.back() == ' ') {
  896. line.clear();
  897. pop_cursor(con_st);
  898. }
  899. has_more = false;
  900. }
  901. } else {
  902. if (end_of_stream) {
  903. has_more = false;
  904. } else {
  905. line += '\n';
  906. fputc('\n', con_st.out);
  907. }
  908. }
  909. fflush(con_st.out);
  910. return has_more;
  911. }