common.cpp 39 KB

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