common.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  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. #endif
  26. #if defined(_MSC_VER)
  27. #pragma warning(disable: 4244 4267) // possible loss of data
  28. #endif
  29. int32_t get_num_physical_cores() {
  30. #ifdef __linux__
  31. // enumerate the set of thread siblings, num entries is num cores
  32. std::unordered_set<std::string> siblings;
  33. for (uint32_t cpu=0; cpu < UINT32_MAX; ++cpu) {
  34. std::ifstream thread_siblings("/sys/devices/system/cpu"
  35. + std::to_string(cpu) + "/topology/thread_siblings");
  36. if (!thread_siblings.is_open()) {
  37. break; // no more cpus
  38. }
  39. std::string line;
  40. if (std::getline(thread_siblings, line)) {
  41. siblings.insert(line);
  42. }
  43. }
  44. if (siblings.size() > 0) {
  45. return static_cast<int32_t>(siblings.size());
  46. }
  47. #elif defined(__APPLE__) && defined(__MACH__)
  48. int32_t num_physical_cores;
  49. size_t len = sizeof(num_physical_cores);
  50. int result = sysctlbyname("hw.perflevel0.physicalcpu", &num_physical_cores, &len, NULL, 0);
  51. if (result == 0) {
  52. return num_physical_cores;
  53. }
  54. result = sysctlbyname("hw.physicalcpu", &num_physical_cores, &len, NULL, 0);
  55. if (result == 0) {
  56. return num_physical_cores;
  57. }
  58. #elif defined(_WIN32)
  59. //TODO: Implement
  60. #endif
  61. unsigned int n_threads = std::thread::hardware_concurrency();
  62. return n_threads > 0 ? (n_threads <= 4 ? n_threads : n_threads / 2) : 4;
  63. }
  64. void process_escapes(std::string& input) {
  65. std::size_t input_len = input.length();
  66. std::size_t output_idx = 0;
  67. for (std::size_t input_idx = 0; input_idx < input_len; ++input_idx) {
  68. if (input[input_idx] == '\\' && input_idx + 1 < input_len) {
  69. switch (input[++input_idx]) {
  70. case 'n': input[output_idx++] = '\n'; break;
  71. case 'r': input[output_idx++] = '\r'; break;
  72. case 't': input[output_idx++] = '\t'; break;
  73. case '\'': input[output_idx++] = '\''; break;
  74. case '\"': input[output_idx++] = '\"'; break;
  75. case '\\': input[output_idx++] = '\\'; break;
  76. default: input[output_idx++] = '\\';
  77. input[output_idx++] = input[input_idx]; break;
  78. }
  79. } else {
  80. input[output_idx++] = input[input_idx];
  81. }
  82. }
  83. input.resize(output_idx);
  84. }
  85. bool gpt_params_parse(int argc, char ** argv, gpt_params & params) {
  86. bool invalid_param = false;
  87. bool escape_prompt = false;
  88. std::string arg;
  89. gpt_params default_params;
  90. const std::string arg_prefix = "--";
  91. for (int i = 1; i < argc; i++) {
  92. arg = argv[i];
  93. if (arg.compare(0, arg_prefix.size(), arg_prefix) == 0) {
  94. std::replace(arg.begin(), arg.end(), '_', '-');
  95. }
  96. if (arg == "-s" || arg == "--seed") {
  97. if (++i >= argc) {
  98. invalid_param = true;
  99. break;
  100. }
  101. params.seed = std::stoul(argv[i]);
  102. } else if (arg == "-t" || arg == "--threads") {
  103. if (++i >= argc) {
  104. invalid_param = true;
  105. break;
  106. }
  107. params.n_threads = std::stoi(argv[i]);
  108. if (params.n_threads <= 0) {
  109. params.n_threads = std::thread::hardware_concurrency();
  110. }
  111. } else if (arg == "-p" || arg == "--prompt") {
  112. if (++i >= argc) {
  113. invalid_param = true;
  114. break;
  115. }
  116. params.prompt = argv[i];
  117. } else if (arg == "-e") {
  118. escape_prompt = true;
  119. } else if (arg == "--prompt-cache") {
  120. if (++i >= argc) {
  121. invalid_param = true;
  122. break;
  123. }
  124. params.path_prompt_cache = argv[i];
  125. } else if (arg == "--prompt-cache-all") {
  126. params.prompt_cache_all = true;
  127. } else if (arg == "--prompt-cache-ro") {
  128. params.prompt_cache_ro = true;
  129. } else if (arg == "-f" || arg == "--file") {
  130. if (++i >= argc) {
  131. invalid_param = true;
  132. break;
  133. }
  134. std::ifstream file(argv[i]);
  135. if (!file) {
  136. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  137. invalid_param = true;
  138. break;
  139. }
  140. std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(params.prompt));
  141. if (params.prompt.back() == '\n') {
  142. params.prompt.pop_back();
  143. }
  144. } else if (arg == "-n" || arg == "--n-predict") {
  145. if (++i >= argc) {
  146. invalid_param = true;
  147. break;
  148. }
  149. params.n_predict = std::stoi(argv[i]);
  150. } else if (arg == "--top-k") {
  151. if (++i >= argc) {
  152. invalid_param = true;
  153. break;
  154. }
  155. params.top_k = std::stoi(argv[i]);
  156. } else if (arg == "-c" || arg == "--ctx-size") {
  157. if (++i >= argc) {
  158. invalid_param = true;
  159. break;
  160. }
  161. params.n_ctx = std::stoi(argv[i]);
  162. } else if (arg == "--rope-freq-base") {
  163. if (++i >= argc) {
  164. invalid_param = true;
  165. break;
  166. }
  167. params.rope_freq_base = std::stof(argv[i]);
  168. } else if (arg == "--rope-freq-scale") {
  169. if (++i >= argc) {
  170. invalid_param = true;
  171. break;
  172. }
  173. params.rope_freq_scale = std::stof(argv[i]);
  174. } else if (arg == "--rope-scale") {
  175. if (++i >= argc) {
  176. invalid_param = true;
  177. break;
  178. }
  179. params.rope_freq_scale = 1.0f/std::stof(argv[i]);
  180. } else if (arg == "--memory-f32") {
  181. params.memory_f16 = false;
  182. } else if (arg == "--top-p") {
  183. if (++i >= argc) {
  184. invalid_param = true;
  185. break;
  186. }
  187. params.top_p = std::stof(argv[i]);
  188. } else if (arg == "--temp") {
  189. if (++i >= argc) {
  190. invalid_param = true;
  191. break;
  192. }
  193. params.temp = std::stof(argv[i]);
  194. } else if (arg == "--tfs") {
  195. if (++i >= argc) {
  196. invalid_param = true;
  197. break;
  198. }
  199. params.tfs_z = std::stof(argv[i]);
  200. } else if (arg == "--typical") {
  201. if (++i >= argc) {
  202. invalid_param = true;
  203. break;
  204. }
  205. params.typical_p = std::stof(argv[i]);
  206. } else if (arg == "--repeat-last-n") {
  207. if (++i >= argc) {
  208. invalid_param = true;
  209. break;
  210. }
  211. params.repeat_last_n = std::stoi(argv[i]);
  212. } else if (arg == "--repeat-penalty") {
  213. if (++i >= argc) {
  214. invalid_param = true;
  215. break;
  216. }
  217. params.repeat_penalty = std::stof(argv[i]);
  218. } else if (arg == "--frequency-penalty") {
  219. if (++i >= argc) {
  220. invalid_param = true;
  221. break;
  222. }
  223. params.frequency_penalty = std::stof(argv[i]);
  224. } else if (arg == "--presence-penalty") {
  225. if (++i >= argc) {
  226. invalid_param = true;
  227. break;
  228. }
  229. params.presence_penalty = std::stof(argv[i]);
  230. } else if (arg == "--mirostat") {
  231. if (++i >= argc) {
  232. invalid_param = true;
  233. break;
  234. }
  235. params.mirostat = std::stoi(argv[i]);
  236. } else if (arg == "--mirostat-lr") {
  237. if (++i >= argc) {
  238. invalid_param = true;
  239. break;
  240. }
  241. params.mirostat_eta = std::stof(argv[i]);
  242. } else if (arg == "--mirostat-ent") {
  243. if (++i >= argc) {
  244. invalid_param = true;
  245. break;
  246. }
  247. params.mirostat_tau = std::stof(argv[i]);
  248. } else if (arg == "--cfg-negative-prompt") {
  249. if (++i >= argc) {
  250. invalid_param = true;
  251. break;
  252. }
  253. params.cfg_negative_prompt = argv[i];
  254. } else if (arg == "--cfg-negative-prompt-file") {
  255. if (++i >= argc) {
  256. invalid_param = true;
  257. break;
  258. }
  259. std::ifstream file(argv[i]);
  260. if (!file) {
  261. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  262. invalid_param = true;
  263. break;
  264. }
  265. std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(params.cfg_negative_prompt));
  266. if (params.cfg_negative_prompt.back() == '\n') {
  267. params.cfg_negative_prompt.pop_back();
  268. }
  269. } else if (arg == "--cfg-scale") {
  270. if (++i >= argc) {
  271. invalid_param = true;
  272. break;
  273. }
  274. params.cfg_scale = std::stof(argv[i]);
  275. } else if (arg == "-b" || arg == "--batch-size") {
  276. if (++i >= argc) {
  277. invalid_param = true;
  278. break;
  279. }
  280. params.n_batch = std::stoi(argv[i]);
  281. } else if (arg == "--keep") {
  282. if (++i >= argc) {
  283. invalid_param = true;
  284. break;
  285. }
  286. params.n_keep = std::stoi(argv[i]);
  287. } else if (arg == "--chunks") {
  288. if (++i >= argc) {
  289. invalid_param = true;
  290. break;
  291. }
  292. params.n_chunks = std::stoi(argv[i]);
  293. } else if (arg == "-m" || arg == "--model") {
  294. if (++i >= argc) {
  295. invalid_param = true;
  296. break;
  297. }
  298. params.model = argv[i];
  299. } else if (arg == "-a" || arg == "--alias") {
  300. if (++i >= argc) {
  301. invalid_param = true;
  302. break;
  303. }
  304. params.model_alias = argv[i];
  305. } else if (arg == "--lora") {
  306. if (++i >= argc) {
  307. invalid_param = true;
  308. break;
  309. }
  310. params.lora_adapter = argv[i];
  311. params.use_mmap = false;
  312. } else if (arg == "--lora-base") {
  313. if (++i >= argc) {
  314. invalid_param = true;
  315. break;
  316. }
  317. params.lora_base = argv[i];
  318. } else if (arg == "-i" || arg == "--interactive") {
  319. params.interactive = true;
  320. } else if (arg == "--embedding") {
  321. params.embedding = true;
  322. } else if (arg == "--interactive-first") {
  323. params.interactive_first = true;
  324. } else if (arg == "-ins" || arg == "--instruct") {
  325. params.instruct = true;
  326. } else if (arg == "--multiline-input") {
  327. params.multiline_input = true;
  328. } else if (arg == "--simple-io") {
  329. params.simple_io = true;
  330. } else if (arg == "--color") {
  331. params.use_color = true;
  332. } else if (arg == "--mlock") {
  333. params.use_mlock = true;
  334. } else if (arg == "--gpu-layers" || arg == "-ngl" || arg == "--n-gpu-layers") {
  335. if (++i >= argc) {
  336. invalid_param = true;
  337. break;
  338. }
  339. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  340. params.n_gpu_layers = std::stoi(argv[i]);
  341. #else
  342. fprintf(stderr, "warning: not compiled with GPU offload support, --n-gpu-layers option will be ignored\n");
  343. fprintf(stderr, "warning: see main README.md for information on enabling GPU BLAS support\n");
  344. #endif
  345. } else if (arg == "--main-gpu" || arg == "-mg") {
  346. if (++i >= argc) {
  347. invalid_param = true;
  348. break;
  349. }
  350. #ifdef GGML_USE_CUBLAS
  351. params.main_gpu = std::stoi(argv[i]);
  352. #else
  353. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set a main GPU.\n");
  354. #endif
  355. } else if (arg == "--tensor-split" || arg == "-ts") {
  356. if (++i >= argc) {
  357. invalid_param = true;
  358. break;
  359. }
  360. #ifdef GGML_USE_CUBLAS
  361. std::string arg_next = argv[i];
  362. // split string by , and /
  363. const std::regex regex{R"([,/]+)"};
  364. std::sregex_token_iterator it{arg_next.begin(), arg_next.end(), regex, -1};
  365. std::vector<std::string> split_arg{it, {}};
  366. GGML_ASSERT(split_arg.size() <= LLAMA_MAX_DEVICES);
  367. for (size_t i = 0; i < LLAMA_MAX_DEVICES; ++i) {
  368. if (i < split_arg.size()) {
  369. params.tensor_split[i] = std::stof(split_arg[i]);
  370. } else {
  371. params.tensor_split[i] = 0.0f;
  372. }
  373. }
  374. #else
  375. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set a tensor split.\n");
  376. #endif // GGML_USE_CUBLAS
  377. } else if (arg == "--no-mul-mat-q" || arg == "-nommq") {
  378. #ifdef GGML_USE_CUBLAS
  379. params.mul_mat_q = false;
  380. #else
  381. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. Disabling mul_mat_q kernels has no effect.\n");
  382. #endif // GGML_USE_CUBLAS
  383. } else if (arg == "--low-vram" || arg == "-lv") {
  384. #ifdef GGML_USE_CUBLAS
  385. params.low_vram = true;
  386. #else
  387. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set lower vram usage.\n");
  388. #endif // GGML_USE_CUBLAS
  389. } else if (arg == "--no-mmap") {
  390. params.use_mmap = false;
  391. } else if (arg == "--mtest") {
  392. params.mem_test = true;
  393. } else if (arg == "--numa") {
  394. params.numa = true;
  395. } else if (arg == "--export") {
  396. params.export_cgraph = true;
  397. } else if (arg == "--verbose-prompt") {
  398. params.verbose_prompt = true;
  399. } else if (arg == "-r" || arg == "--reverse-prompt") {
  400. if (++i >= argc) {
  401. invalid_param = true;
  402. break;
  403. }
  404. params.antiprompt.push_back(argv[i]);
  405. } else if (arg == "--perplexity") {
  406. params.perplexity = true;
  407. } else if (arg == "--hellaswag") {
  408. params.hellaswag = true;
  409. } else if (arg == "--hellaswag-tasks") {
  410. if (++i >= argc) {
  411. invalid_param = true;
  412. break;
  413. }
  414. params.hellaswag_tasks = std::stoi(argv[i]);
  415. } else if (arg == "--ignore-eos") {
  416. params.ignore_eos = true;
  417. } else if (arg == "--no-penalize-nl") {
  418. params.penalize_nl = false;
  419. } else if (arg == "-l" || arg == "--logit-bias") {
  420. if (++i >= argc) {
  421. invalid_param = true;
  422. break;
  423. }
  424. std::stringstream ss(argv[i]);
  425. llama_token key;
  426. char sign;
  427. std::string value_str;
  428. try {
  429. if (ss >> key && ss >> sign && std::getline(ss, value_str) && (sign == '+' || sign == '-')) {
  430. params.logit_bias[key] = std::stof(value_str) * ((sign == '-') ? -1.0f : 1.0f);
  431. } else {
  432. throw std::exception();
  433. }
  434. } catch (const std::exception&) {
  435. invalid_param = true;
  436. break;
  437. }
  438. } else if (arg == "-h" || arg == "--help") {
  439. gpt_print_usage(argc, argv, default_params);
  440. exit(0);
  441. } else if (arg == "--random-prompt") {
  442. params.random_prompt = true;
  443. } else if (arg == "--in-prefix-bos") {
  444. params.input_prefix_bos = true;
  445. } else if (arg == "--in-prefix") {
  446. if (++i >= argc) {
  447. invalid_param = true;
  448. break;
  449. }
  450. params.input_prefix = argv[i];
  451. } else if (arg == "--in-suffix") {
  452. if (++i >= argc) {
  453. invalid_param = true;
  454. break;
  455. }
  456. params.input_suffix = argv[i];
  457. } else if (arg == "--grammar") {
  458. if (++i >= argc) {
  459. invalid_param = true;
  460. break;
  461. }
  462. params.grammar = argv[i];
  463. } else if (arg == "--grammar-file") {
  464. if (++i >= argc) {
  465. invalid_param = true;
  466. break;
  467. }
  468. std::ifstream file(argv[i]);
  469. if (!file) {
  470. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  471. invalid_param = true;
  472. break;
  473. }
  474. std::copy(
  475. std::istreambuf_iterator<char>(file),
  476. std::istreambuf_iterator<char>(),
  477. std::back_inserter(params.grammar)
  478. );
  479. } else {
  480. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  481. gpt_print_usage(argc, argv, default_params);
  482. exit(1);
  483. }
  484. }
  485. if (invalid_param) {
  486. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  487. gpt_print_usage(argc, argv, default_params);
  488. exit(1);
  489. }
  490. if (params.prompt_cache_all &&
  491. (params.interactive || params.interactive_first ||
  492. params.instruct)) {
  493. fprintf(stderr, "error: --prompt-cache-all not supported in interactive mode yet\n");
  494. gpt_print_usage(argc, argv, default_params);
  495. exit(1);
  496. }
  497. if (escape_prompt) {
  498. process_escapes(params.prompt);
  499. process_escapes(params.input_prefix);
  500. process_escapes(params.input_suffix);
  501. }
  502. return true;
  503. }
  504. void gpt_print_usage(int /*argc*/, char ** argv, const gpt_params & params) {
  505. fprintf(stdout, "usage: %s [options]\n", argv[0]);
  506. fprintf(stdout, "\n");
  507. fprintf(stdout, "options:\n");
  508. fprintf(stdout, " -h, --help show this help message and exit\n");
  509. fprintf(stdout, " -i, --interactive run in interactive mode\n");
  510. fprintf(stdout, " --interactive-first run in interactive mode and wait for input right away\n");
  511. fprintf(stdout, " -ins, --instruct run in instruction mode (use with Alpaca models)\n");
  512. fprintf(stdout, " --multiline-input allows you to write or paste multiple lines without ending each in '\\'\n");
  513. fprintf(stdout, " -r PROMPT, --reverse-prompt PROMPT\n");
  514. fprintf(stdout, " halt generation at PROMPT, return control in interactive mode\n");
  515. fprintf(stdout, " (can be specified more than once for multiple prompts).\n");
  516. fprintf(stdout, " --color colorise output to distinguish prompt and user input from generations\n");
  517. fprintf(stdout, " -s SEED, --seed SEED RNG seed (default: -1, use random seed for < 0)\n");
  518. fprintf(stdout, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
  519. fprintf(stdout, " -p PROMPT, --prompt PROMPT\n");
  520. fprintf(stdout, " prompt to start generation with (default: empty)\n");
  521. fprintf(stdout, " -e process prompt escapes sequences (\\n, \\r, \\t, \\', \\\", \\\\)\n");
  522. fprintf(stdout, " --prompt-cache FNAME file to cache prompt state for faster startup (default: none)\n");
  523. fprintf(stdout, " --prompt-cache-all if specified, saves user input and generations to cache as well.\n");
  524. fprintf(stdout, " not supported with --interactive or other interactive options\n");
  525. fprintf(stdout, " --prompt-cache-ro if specified, uses the prompt cache but does not update it.\n");
  526. fprintf(stdout, " --random-prompt start with a randomized prompt.\n");
  527. fprintf(stdout, " --in-prefix-bos prefix BOS to user inputs, preceding the `--in-prefix` string\n");
  528. fprintf(stdout, " --in-prefix STRING string to prefix user inputs with (default: empty)\n");
  529. fprintf(stdout, " --in-suffix STRING string to suffix after user inputs with (default: empty)\n");
  530. fprintf(stdout, " -f FNAME, --file FNAME\n");
  531. fprintf(stdout, " prompt file to start generation.\n");
  532. fprintf(stdout, " -n N, --n-predict N number of tokens to predict (default: %d, -1 = infinity, -2 = until context filled)\n", params.n_predict);
  533. fprintf(stdout, " -c N, --ctx-size N size of the prompt context (default: %d)\n", params.n_ctx);
  534. fprintf(stdout, " -b N, --batch-size N batch size for prompt processing (default: %d)\n", params.n_batch);
  535. fprintf(stdout, " --top-k N top-k sampling (default: %d, 0 = disabled)\n", params.top_k);
  536. fprintf(stdout, " --top-p N top-p sampling (default: %.1f, 1.0 = disabled)\n", (double)params.top_p);
  537. fprintf(stdout, " --tfs N tail free sampling, parameter z (default: %.1f, 1.0 = disabled)\n", (double)params.tfs_z);
  538. fprintf(stdout, " --typical N locally typical sampling, parameter p (default: %.1f, 1.0 = disabled)\n", (double)params.typical_p);
  539. 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);
  540. fprintf(stdout, " --repeat-penalty N penalize repeat sequence of tokens (default: %.1f, 1.0 = disabled)\n", (double)params.repeat_penalty);
  541. fprintf(stdout, " --presence-penalty N repeat alpha presence penalty (default: %.1f, 0.0 = disabled)\n", (double)params.presence_penalty);
  542. fprintf(stdout, " --frequency-penalty N repeat alpha frequency penalty (default: %.1f, 0.0 = disabled)\n", (double)params.frequency_penalty);
  543. fprintf(stdout, " --mirostat N use Mirostat sampling.\n");
  544. fprintf(stdout, " Top K, Nucleus, Tail Free and Locally Typical samplers are ignored if used.\n");
  545. fprintf(stdout, " (default: %d, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)\n", params.mirostat);
  546. fprintf(stdout, " --mirostat-lr N Mirostat learning rate, parameter eta (default: %.1f)\n", (double)params.mirostat_eta);
  547. fprintf(stdout, " --mirostat-ent N Mirostat target entropy, parameter tau (default: %.1f)\n", (double)params.mirostat_tau);
  548. fprintf(stdout, " -l TOKEN_ID(+/-)BIAS, --logit-bias TOKEN_ID(+/-)BIAS\n");
  549. fprintf(stdout, " modifies the likelihood of token appearing in the completion,\n");
  550. fprintf(stdout, " i.e. `--logit-bias 15043+1` to increase likelihood of token ' Hello',\n");
  551. fprintf(stdout, " or `--logit-bias 15043-1` to decrease likelihood of token ' Hello'\n");
  552. fprintf(stdout, " --grammar GRAMMAR BNF-like grammar to constrain generations (see samples in grammars/ dir)\n");
  553. fprintf(stdout, " --grammar-file FNAME file to read grammar from\n");
  554. fprintf(stdout, " --cfg-negative-prompt PROMPT\n");
  555. fprintf(stdout, " negative prompt to use for guidance. (default: empty)\n");
  556. fprintf(stdout, " --cfg-negative-prompt-file FNAME\n");
  557. fprintf(stdout, " negative prompt file to use for guidance. (default: empty)\n");
  558. fprintf(stdout, " --cfg-scale N strength of guidance (default: %f, 1.0 = disable)\n", params.cfg_scale);
  559. fprintf(stdout, " --rope-scale N RoPE context linear scaling factor, inverse of --rope-freq-scale (default: %g)\n", 1.0f/params.rope_freq_scale);
  560. fprintf(stdout, " --rope-freq-base N RoPE base frequency, used by NTK-aware scaling (default: %.1f)\n", params.rope_freq_base);
  561. fprintf(stdout, " --rope-freq-scale N RoPE frequency linear scaling factor, inverse of --rope-scale (default: %g)\n", params.rope_freq_scale);
  562. fprintf(stdout, " --ignore-eos ignore end of stream token and continue generating (implies --logit-bias 2-inf)\n");
  563. fprintf(stdout, " --no-penalize-nl do not penalize newline token\n");
  564. fprintf(stdout, " --memory-f32 use f32 instead of f16 for memory key+value (default: disabled)\n");
  565. fprintf(stdout, " not recommended: doubles context memory required and no measurable increase in quality\n");
  566. fprintf(stdout, " --temp N temperature (default: %.1f)\n", (double)params.temp);
  567. fprintf(stdout, " --perplexity compute perplexity over each ctx window of the prompt\n");
  568. fprintf(stdout, " --hellaswag compute HellaSwag score over random tasks from datafile supplied with -f\n");
  569. fprintf(stdout, " --hellaswag-tasks N number of tasks to use when computing the HellaSwag score (default: %zu)\n", params.hellaswag_tasks);
  570. fprintf(stdout, " --keep N number of tokens to keep from the initial prompt (default: %d, -1 = all)\n", params.n_keep);
  571. fprintf(stdout, " --chunks N max number of chunks to process (default: %d, -1 = all)\n", params.n_chunks);
  572. if (llama_mlock_supported()) {
  573. fprintf(stdout, " --mlock force system to keep model in RAM rather than swapping or compressing\n");
  574. }
  575. if (llama_mmap_supported()) {
  576. fprintf(stdout, " --no-mmap do not memory-map model (slower load but may reduce pageouts if not using mlock)\n");
  577. }
  578. fprintf(stdout, " --numa attempt optimizations that help on some NUMA systems\n");
  579. fprintf(stdout, " if run without this previously, it is recommended to drop the system page cache before using this\n");
  580. fprintf(stdout, " see https://github.com/ggerganov/llama.cpp/issues/1437\n");
  581. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  582. fprintf(stdout, " -ngl N, --n-gpu-layers N\n");
  583. fprintf(stdout, " number of layers to store in VRAM\n");
  584. fprintf(stdout, " -ts SPLIT --tensor-split SPLIT\n");
  585. fprintf(stdout, " how to split tensors across multiple GPUs, comma-separated list of proportions, e.g. 3,1\n");
  586. fprintf(stdout, " -mg i, --main-gpu i the GPU to use for scratch and small tensors\n");
  587. fprintf(stdout, " -lv, --low-vram don't allocate VRAM scratch buffer\n");
  588. fprintf(stdout, " -nommq, --no-mul-mat-q\n");
  589. fprintf(stdout, " use cuBLAS instead of custom mul_mat_q CUDA kernels.\n");
  590. fprintf(stdout, " Not recommended since this is both slower and uses more VRAM.\n");
  591. #endif
  592. fprintf(stdout, " --mtest compute maximum memory usage\n");
  593. fprintf(stdout, " --export export the computation graph to 'llama.ggml'\n");
  594. fprintf(stdout, " --verbose-prompt print prompt before generation\n");
  595. fprintf(stderr, " --simple-io use basic IO for better compatibility in subprocesses and limited consoles\n");
  596. fprintf(stdout, " --lora FNAME apply LoRA adapter (implies --no-mmap)\n");
  597. fprintf(stdout, " --lora-base FNAME optional model to use as a base for the layers modified by the LoRA adapter\n");
  598. fprintf(stdout, " -m FNAME, --model FNAME\n");
  599. fprintf(stdout, " model path (default: %s)\n", params.model.c_str());
  600. fprintf(stdout, "\n");
  601. }
  602. std::string gpt_random_prompt(std::mt19937 & rng) {
  603. const int r = rng() % 10;
  604. switch (r) {
  605. case 0: return "So";
  606. case 1: return "Once upon a time";
  607. case 2: return "When";
  608. case 3: return "The";
  609. case 4: return "After";
  610. case 5: return "If";
  611. case 6: return "import";
  612. case 7: return "He";
  613. case 8: return "She";
  614. case 9: return "They";
  615. default: return "To";
  616. }
  617. return "The";
  618. }
  619. //
  620. // Model utils
  621. //
  622. struct llama_context_params llama_context_params_from_gpt_params(const gpt_params & params) {
  623. auto lparams = llama_context_default_params();
  624. lparams.n_ctx = params.n_ctx;
  625. lparams.n_batch = params.n_batch;
  626. lparams.n_gpu_layers = params.n_gpu_layers;
  627. lparams.main_gpu = params.main_gpu;
  628. lparams.tensor_split = params.tensor_split;
  629. lparams.low_vram = params.low_vram;
  630. lparams.mul_mat_q = params.mul_mat_q;
  631. lparams.seed = params.seed;
  632. lparams.f16_kv = params.memory_f16;
  633. lparams.use_mmap = params.use_mmap;
  634. lparams.use_mlock = params.use_mlock;
  635. lparams.logits_all = params.perplexity;
  636. lparams.embedding = params.embedding;
  637. lparams.rope_freq_base = params.rope_freq_base;
  638. lparams.rope_freq_scale = params.rope_freq_scale;
  639. return lparams;
  640. }
  641. std::tuple<struct llama_model *, struct llama_context *> llama_init_from_gpt_params(gpt_params & params) {
  642. auto lparams = llama_context_params_from_gpt_params(params);
  643. llama_model * model = llama_load_model_from_file(params.model.c_str(), lparams);
  644. if (model == NULL) {
  645. fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, params.model.c_str());
  646. return std::make_tuple(nullptr, nullptr);
  647. }
  648. llama_context * lctx = llama_new_context_with_model(model, lparams);
  649. if (lctx == NULL) {
  650. fprintf(stderr, "%s: error: failed to create context with model '%s'\n", __func__, params.model.c_str());
  651. llama_free_model(model);
  652. return std::make_tuple(nullptr, nullptr);
  653. }
  654. if (!params.lora_adapter.empty()) {
  655. int err = llama_model_apply_lora_from_file(model,
  656. params.lora_adapter.c_str(),
  657. params.lora_base.empty() ? NULL : params.lora_base.c_str(),
  658. params.n_threads);
  659. if (err != 0) {
  660. fprintf(stderr, "%s: error: failed to apply lora adapter\n", __func__);
  661. llama_free(lctx);
  662. llama_free_model(model);
  663. return std::make_tuple(nullptr, nullptr);
  664. }
  665. }
  666. if (params.ignore_eos) {
  667. params.logit_bias[llama_token_eos(lctx)] = -INFINITY;
  668. }
  669. return std::make_tuple(model, lctx);
  670. }
  671. //
  672. // Vocab utils
  673. //
  674. std::vector<llama_token> llama_tokenize(
  675. struct llama_context * ctx,
  676. const std::string & text,
  677. bool add_bos) {
  678. // upper limit for the number of tokens
  679. int n_tokens = text.length() + add_bos;
  680. std::vector<llama_token> result(n_tokens);
  681. n_tokens = llama_tokenize(ctx, text.c_str(), result.data(), result.size(), add_bos);
  682. if (n_tokens < 0) {
  683. result.resize(-n_tokens);
  684. int check = llama_tokenize(ctx, text.c_str(), result.data(), result.size(), add_bos);
  685. GGML_ASSERT(check == -n_tokens);
  686. } else {
  687. result.resize(n_tokens);
  688. }
  689. return result;
  690. }
  691. std::string llama_token_to_str(const struct llama_context * ctx, llama_token token) {
  692. std::vector<char> result(8, 0);
  693. const int n_tokens = llama_token_to_str(ctx, token, result.data(), result.size());
  694. if (n_tokens < 0) {
  695. result.resize(-n_tokens);
  696. int check = llama_token_to_str(ctx, token, result.data(), result.size());
  697. GGML_ASSERT(check == -n_tokens);
  698. } else {
  699. result.resize(n_tokens);
  700. }
  701. return std::string(result.data(), result.size());
  702. }
  703. std::vector<llama_token> llama_tokenize_bpe(
  704. struct llama_context * ctx,
  705. const std::string & text,
  706. bool add_bos) {
  707. int n_tokens = text.length() + add_bos;
  708. std::vector<llama_token> result(n_tokens);
  709. n_tokens = llama_tokenize_bpe(ctx, text.c_str(), result.data(), result.size(), add_bos);
  710. if (n_tokens < 0) {
  711. result.resize(-n_tokens);
  712. int check = llama_tokenize_bpe(ctx, text.c_str(), result.data(), result.size(), add_bos);
  713. GGML_ASSERT(check == -n_tokens);
  714. } else {
  715. result.resize(n_tokens);
  716. }
  717. return result;
  718. }
  719. std::string llama_token_to_str_bpe(const struct llama_context * ctx, llama_token token) {
  720. std::vector<char> result(8, 0);
  721. const int n_tokens = llama_token_to_str_bpe(ctx, token, result.data(), result.size());
  722. if (n_tokens < 0) {
  723. result.resize(-n_tokens);
  724. const int check = llama_token_to_str_bpe(ctx, token, result.data(), result.size());
  725. GGML_ASSERT(check == -n_tokens);
  726. } else {
  727. result.resize(n_tokens);
  728. }
  729. return std::string(result.data(), result.size());
  730. }