common.cpp 41 KB

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