1
0

common.cpp 30 KB

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