common.cpp 39 KB

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