common.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  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 == "-gqa" || arg == "--gqa") {
  163. if (++i >= argc) {
  164. invalid_param = true;
  165. break;
  166. }
  167. params.n_gqa = std::stoi(argv[i]);
  168. } else if (arg == "-eps" || arg == "--rms-norm-eps") {
  169. if (++i >= argc) {
  170. invalid_param = true;
  171. break;
  172. }
  173. params.rms_norm_eps = std::stof(argv[i]);
  174. } else if (arg == "--rope-freq-base") {
  175. if (++i >= argc) {
  176. invalid_param = true;
  177. break;
  178. }
  179. params.rope_freq_base = std::stof(argv[i]);
  180. } else if (arg == "--rope-freq-scale") {
  181. if (++i >= argc) {
  182. invalid_param = true;
  183. break;
  184. }
  185. params.rope_freq_scale = std::stof(argv[i]);
  186. } else if (arg == "--rope-scale") {
  187. if (++i >= argc) {
  188. invalid_param = true;
  189. break;
  190. }
  191. params.rope_freq_scale = 1.0f/std::stof(argv[i]);
  192. } else if (arg == "--memory-f32") {
  193. params.memory_f16 = false;
  194. } else if (arg == "--top-p") {
  195. if (++i >= argc) {
  196. invalid_param = true;
  197. break;
  198. }
  199. params.top_p = std::stof(argv[i]);
  200. } else if (arg == "--temp") {
  201. if (++i >= argc) {
  202. invalid_param = true;
  203. break;
  204. }
  205. params.temp = std::stof(argv[i]);
  206. } else if (arg == "--tfs") {
  207. if (++i >= argc) {
  208. invalid_param = true;
  209. break;
  210. }
  211. params.tfs_z = std::stof(argv[i]);
  212. } else if (arg == "--typical") {
  213. if (++i >= argc) {
  214. invalid_param = true;
  215. break;
  216. }
  217. params.typical_p = std::stof(argv[i]);
  218. } else if (arg == "--repeat-last-n") {
  219. if (++i >= argc) {
  220. invalid_param = true;
  221. break;
  222. }
  223. params.repeat_last_n = std::stoi(argv[i]);
  224. } else if (arg == "--repeat-penalty") {
  225. if (++i >= argc) {
  226. invalid_param = true;
  227. break;
  228. }
  229. params.repeat_penalty = std::stof(argv[i]);
  230. } else if (arg == "--frequency-penalty") {
  231. if (++i >= argc) {
  232. invalid_param = true;
  233. break;
  234. }
  235. params.frequency_penalty = std::stof(argv[i]);
  236. } else if (arg == "--presence-penalty") {
  237. if (++i >= argc) {
  238. invalid_param = true;
  239. break;
  240. }
  241. params.presence_penalty = std::stof(argv[i]);
  242. } else if (arg == "--mirostat") {
  243. if (++i >= argc) {
  244. invalid_param = true;
  245. break;
  246. }
  247. params.mirostat = std::stoi(argv[i]);
  248. } else if (arg == "--mirostat-lr") {
  249. if (++i >= argc) {
  250. invalid_param = true;
  251. break;
  252. }
  253. params.mirostat_eta = std::stof(argv[i]);
  254. } else if (arg == "--mirostat-ent") {
  255. if (++i >= argc) {
  256. invalid_param = true;
  257. break;
  258. }
  259. params.mirostat_tau = std::stof(argv[i]);
  260. } else if (arg == "--cfg-negative-prompt") {
  261. if (++i >= argc) {
  262. invalid_param = true;
  263. break;
  264. }
  265. params.cfg_negative_prompt = argv[i];
  266. } else if (arg == "--cfg-scale") {
  267. if (++i >= argc) {
  268. invalid_param = true;
  269. break;
  270. }
  271. params.cfg_scale = std::stof(argv[i]);
  272. } else if (arg == "-b" || arg == "--batch-size") {
  273. if (++i >= argc) {
  274. invalid_param = true;
  275. break;
  276. }
  277. params.n_batch = std::stoi(argv[i]);
  278. params.n_batch = std::min(512, params.n_batch);
  279. } else if (arg == "--keep") {
  280. if (++i >= argc) {
  281. invalid_param = true;
  282. break;
  283. }
  284. params.n_keep = std::stoi(argv[i]);
  285. } else if (arg == "--chunks") {
  286. if (++i >= argc) {
  287. invalid_param = true;
  288. break;
  289. }
  290. params.n_chunks = std::stoi(argv[i]);
  291. } else if (arg == "-m" || arg == "--model") {
  292. if (++i >= argc) {
  293. invalid_param = true;
  294. break;
  295. }
  296. params.model = argv[i];
  297. } else if (arg == "-a" || arg == "--alias") {
  298. if (++i >= argc) {
  299. invalid_param = true;
  300. break;
  301. }
  302. params.model_alias = argv[i];
  303. } else if (arg == "--lora") {
  304. if (++i >= argc) {
  305. invalid_param = true;
  306. break;
  307. }
  308. params.lora_adapter = argv[i];
  309. params.use_mmap = false;
  310. } else if (arg == "--lora-base") {
  311. if (++i >= argc) {
  312. invalid_param = true;
  313. break;
  314. }
  315. params.lora_base = argv[i];
  316. } else if (arg == "-i" || arg == "--interactive") {
  317. params.interactive = true;
  318. } else if (arg == "--embedding") {
  319. params.embedding = true;
  320. } else if (arg == "--interactive-first") {
  321. params.interactive_first = true;
  322. } else if (arg == "-ins" || arg == "--instruct") {
  323. params.instruct = true;
  324. } else if (arg == "--multiline-input") {
  325. params.multiline_input = true;
  326. } else if (arg == "--simple-io") {
  327. params.simple_io = true;
  328. } else if (arg == "--color") {
  329. params.use_color = true;
  330. } else if (arg == "--mlock") {
  331. params.use_mlock = true;
  332. } else if (arg == "--gpu-layers" || arg == "-ngl" || arg == "--n-gpu-layers") {
  333. if (++i >= argc) {
  334. invalid_param = true;
  335. break;
  336. }
  337. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  338. params.n_gpu_layers = std::stoi(argv[i]);
  339. #else
  340. fprintf(stderr, "warning: not compiled with GPU offload support, --n-gpu-layers option will be ignored\n");
  341. fprintf(stderr, "warning: see main README.md for information on enabling GPU BLAS support\n");
  342. #endif
  343. } else if (arg == "--main-gpu" || arg == "-mg") {
  344. if (++i >= argc) {
  345. invalid_param = true;
  346. break;
  347. }
  348. #ifdef GGML_USE_CUBLAS
  349. params.main_gpu = std::stoi(argv[i]);
  350. #else
  351. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set a main GPU.\n");
  352. #endif
  353. } else if (arg == "--tensor-split" || arg == "-ts") {
  354. if (++i >= argc) {
  355. invalid_param = true;
  356. break;
  357. }
  358. #ifdef GGML_USE_CUBLAS
  359. std::string arg_next = argv[i];
  360. // split string by , and /
  361. const std::regex regex{R"([,/]+)"};
  362. std::sregex_token_iterator it{arg_next.begin(), arg_next.end(), regex, -1};
  363. std::vector<std::string> split_arg{it, {}};
  364. GGML_ASSERT(split_arg.size() <= LLAMA_MAX_DEVICES);
  365. for (size_t i = 0; i < LLAMA_MAX_DEVICES; ++i) {
  366. if (i < split_arg.size()) {
  367. params.tensor_split[i] = std::stof(split_arg[i]);
  368. } else {
  369. params.tensor_split[i] = 0.0f;
  370. }
  371. }
  372. #else
  373. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set a tensor split.\n");
  374. #endif // GGML_USE_CUBLAS
  375. } else if (arg == "--mul-mat-q" || arg == "-mmq") {
  376. #ifdef GGML_USE_CUBLAS
  377. params.mul_mat_q = true;
  378. #else
  379. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to use mul_mat_q kernels.\n");
  380. #endif // GGML_USE_CUBLAS
  381. } else if (arg == "--low-vram" || arg == "-lv") {
  382. #ifdef GGML_USE_CUBLAS
  383. params.low_vram = true;
  384. #else
  385. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set lower vram usage.\n");
  386. #endif // GGML_USE_CUBLAS
  387. } else if (arg == "--no-mmap") {
  388. params.use_mmap = false;
  389. } else if (arg == "--mtest") {
  390. params.mem_test = true;
  391. } else if (arg == "--numa") {
  392. params.numa = true;
  393. } else if (arg == "--export") {
  394. params.export_cgraph = true;
  395. } else if (arg == "--verbose-prompt") {
  396. params.verbose_prompt = true;
  397. } else if (arg == "-r" || arg == "--reverse-prompt") {
  398. if (++i >= argc) {
  399. invalid_param = true;
  400. break;
  401. }
  402. params.antiprompt.push_back(argv[i]);
  403. } else if (arg == "--perplexity") {
  404. params.perplexity = true;
  405. } else if (arg == "--hellaswag") {
  406. params.hellaswag = true;
  407. } else if (arg == "--hellaswag-tasks") {
  408. if (++i >= argc) {
  409. invalid_param = true;
  410. break;
  411. }
  412. params.hellaswag_tasks = std::stoi(argv[i]);
  413. } else if (arg == "--ignore-eos") {
  414. params.logit_bias[llama_token_eos()] = -INFINITY;
  415. } else if (arg == "--no-penalize-nl") {
  416. params.penalize_nl = false;
  417. } else if (arg == "-l" || arg == "--logit-bias") {
  418. if (++i >= argc) {
  419. invalid_param = true;
  420. break;
  421. }
  422. std::stringstream ss(argv[i]);
  423. llama_token key;
  424. char sign;
  425. std::string value_str;
  426. try {
  427. if (ss >> key && ss >> sign && std::getline(ss, value_str) && (sign == '+' || sign == '-')) {
  428. params.logit_bias[key] = std::stof(value_str) * ((sign == '-') ? -1.0f : 1.0f);
  429. } else {
  430. throw std::exception();
  431. }
  432. } catch (const std::exception&) {
  433. invalid_param = true;
  434. break;
  435. }
  436. } else if (arg == "-h" || arg == "--help") {
  437. gpt_print_usage(argc, argv, default_params);
  438. exit(0);
  439. } else if (arg == "--random-prompt") {
  440. params.random_prompt = true;
  441. } else if (arg == "--in-prefix-bos") {
  442. params.input_prefix_bos = true;
  443. } else if (arg == "--in-prefix") {
  444. if (++i >= argc) {
  445. invalid_param = true;
  446. break;
  447. }
  448. params.input_prefix = argv[i];
  449. } else if (arg == "--in-suffix") {
  450. if (++i >= argc) {
  451. invalid_param = true;
  452. break;
  453. }
  454. params.input_suffix = argv[i];
  455. } else if (arg == "--grammar") {
  456. if (++i >= argc) {
  457. invalid_param = true;
  458. break;
  459. }
  460. params.grammar = argv[i];
  461. } else if (arg == "--grammar-file") {
  462. if (++i >= argc) {
  463. invalid_param = true;
  464. break;
  465. }
  466. std::ifstream file(argv[i]);
  467. if (!file) {
  468. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  469. invalid_param = true;
  470. break;
  471. }
  472. std::copy(
  473. std::istreambuf_iterator<char>(file),
  474. std::istreambuf_iterator<char>(),
  475. std::back_inserter(params.grammar)
  476. );
  477. } else {
  478. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  479. gpt_print_usage(argc, argv, default_params);
  480. exit(1);
  481. }
  482. }
  483. if (invalid_param) {
  484. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  485. gpt_print_usage(argc, argv, default_params);
  486. exit(1);
  487. }
  488. if (params.prompt_cache_all &&
  489. (params.interactive || params.interactive_first ||
  490. params.instruct)) {
  491. fprintf(stderr, "error: --prompt-cache-all not supported in interactive mode yet\n");
  492. gpt_print_usage(argc, argv, default_params);
  493. exit(1);
  494. }
  495. if (escape_prompt) {
  496. process_escapes(params.prompt);
  497. process_escapes(params.input_prefix);
  498. process_escapes(params.input_suffix);
  499. }
  500. return true;
  501. }
  502. void gpt_print_usage(int /*argc*/, char ** argv, const gpt_params & params) {
  503. fprintf(stdout, "usage: %s [options]\n", argv[0]);
  504. fprintf(stdout, "\n");
  505. fprintf(stdout, "options:\n");
  506. fprintf(stdout, " -h, --help show this help message and exit\n");
  507. fprintf(stdout, " -i, --interactive run in interactive mode\n");
  508. fprintf(stdout, " --interactive-first run in interactive mode and wait for input right away\n");
  509. fprintf(stdout, " -ins, --instruct run in instruction mode (use with Alpaca models)\n");
  510. fprintf(stdout, " --multiline-input allows you to write or paste multiple lines without ending each in '\\'\n");
  511. fprintf(stdout, " -r PROMPT, --reverse-prompt PROMPT\n");
  512. fprintf(stdout, " halt generation at PROMPT, return control in interactive mode\n");
  513. fprintf(stdout, " (can be specified more than once for multiple prompts).\n");
  514. fprintf(stdout, " --color colorise output to distinguish prompt and user input from generations\n");
  515. fprintf(stdout, " -s SEED, --seed SEED RNG seed (default: -1, use random seed for < 0)\n");
  516. fprintf(stdout, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
  517. fprintf(stdout, " -p PROMPT, --prompt PROMPT\n");
  518. fprintf(stdout, " prompt to start generation with (default: empty)\n");
  519. fprintf(stdout, " -e process prompt escapes sequences (\\n, \\r, \\t, \\', \\\", \\\\)\n");
  520. fprintf(stdout, " --prompt-cache FNAME file to cache prompt state for faster startup (default: none)\n");
  521. fprintf(stdout, " --prompt-cache-all if specified, saves user input and generations to cache as well.\n");
  522. fprintf(stdout, " not supported with --interactive or other interactive options\n");
  523. fprintf(stdout, " --prompt-cache-ro if specified, uses the prompt cache but does not update it.\n");
  524. fprintf(stdout, " --random-prompt start with a randomized prompt.\n");
  525. fprintf(stdout, " --in-prefix-bos prefix BOS to user inputs, preceding the `--in-prefix` string\n");
  526. fprintf(stdout, " --in-prefix STRING string to prefix user inputs with (default: empty)\n");
  527. fprintf(stdout, " --in-suffix STRING string to suffix after user inputs with (default: empty)\n");
  528. fprintf(stdout, " -f FNAME, --file FNAME\n");
  529. fprintf(stdout, " prompt file to start generation.\n");
  530. fprintf(stdout, " -n N, --n-predict N number of tokens to predict (default: %d, -1 = infinity)\n", params.n_predict);
  531. fprintf(stdout, " -c N, --ctx-size N size of the prompt context (default: %d)\n", params.n_ctx);
  532. fprintf(stdout, " -b N, --batch-size N batch size for prompt processing (default: %d)\n", params.n_batch);
  533. fprintf(stdout, " -gqa N, --gqa N grouped-query attention factor (TEMP!!! use 8 for LLaMAv2 70B) (default: %d)\n", params.n_gqa);
  534. fprintf(stdout, " -eps N, --rms-norm-eps N rms norm eps (TEMP!!! use 1e-5 for LLaMAv2) (default: %.1e)\n", params.rms_norm_eps);
  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-scale N strength of guidance (default: %f, 1.0 = disable)\n", params.cfg_scale);
  557. fprintf(stdout, " --rope-scale N RoPE context linear scaling factor, inverse of --rope-freq-scale (default: %g)\n", 1.0f/params.rope_freq_scale);
  558. fprintf(stdout, " --rope-freq-base N RoPE base frequency, used by NTK-aware scaling (default: %.1f)\n", params.rope_freq_base);
  559. fprintf(stdout, " --rope-freq-scale N RoPE frequency linear scaling factor, inverse of --rope-scale (default: %g)\n", params.rope_freq_scale);
  560. fprintf(stdout, " --ignore-eos ignore end of stream token and continue generating (implies --logit-bias 2-inf)\n");
  561. fprintf(stdout, " --no-penalize-nl do not penalize newline token\n");
  562. fprintf(stdout, " --memory-f32 use f32 instead of f16 for memory key+value (default: disabled)\n");
  563. fprintf(stdout, " not recommended: doubles context memory required and no measurable increase in quality\n");
  564. fprintf(stdout, " --temp N temperature (default: %.1f)\n", (double)params.temp);
  565. fprintf(stdout, " --perplexity compute perplexity over each ctx window of the prompt\n");
  566. fprintf(stdout, " --hellaswag compute HellaSwag score over random tasks from datafile supplied with -f\n");
  567. fprintf(stdout, " --hellaswag-tasks N number of tasks to use when computing the HellaSwag score (default: %zu)\n", params.hellaswag_tasks);
  568. fprintf(stdout, " --keep N number of tokens to keep from the initial prompt (default: %d, -1 = all)\n", params.n_keep);
  569. fprintf(stdout, " --chunks N max number of chunks to process (default: %d, -1 = all)\n", params.n_chunks);
  570. if (llama_mlock_supported()) {
  571. fprintf(stdout, " --mlock force system to keep model in RAM rather than swapping or compressing\n");
  572. }
  573. if (llama_mmap_supported()) {
  574. fprintf(stdout, " --no-mmap do not memory-map model (slower load but may reduce pageouts if not using mlock)\n");
  575. }
  576. fprintf(stdout, " --numa attempt optimizations that help on some NUMA systems\n");
  577. fprintf(stdout, " if run without this previously, it is recommended to drop the system page cache before using this\n");
  578. fprintf(stdout, " see https://github.com/ggerganov/llama.cpp/issues/1437\n");
  579. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  580. fprintf(stdout, " -ngl N, --n-gpu-layers N\n");
  581. fprintf(stdout, " number of layers to store in VRAM\n");
  582. fprintf(stdout, " -ts SPLIT --tensor-split SPLIT\n");
  583. fprintf(stdout, " how to split tensors across multiple GPUs, comma-separated list of proportions, e.g. 3,1\n");
  584. fprintf(stdout, " -mg i, --main-gpu i the GPU to use for scratch and small tensors\n" );
  585. fprintf(stdout, " -lv, --low-vram don't allocate VRAM scratch buffer\n" );
  586. fprintf(stdout, " -mmq, --mul-mat-q use experimental mul_mat_q CUDA kernels instead of cuBLAS. TEMP!!!\n" );
  587. fprintf(stdout, " Reduces VRAM usage by 700/970/1430 MiB for 7b/13b/33b but prompt processing speed\n" );
  588. fprintf(stdout, " is still suboptimal, especially q2_K, q3_K, q5_K, and q6_K.\n" );
  589. #endif
  590. fprintf(stdout, " --mtest compute maximum memory usage\n");
  591. fprintf(stdout, " --export export the computation graph to 'llama.ggml'\n");
  592. fprintf(stdout, " --verbose-prompt print prompt before generation\n");
  593. fprintf(stderr, " --simple-io use basic IO for better compatibility in subprocesses and limited consoles\n");
  594. fprintf(stdout, " --lora FNAME apply LoRA adapter (implies --no-mmap)\n");
  595. fprintf(stdout, " --lora-base FNAME optional model to use as a base for the layers modified by the LoRA adapter\n");
  596. fprintf(stdout, " -m FNAME, --model FNAME\n");
  597. fprintf(stdout, " model path (default: %s)\n", params.model.c_str());
  598. fprintf(stdout, "\n");
  599. }
  600. std::string gpt_random_prompt(std::mt19937 & rng) {
  601. const int r = rng() % 10;
  602. switch (r) {
  603. case 0: return "So";
  604. case 1: return "Once upon a time";
  605. case 2: return "When";
  606. case 3: return "The";
  607. case 4: return "After";
  608. case 5: return "If";
  609. case 6: return "import";
  610. case 7: return "He";
  611. case 8: return "She";
  612. case 9: return "They";
  613. default: return "To";
  614. }
  615. return "The";
  616. }
  617. // TODO: not great allocating this every time
  618. std::vector<llama_token> llama_tokenize(struct llama_context * ctx, const std::string & text, bool add_bos) {
  619. // initialize to prompt numer of chars, since n_tokens <= n_prompt_chars
  620. std::vector<llama_token> res(text.size() + (int) add_bos);
  621. const int n = llama_tokenize(ctx, text.c_str(), res.data(), res.size(), add_bos);
  622. assert(n >= 0);
  623. res.resize(n);
  624. return res;
  625. }
  626. struct llama_context_params llama_context_params_from_gpt_params(const gpt_params & params) {
  627. auto lparams = llama_context_default_params();
  628. lparams.n_ctx = params.n_ctx;
  629. lparams.n_batch = params.n_batch;
  630. lparams.n_gqa = params.n_gqa;
  631. lparams.rms_norm_eps = params.rms_norm_eps;
  632. lparams.n_gpu_layers = params.n_gpu_layers;
  633. lparams.main_gpu = params.main_gpu;
  634. lparams.tensor_split = params.tensor_split;
  635. lparams.low_vram = params.low_vram;
  636. lparams.mul_mat_q = params.mul_mat_q;
  637. lparams.seed = params.seed;
  638. lparams.f16_kv = params.memory_f16;
  639. lparams.use_mmap = params.use_mmap;
  640. lparams.use_mlock = params.use_mlock;
  641. lparams.logits_all = params.perplexity;
  642. lparams.embedding = params.embedding;
  643. lparams.rope_freq_base = params.rope_freq_base;
  644. lparams.rope_freq_scale = params.rope_freq_scale;
  645. return lparams;
  646. }
  647. std::tuple<struct llama_model *, struct llama_context *> llama_init_from_gpt_params(const gpt_params & params) {
  648. auto lparams = llama_context_params_from_gpt_params(params);
  649. llama_model * model = llama_load_model_from_file(params.model.c_str(), lparams);
  650. if (model == NULL) {
  651. fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, params.model.c_str());
  652. return std::make_tuple(nullptr, nullptr);
  653. }
  654. llama_context * lctx = llama_new_context_with_model(model, lparams);
  655. if (lctx == NULL) {
  656. fprintf(stderr, "%s: error: failed to create context with model '%s'\n", __func__, params.model.c_str());
  657. llama_free_model(model);
  658. return std::make_tuple(nullptr, nullptr);
  659. }
  660. if (!params.lora_adapter.empty()) {
  661. int err = llama_model_apply_lora_from_file(model,
  662. params.lora_adapter.c_str(),
  663. params.lora_base.empty() ? NULL : params.lora_base.c_str(),
  664. params.n_threads);
  665. if (err != 0) {
  666. fprintf(stderr, "%s: error: failed to apply lora adapter\n", __func__);
  667. llama_free(lctx);
  668. llama_free_model(model);
  669. return std::make_tuple(nullptr, nullptr);
  670. }
  671. }
  672. return std::make_tuple(model, lctx);
  673. }