common.cpp 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  1. #include "common.h"
  2. #include "build-info.h"
  3. #include "llama.h"
  4. #include <algorithm>
  5. #include <cassert>
  6. #include <cmath>
  7. #include <cstring>
  8. #include <ctime>
  9. #include <fstream>
  10. #include <iterator>
  11. #include <iostream>
  12. #include <regex>
  13. #include <sstream>
  14. #include <string>
  15. #include <unordered_set>
  16. #include <vector>
  17. #include <cinttypes>
  18. #if defined(__APPLE__) && defined(__MACH__)
  19. #include <sys/types.h>
  20. #include <sys/sysctl.h>
  21. #endif
  22. #if defined(_WIN32)
  23. #define WIN32_LEAN_AND_MEAN
  24. #ifndef NOMINMAX
  25. # define NOMINMAX
  26. #endif
  27. #include <codecvt>
  28. #include <locale>
  29. #include <windows.h>
  30. #include <fcntl.h>
  31. #include <io.h>
  32. #else
  33. #include <sys/ioctl.h>
  34. #include <sys/stat.h>
  35. #include <unistd.h>
  36. #endif
  37. #if defined(_MSC_VER)
  38. #pragma warning(disable: 4244 4267) // possible loss of data
  39. #endif
  40. int32_t get_num_physical_cores() {
  41. #ifdef __linux__
  42. // enumerate the set of thread siblings, num entries is num cores
  43. std::unordered_set<std::string> siblings;
  44. for (uint32_t cpu=0; cpu < UINT32_MAX; ++cpu) {
  45. std::ifstream thread_siblings("/sys/devices/system/cpu"
  46. + std::to_string(cpu) + "/topology/thread_siblings");
  47. if (!thread_siblings.is_open()) {
  48. break; // no more cpus
  49. }
  50. std::string line;
  51. if (std::getline(thread_siblings, line)) {
  52. siblings.insert(line);
  53. }
  54. }
  55. if (!siblings.empty()) {
  56. return static_cast<int32_t>(siblings.size());
  57. }
  58. #elif defined(__APPLE__) && defined(__MACH__)
  59. int32_t num_physical_cores;
  60. size_t len = sizeof(num_physical_cores);
  61. int result = sysctlbyname("hw.perflevel0.physicalcpu", &num_physical_cores, &len, NULL, 0);
  62. if (result == 0) {
  63. return num_physical_cores;
  64. }
  65. result = sysctlbyname("hw.physicalcpu", &num_physical_cores, &len, NULL, 0);
  66. if (result == 0) {
  67. return num_physical_cores;
  68. }
  69. #elif defined(_WIN32)
  70. //TODO: Implement
  71. #endif
  72. unsigned int n_threads = std::thread::hardware_concurrency();
  73. return n_threads > 0 ? (n_threads <= 4 ? n_threads : n_threads / 2) : 4;
  74. }
  75. void process_escapes(std::string& input) {
  76. std::size_t input_len = input.length();
  77. std::size_t output_idx = 0;
  78. for (std::size_t input_idx = 0; input_idx < input_len; ++input_idx) {
  79. if (input[input_idx] == '\\' && input_idx + 1 < input_len) {
  80. switch (input[++input_idx]) {
  81. case 'n': input[output_idx++] = '\n'; break;
  82. case 'r': input[output_idx++] = '\r'; break;
  83. case 't': input[output_idx++] = '\t'; break;
  84. case '\'': input[output_idx++] = '\''; break;
  85. case '\"': input[output_idx++] = '\"'; break;
  86. case '\\': input[output_idx++] = '\\'; break;
  87. default: input[output_idx++] = '\\';
  88. input[output_idx++] = input[input_idx]; break;
  89. }
  90. } else {
  91. input[output_idx++] = input[input_idx];
  92. }
  93. }
  94. input.resize(output_idx);
  95. }
  96. bool gpt_params_parse(int argc, char ** argv, gpt_params & params) {
  97. bool result = true;
  98. try {
  99. if (!gpt_params_parse_ex(argc, argv, params)) {
  100. gpt_print_usage(argc, argv, gpt_params());
  101. exit(0);
  102. }
  103. }
  104. catch (const std::invalid_argument & ex) {
  105. fprintf(stderr, "%s\n", ex.what());
  106. gpt_print_usage(argc, argv, gpt_params());
  107. exit(1);
  108. }
  109. return result;
  110. }
  111. bool gpt_params_parse_ex(int argc, char ** argv, gpt_params & params) {
  112. bool invalid_param = false;
  113. std::string arg;
  114. const std::string arg_prefix = "--";
  115. llama_sampling_params & sparams = params.sparams;
  116. for (int i = 1; i < argc; i++) {
  117. arg = argv[i];
  118. if (arg.compare(0, arg_prefix.size(), arg_prefix) == 0) {
  119. std::replace(arg.begin(), arg.end(), '_', '-');
  120. }
  121. if (arg == "-s" || arg == "--seed") {
  122. if (++i >= argc) {
  123. invalid_param = true;
  124. break;
  125. }
  126. params.seed = std::stoul(argv[i]);
  127. } else if (arg == "-t" || arg == "--threads") {
  128. if (++i >= argc) {
  129. invalid_param = true;
  130. break;
  131. }
  132. params.n_threads = std::stoi(argv[i]);
  133. if (params.n_threads <= 0) {
  134. params.n_threads = std::thread::hardware_concurrency();
  135. }
  136. } else if (arg == "-tb" || arg == "--threads-batch") {
  137. if (++i >= argc) {
  138. invalid_param = true;
  139. break;
  140. }
  141. params.n_threads_batch = std::stoi(argv[i]);
  142. if (params.n_threads_batch <= 0) {
  143. params.n_threads_batch = std::thread::hardware_concurrency();
  144. }
  145. } else if (arg == "-p" || arg == "--prompt") {
  146. if (++i >= argc) {
  147. invalid_param = true;
  148. break;
  149. }
  150. params.prompt = argv[i];
  151. } else if (arg == "-e" || arg == "--escape") {
  152. params.escape = true;
  153. } else if (arg == "--prompt-cache") {
  154. if (++i >= argc) {
  155. invalid_param = true;
  156. break;
  157. }
  158. params.path_prompt_cache = argv[i];
  159. } else if (arg == "--prompt-cache-all") {
  160. params.prompt_cache_all = true;
  161. } else if (arg == "--prompt-cache-ro") {
  162. params.prompt_cache_ro = true;
  163. } else if (arg == "-f" || arg == "--file") {
  164. if (++i >= argc) {
  165. invalid_param = true;
  166. break;
  167. }
  168. std::ifstream file(argv[i]);
  169. if (!file) {
  170. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  171. invalid_param = true;
  172. break;
  173. }
  174. // store the external file name in params
  175. params.prompt_file = argv[i];
  176. std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(params.prompt));
  177. if (!params.prompt.empty() && params.prompt.back() == '\n') {
  178. params.prompt.pop_back();
  179. }
  180. } else if (arg == "-n" || arg == "--n-predict") {
  181. if (++i >= argc) {
  182. invalid_param = true;
  183. break;
  184. }
  185. params.n_predict = std::stoi(argv[i]);
  186. } else if (arg == "--top-k") {
  187. if (++i >= argc) {
  188. invalid_param = true;
  189. break;
  190. }
  191. sparams.top_k = std::stoi(argv[i]);
  192. } else if (arg == "-c" || arg == "--ctx-size") {
  193. if (++i >= argc) {
  194. invalid_param = true;
  195. break;
  196. }
  197. params.n_ctx = std::stoi(argv[i]);
  198. } else if (arg == "--rope-freq-base") {
  199. if (++i >= argc) {
  200. invalid_param = true;
  201. break;
  202. }
  203. params.rope_freq_base = std::stof(argv[i]);
  204. } else if (arg == "--rope-freq-scale") {
  205. if (++i >= argc) {
  206. invalid_param = true;
  207. break;
  208. }
  209. params.rope_freq_scale = std::stof(argv[i]);
  210. } else if (arg == "--rope-scale") {
  211. if (++i >= argc) {
  212. invalid_param = true;
  213. break;
  214. }
  215. params.rope_freq_scale = 1.0f/std::stof(argv[i]);
  216. } else if (arg == "--memory-f32") {
  217. params.memory_f16 = false;
  218. } else if (arg == "--top-p") {
  219. if (++i >= argc) {
  220. invalid_param = true;
  221. break;
  222. }
  223. sparams.top_p = std::stof(argv[i]);
  224. } else if (arg == "--min-p") {
  225. if (++i >= argc) {
  226. invalid_param = true;
  227. break;
  228. }
  229. sparams.min_p = std::stof(argv[i]);
  230. } else if (arg == "--temp") {
  231. if (++i >= argc) {
  232. invalid_param = true;
  233. break;
  234. }
  235. sparams.temp = std::stof(argv[i]);
  236. sparams.temp = std::max(sparams.temp, 0.0f);
  237. } else if (arg == "--tfs") {
  238. if (++i >= argc) {
  239. invalid_param = true;
  240. break;
  241. }
  242. sparams.tfs_z = std::stof(argv[i]);
  243. } else if (arg == "--typical") {
  244. if (++i >= argc) {
  245. invalid_param = true;
  246. break;
  247. }
  248. sparams.typical_p = std::stof(argv[i]);
  249. } else if (arg == "--repeat-last-n") {
  250. if (++i >= argc) {
  251. invalid_param = true;
  252. break;
  253. }
  254. sparams.penalty_last_n = std::stoi(argv[i]);
  255. sparams.n_prev = std::max(sparams.n_prev, sparams.penalty_last_n);
  256. } else if (arg == "--repeat-penalty") {
  257. if (++i >= argc) {
  258. invalid_param = true;
  259. break;
  260. }
  261. sparams.penalty_repeat = std::stof(argv[i]);
  262. } else if (arg == "--frequency-penalty") {
  263. if (++i >= argc) {
  264. invalid_param = true;
  265. break;
  266. }
  267. sparams.penalty_freq = std::stof(argv[i]);
  268. } else if (arg == "--presence-penalty") {
  269. if (++i >= argc) {
  270. invalid_param = true;
  271. break;
  272. }
  273. sparams.penalty_present = std::stof(argv[i]);
  274. } else if (arg == "--mirostat") {
  275. if (++i >= argc) {
  276. invalid_param = true;
  277. break;
  278. }
  279. sparams.mirostat = std::stoi(argv[i]);
  280. } else if (arg == "--mirostat-lr") {
  281. if (++i >= argc) {
  282. invalid_param = true;
  283. break;
  284. }
  285. sparams.mirostat_eta = std::stof(argv[i]);
  286. } else if (arg == "--mirostat-ent") {
  287. if (++i >= argc) {
  288. invalid_param = true;
  289. break;
  290. }
  291. sparams.mirostat_tau = std::stof(argv[i]);
  292. } else if (arg == "--cfg-negative-prompt") {
  293. if (++i >= argc) {
  294. invalid_param = true;
  295. break;
  296. }
  297. sparams.cfg_negative_prompt = argv[i];
  298. } else if (arg == "--cfg-negative-prompt-file") {
  299. if (++i >= argc) {
  300. invalid_param = true;
  301. break;
  302. }
  303. std::ifstream file(argv[i]);
  304. if (!file) {
  305. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  306. invalid_param = true;
  307. break;
  308. }
  309. std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(sparams.cfg_negative_prompt));
  310. if (!sparams.cfg_negative_prompt.empty() && sparams.cfg_negative_prompt.back() == '\n') {
  311. sparams.cfg_negative_prompt.pop_back();
  312. }
  313. } else if (arg == "--cfg-scale") {
  314. if (++i >= argc) {
  315. invalid_param = true;
  316. break;
  317. }
  318. sparams.cfg_scale = std::stof(argv[i]);
  319. } else if (arg == "-b" || arg == "--batch-size") {
  320. if (++i >= argc) {
  321. invalid_param = true;
  322. break;
  323. }
  324. params.n_batch = std::stoi(argv[i]);
  325. } else if (arg == "--keep") {
  326. if (++i >= argc) {
  327. invalid_param = true;
  328. break;
  329. }
  330. params.n_keep = std::stoi(argv[i]);
  331. } else if (arg == "--draft") {
  332. if (++i >= argc) {
  333. invalid_param = true;
  334. break;
  335. }
  336. params.n_draft = std::stoi(argv[i]);
  337. } else if (arg == "--chunks") {
  338. if (++i >= argc) {
  339. invalid_param = true;
  340. break;
  341. }
  342. params.n_chunks = std::stoi(argv[i]);
  343. } else if (arg == "-np" || arg == "--parallel") {
  344. if (++i >= argc) {
  345. invalid_param = true;
  346. break;
  347. }
  348. params.n_parallel = std::stoi(argv[i]);
  349. } else if (arg == "-ns" || arg == "--sequences") {
  350. if (++i >= argc) {
  351. invalid_param = true;
  352. break;
  353. }
  354. params.n_sequences = std::stoi(argv[i]);
  355. } else if (arg == "-m" || arg == "--model") {
  356. if (++i >= argc) {
  357. invalid_param = true;
  358. break;
  359. }
  360. params.model = argv[i];
  361. } else if (arg == "-md" || arg == "--model-draft") {
  362. if (++i >= argc) {
  363. invalid_param = true;
  364. break;
  365. }
  366. params.model_draft = argv[i];
  367. } else if (arg == "-a" || arg == "--alias") {
  368. if (++i >= argc) {
  369. invalid_param = true;
  370. break;
  371. }
  372. params.model_alias = argv[i];
  373. } else if (arg == "--lora") {
  374. if (++i >= argc) {
  375. invalid_param = true;
  376. break;
  377. }
  378. params.lora_adapter.push_back(std::make_tuple(argv[i], 1.0f));
  379. params.use_mmap = false;
  380. } else if (arg == "--lora-scaled") {
  381. if (++i >= argc) {
  382. invalid_param = true;
  383. break;
  384. }
  385. const char * lora_adapter = argv[i];
  386. if (++i >= argc) {
  387. invalid_param = true;
  388. break;
  389. }
  390. params.lora_adapter.push_back(std::make_tuple(lora_adapter, std::stof(argv[i])));
  391. params.use_mmap = false;
  392. } else if (arg == "--lora-base") {
  393. if (++i >= argc) {
  394. invalid_param = true;
  395. break;
  396. }
  397. params.lora_base = argv[i];
  398. } else if (arg == "--mmproj") {
  399. if (++i >= argc) {
  400. invalid_param = true;
  401. break;
  402. }
  403. params.mmproj = argv[i];
  404. } else if (arg == "--image") {
  405. if (++i >= argc) {
  406. invalid_param = true;
  407. break;
  408. }
  409. params.image = argv[i];
  410. } else if (arg == "-i" || arg == "--interactive") {
  411. params.interactive = true;
  412. } else if (arg == "--embedding") {
  413. params.embedding = true;
  414. } else if (arg == "--interactive-first") {
  415. params.interactive_first = true;
  416. } else if (arg == "-ins" || arg == "--instruct") {
  417. params.instruct = true;
  418. } else if (arg == "--infill") {
  419. params.infill = true;
  420. } else if (arg == "--multiline-input") {
  421. params.multiline_input = true;
  422. } else if (arg == "--simple-io") {
  423. params.simple_io = true;
  424. } else if (arg == "-cb" || arg == "--cont-batching") {
  425. params.cont_batching = true;
  426. } else if (arg == "--color") {
  427. params.use_color = true;
  428. } else if (arg == "--mlock") {
  429. params.use_mlock = true;
  430. } else if (arg == "--gpu-layers" || arg == "-ngl" || arg == "--n-gpu-layers") {
  431. if (++i >= argc) {
  432. invalid_param = true;
  433. break;
  434. }
  435. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  436. params.n_gpu_layers = std::stoi(argv[i]);
  437. #else
  438. fprintf(stderr, "warning: not compiled with GPU offload support, --n-gpu-layers option will be ignored\n");
  439. fprintf(stderr, "warning: see main README.md for information on enabling GPU BLAS support\n");
  440. #endif
  441. } else if (arg == "--gpu-layers-draft" || arg == "-ngld" || arg == "--n-gpu-layers-draft") {
  442. if (++i >= argc) {
  443. invalid_param = true;
  444. break;
  445. }
  446. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  447. params.n_gpu_layers_draft = std::stoi(argv[i]);
  448. #else
  449. fprintf(stderr, "warning: not compiled with GPU offload support, --n-gpu-layers-draft option will be ignored\n");
  450. fprintf(stderr, "warning: see main README.md for information on enabling GPU BLAS support\n");
  451. #endif
  452. } else if (arg == "--main-gpu" || arg == "-mg") {
  453. if (++i >= argc) {
  454. invalid_param = true;
  455. break;
  456. }
  457. #ifdef GGML_USE_CUBLAS
  458. params.main_gpu = std::stoi(argv[i]);
  459. #else
  460. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set a main GPU.\n");
  461. #endif
  462. } else if (arg == "--tensor-split" || arg == "-ts") {
  463. if (++i >= argc) {
  464. invalid_param = true;
  465. break;
  466. }
  467. #ifdef GGML_USE_CUBLAS
  468. std::string arg_next = argv[i];
  469. // split string by , and /
  470. const std::regex regex{R"([,/]+)"};
  471. std::sregex_token_iterator it{arg_next.begin(), arg_next.end(), regex, -1};
  472. std::vector<std::string> split_arg{it, {}};
  473. GGML_ASSERT(split_arg.size() <= LLAMA_MAX_DEVICES);
  474. for (size_t i = 0; i < LLAMA_MAX_DEVICES; ++i) {
  475. if (i < split_arg.size()) {
  476. params.tensor_split[i] = std::stof(split_arg[i]);
  477. } else {
  478. params.tensor_split[i] = 0.0f;
  479. }
  480. }
  481. #else
  482. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set a tensor split.\n");
  483. #endif // GGML_USE_CUBLAS
  484. } else if (arg == "--no-mul-mat-q" || arg == "-nommq") {
  485. #ifdef GGML_USE_CUBLAS
  486. params.mul_mat_q = false;
  487. #else
  488. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. Disabling mul_mat_q kernels has no effect.\n");
  489. #endif // GGML_USE_CUBLAS
  490. } else if (arg == "--no-mmap") {
  491. params.use_mmap = false;
  492. } else if (arg == "--numa") {
  493. params.numa = true;
  494. } else if (arg == "--verbose-prompt") {
  495. params.verbose_prompt = true;
  496. } else if (arg == "-r" || arg == "--reverse-prompt") {
  497. if (++i >= argc) {
  498. invalid_param = true;
  499. break;
  500. }
  501. params.antiprompt.push_back(argv[i]);
  502. } else if (arg == "-ld" || arg == "--logdir") {
  503. if (++i >= argc) {
  504. invalid_param = true;
  505. break;
  506. }
  507. params.logdir = argv[i];
  508. if (params.logdir.back() != DIRECTORY_SEPARATOR) {
  509. params.logdir += DIRECTORY_SEPARATOR;
  510. }
  511. } else if (arg == "--perplexity" || arg == "--all-logits") {
  512. params.logits_all = true;
  513. } else if (arg == "--ppl-stride") {
  514. if (++i >= argc) {
  515. invalid_param = true;
  516. break;
  517. }
  518. params.ppl_stride = std::stoi(argv[i]);
  519. } else if (arg == "--ppl-output-type") {
  520. if (++i >= argc) {
  521. invalid_param = true;
  522. break;
  523. }
  524. params.ppl_output_type = std::stoi(argv[i]);
  525. } else if (arg == "--hellaswag") {
  526. params.hellaswag = true;
  527. } else if (arg == "--hellaswag-tasks") {
  528. if (++i >= argc) {
  529. invalid_param = true;
  530. break;
  531. }
  532. params.hellaswag_tasks = std::stoi(argv[i]);
  533. } else if (arg == "--ignore-eos") {
  534. params.ignore_eos = true;
  535. } else if (arg == "--no-penalize-nl") {
  536. sparams.penalize_nl = false;
  537. } else if (arg == "-l" || arg == "--logit-bias") {
  538. if (++i >= argc) {
  539. invalid_param = true;
  540. break;
  541. }
  542. std::stringstream ss(argv[i]);
  543. llama_token key;
  544. char sign;
  545. std::string value_str;
  546. try {
  547. if (ss >> key && ss >> sign && std::getline(ss, value_str) && (sign == '+' || sign == '-')) {
  548. sparams.logit_bias[key] = std::stof(value_str) * ((sign == '-') ? -1.0f : 1.0f);
  549. } else {
  550. throw std::exception();
  551. }
  552. } catch (const std::exception&) {
  553. invalid_param = true;
  554. break;
  555. }
  556. } else if (arg == "-h" || arg == "--help") {
  557. return false;
  558. } else if (arg == "--random-prompt") {
  559. params.random_prompt = true;
  560. } else if (arg == "--in-prefix-bos") {
  561. params.input_prefix_bos = true;
  562. } else if (arg == "--in-prefix") {
  563. if (++i >= argc) {
  564. invalid_param = true;
  565. break;
  566. }
  567. params.input_prefix = argv[i];
  568. } else if (arg == "--in-suffix") {
  569. if (++i >= argc) {
  570. invalid_param = true;
  571. break;
  572. }
  573. params.input_suffix = argv[i];
  574. } else if (arg == "--grammar") {
  575. if (++i >= argc) {
  576. invalid_param = true;
  577. break;
  578. }
  579. sparams.grammar = argv[i];
  580. } else if (arg == "--grammar-file") {
  581. if (++i >= argc) {
  582. invalid_param = true;
  583. break;
  584. }
  585. std::ifstream file(argv[i]);
  586. if (!file) {
  587. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  588. invalid_param = true;
  589. break;
  590. }
  591. std::copy(
  592. std::istreambuf_iterator<char>(file),
  593. std::istreambuf_iterator<char>(),
  594. std::back_inserter(sparams.grammar)
  595. );
  596. #ifndef LOG_DISABLE_LOGS
  597. // Parse args for logging parameters
  598. } else if ( log_param_single_parse( argv[i] ) ) {
  599. // Do nothing, log_param_single_parse automatically does it's thing
  600. // and returns if a match was found and parsed.
  601. } else if ( log_param_pair_parse( /*check_but_dont_parse*/ true, argv[i] ) ) {
  602. // We have a matching known parameter requiring an argument,
  603. // now we need to check if there is anything after this argv
  604. // and flag invalid_param or parse it.
  605. if (++i >= argc) {
  606. invalid_param = true;
  607. break;
  608. }
  609. if( !log_param_pair_parse( /*check_but_dont_parse*/ false, argv[i-1], argv[i]) ) {
  610. invalid_param = true;
  611. break;
  612. }
  613. // End of Parse args for logging parameters
  614. #endif // LOG_DISABLE_LOGS
  615. } else {
  616. throw std::invalid_argument("error: unknown argument: " + arg);
  617. }
  618. }
  619. if (invalid_param) {
  620. throw std::invalid_argument("error: invalid parameter for argument: " + arg);
  621. }
  622. if (params.prompt_cache_all &&
  623. (params.interactive || params.interactive_first ||
  624. params.instruct)) {
  625. throw std::invalid_argument("error: --prompt-cache-all not supported in interactive mode yet\n");
  626. }
  627. if (params.escape) {
  628. process_escapes(params.prompt);
  629. process_escapes(params.input_prefix);
  630. process_escapes(params.input_suffix);
  631. process_escapes(sparams.cfg_negative_prompt);
  632. for (auto & antiprompt : params.antiprompt) {
  633. process_escapes(antiprompt);
  634. }
  635. }
  636. return true;
  637. }
  638. void gpt_print_usage(int /*argc*/, char ** argv, const gpt_params & params) {
  639. const llama_sampling_params & sparams = params.sparams;
  640. printf("\n");
  641. printf("usage: %s [options]\n", argv[0]);
  642. printf("\n");
  643. printf("options:\n");
  644. printf(" -h, --help show this help message and exit\n");
  645. printf(" -i, --interactive run in interactive mode\n");
  646. printf(" --interactive-first run in interactive mode and wait for input right away\n");
  647. printf(" -ins, --instruct run in instruction mode (use with Alpaca models)\n");
  648. printf(" --multiline-input allows you to write or paste multiple lines without ending each in '\\'\n");
  649. printf(" -r PROMPT, --reverse-prompt PROMPT\n");
  650. printf(" halt generation at PROMPT, return control in interactive mode\n");
  651. printf(" (can be specified more than once for multiple prompts).\n");
  652. printf(" --color colorise output to distinguish prompt and user input from generations\n");
  653. printf(" -s SEED, --seed SEED RNG seed (default: -1, use random seed for < 0)\n");
  654. printf(" -t N, --threads N number of threads to use during generation (default: %d)\n", params.n_threads);
  655. printf(" -tb N, --threads-batch N\n");
  656. printf(" number of threads to use during batch and prompt processing (default: same as --threads)\n");
  657. printf(" -p PROMPT, --prompt PROMPT\n");
  658. printf(" prompt to start generation with (default: empty)\n");
  659. printf(" -e, --escape process prompt escapes sequences (\\n, \\r, \\t, \\', \\\", \\\\)\n");
  660. printf(" --prompt-cache FNAME file to cache prompt state for faster startup (default: none)\n");
  661. printf(" --prompt-cache-all if specified, saves user input and generations to cache as well.\n");
  662. printf(" not supported with --interactive or other interactive options\n");
  663. printf(" --prompt-cache-ro if specified, uses the prompt cache but does not update it.\n");
  664. printf(" --random-prompt start with a randomized prompt.\n");
  665. printf(" --in-prefix-bos prefix BOS to user inputs, preceding the `--in-prefix` string\n");
  666. printf(" --in-prefix STRING string to prefix user inputs with (default: empty)\n");
  667. printf(" --in-suffix STRING string to suffix after user inputs with (default: empty)\n");
  668. printf(" -f FNAME, --file FNAME\n");
  669. printf(" prompt file to start generation.\n");
  670. printf(" -n N, --n-predict N number of tokens to predict (default: %d, -1 = infinity, -2 = until context filled)\n", params.n_predict);
  671. printf(" -c N, --ctx-size N size of the prompt context (default: %d, 0 = loaded from model)\n", params.n_ctx);
  672. printf(" -b N, --batch-size N batch size for prompt processing (default: %d)\n", params.n_batch);
  673. printf(" --top-k N top-k sampling (default: %d, 0 = disabled)\n", sparams.top_k);
  674. printf(" --top-p N top-p sampling (default: %.1f, 1.0 = disabled)\n", (double)sparams.top_p);
  675. printf(" --min-p N min-p sampling (default: %.1f, 0.0 = disabled)\n", (double)sparams.min_p);
  676. printf(" --tfs N tail free sampling, parameter z (default: %.1f, 1.0 = disabled)\n", (double)sparams.tfs_z);
  677. printf(" --typical N locally typical sampling, parameter p (default: %.1f, 1.0 = disabled)\n", (double)sparams.typical_p);
  678. printf(" --repeat-last-n N last n tokens to consider for penalize (default: %d, 0 = disabled, -1 = ctx_size)\n", sparams.penalty_last_n);
  679. printf(" --repeat-penalty N penalize repeat sequence of tokens (default: %.1f, 1.0 = disabled)\n", (double)sparams.penalty_repeat);
  680. printf(" --presence-penalty N repeat alpha presence penalty (default: %.1f, 0.0 = disabled)\n", (double)sparams.penalty_present);
  681. printf(" --frequency-penalty N repeat alpha frequency penalty (default: %.1f, 0.0 = disabled)\n", (double)sparams.penalty_freq);
  682. printf(" --mirostat N use Mirostat sampling.\n");
  683. printf(" Top K, Nucleus, Tail Free and Locally Typical samplers are ignored if used.\n");
  684. printf(" (default: %d, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)\n", sparams.mirostat);
  685. printf(" --mirostat-lr N Mirostat learning rate, parameter eta (default: %.1f)\n", (double)sparams.mirostat_eta);
  686. printf(" --mirostat-ent N Mirostat target entropy, parameter tau (default: %.1f)\n", (double)sparams.mirostat_tau);
  687. printf(" -l TOKEN_ID(+/-)BIAS, --logit-bias TOKEN_ID(+/-)BIAS\n");
  688. printf(" modifies the likelihood of token appearing in the completion,\n");
  689. printf(" i.e. `--logit-bias 15043+1` to increase likelihood of token ' Hello',\n");
  690. printf(" or `--logit-bias 15043-1` to decrease likelihood of token ' Hello'\n");
  691. printf(" --grammar GRAMMAR BNF-like grammar to constrain generations (see samples in grammars/ dir)\n");
  692. printf(" --grammar-file FNAME file to read grammar from\n");
  693. printf(" --cfg-negative-prompt PROMPT\n");
  694. printf(" negative prompt to use for guidance. (default: empty)\n");
  695. printf(" --cfg-negative-prompt-file FNAME\n");
  696. printf(" negative prompt file to use for guidance. (default: empty)\n");
  697. printf(" --cfg-scale N strength of guidance (default: %f, 1.0 = disable)\n", sparams.cfg_scale);
  698. printf(" --rope-scale N RoPE context linear scaling factor, inverse of --rope-freq-scale\n");
  699. printf(" --rope-freq-base N RoPE base frequency, used by NTK-aware scaling (default: loaded from model)\n");
  700. printf(" --rope-freq-scale N RoPE frequency linear scaling factor (default: loaded from model)\n");
  701. printf(" --ignore-eos ignore end of stream token and continue generating (implies --logit-bias 2-inf)\n");
  702. printf(" --no-penalize-nl do not penalize newline token\n");
  703. printf(" --memory-f32 use f32 instead of f16 for memory key+value (default: disabled)\n");
  704. printf(" not recommended: doubles context memory required and no measurable increase in quality\n");
  705. printf(" --temp N temperature (default: %.1f)\n", (double)sparams.temp);
  706. printf(" --logits-all return logits for all tokens in the batch (default: disabled)\n");
  707. printf(" --hellaswag compute HellaSwag score over random tasks from datafile supplied with -f\n");
  708. printf(" --hellaswag-tasks N number of tasks to use when computing the HellaSwag score (default: %zu)\n", params.hellaswag_tasks);
  709. printf(" --keep N number of tokens to keep from the initial prompt (default: %d, -1 = all)\n", params.n_keep);
  710. printf(" --draft N number of tokens to draft for speculative decoding (default: %d)\n", params.n_draft);
  711. printf(" --chunks N max number of chunks to process (default: %d, -1 = all)\n", params.n_chunks);
  712. printf(" -np N, --parallel N number of parallel sequences to decode (default: %d)\n", params.n_parallel);
  713. printf(" -ns N, --sequences N number of sequences to decode (default: %d)\n", params.n_sequences);
  714. printf(" -cb, --cont-batching enable continuous batching (a.k.a dynamic batching) (default: disabled)\n");
  715. printf(" --mmproj MMPROJ_FILE path to a multimodal projector file for LLaVA. see examples/llava/README.md\n");
  716. printf(" --image IMAGE_FILE path to an image file. use with multimodal models\n");
  717. if (llama_mlock_supported()) {
  718. printf(" --mlock force system to keep model in RAM rather than swapping or compressing\n");
  719. }
  720. if (llama_mmap_supported()) {
  721. printf(" --no-mmap do not memory-map model (slower load but may reduce pageouts if not using mlock)\n");
  722. }
  723. printf(" --numa attempt optimizations that help on some NUMA systems\n");
  724. printf(" if run without this previously, it is recommended to drop the system page cache before using this\n");
  725. printf(" see https://github.com/ggerganov/llama.cpp/issues/1437\n");
  726. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  727. printf(" -ngl N, --n-gpu-layers N\n");
  728. printf(" number of layers to store in VRAM\n");
  729. printf(" -ngld N, --n-gpu-layers-draft N\n");
  730. printf(" number of layers to store in VRAM for the draft model\n");
  731. printf(" -ts SPLIT --tensor-split SPLIT\n");
  732. printf(" how to split tensors across multiple GPUs, comma-separated list of proportions, e.g. 3,1\n");
  733. printf(" -mg i, --main-gpu i the GPU to use for scratch and small tensors\n");
  734. #ifdef GGML_USE_CUBLAS
  735. printf(" -nommq, --no-mul-mat-q\n");
  736. printf(" use " GGML_CUBLAS_NAME " instead of custom mul_mat_q " GGML_CUDA_NAME " kernels.\n");
  737. printf(" Not recommended since this is both slower and uses more VRAM.\n");
  738. #endif // GGML_USE_CUBLAS
  739. #endif
  740. printf(" --verbose-prompt print prompt before generation\n");
  741. printf(" --simple-io use basic IO for better compatibility in subprocesses and limited consoles\n");
  742. printf(" --lora FNAME apply LoRA adapter (implies --no-mmap)\n");
  743. printf(" --lora-scaled FNAME S apply LoRA adapter with user defined scaling S (implies --no-mmap)\n");
  744. printf(" --lora-base FNAME optional model to use as a base for the layers modified by the LoRA adapter\n");
  745. printf(" -m FNAME, --model FNAME\n");
  746. printf(" model path (default: %s)\n", params.model.c_str());
  747. printf(" -md FNAME, --model-draft FNAME\n");
  748. printf(" draft model for speculative decoding (default: %s)\n", params.model.c_str());
  749. printf(" -ld LOGDIR, --logdir LOGDIR\n");
  750. printf(" path under which to save YAML logs (no logging if unset)\n");
  751. printf("\n");
  752. #ifndef LOG_DISABLE_LOGS
  753. log_print_usage();
  754. #endif // LOG_DISABLE_LOGS
  755. }
  756. std::string get_system_info(const gpt_params & params) {
  757. std::ostringstream os;
  758. os << "system_info: n_threads = " << params.n_threads;
  759. if (params.n_threads_batch != -1) {
  760. os << " (n_threads_batch = " << params.n_threads_batch << ")";
  761. }
  762. os << " / " << std::thread::hardware_concurrency() << " | " << llama_print_system_info();
  763. return os.str();
  764. }
  765. std::string gpt_random_prompt(std::mt19937 & rng) {
  766. const int r = rng() % 10;
  767. switch (r) {
  768. case 0: return "So";
  769. case 1: return "Once upon a time";
  770. case 2: return "When";
  771. case 3: return "The";
  772. case 4: return "After";
  773. case 5: return "If";
  774. case 6: return "import";
  775. case 7: return "He";
  776. case 8: return "She";
  777. case 9: return "They";
  778. }
  779. GGML_UNREACHABLE();
  780. }
  781. //
  782. // Model utils
  783. //
  784. struct llama_model_params llama_model_params_from_gpt_params(const gpt_params & params) {
  785. auto mparams = llama_model_default_params();
  786. if (params.n_gpu_layers != -1) {
  787. mparams.n_gpu_layers = params.n_gpu_layers;
  788. }
  789. mparams.main_gpu = params.main_gpu;
  790. mparams.tensor_split = params.tensor_split;
  791. mparams.use_mmap = params.use_mmap;
  792. mparams.use_mlock = params.use_mlock;
  793. return mparams;
  794. }
  795. struct llama_context_params llama_context_params_from_gpt_params(const gpt_params & params) {
  796. auto cparams = llama_context_default_params();
  797. cparams.n_ctx = params.n_ctx;
  798. cparams.n_batch = params.n_batch;
  799. cparams.n_threads = params.n_threads;
  800. cparams.n_threads_batch = params.n_threads_batch == -1 ? params.n_threads : params.n_threads_batch;
  801. cparams.mul_mat_q = params.mul_mat_q;
  802. cparams.seed = params.seed;
  803. cparams.f16_kv = params.memory_f16;
  804. cparams.logits_all = params.logits_all;
  805. cparams.embedding = params.embedding;
  806. cparams.rope_freq_base = params.rope_freq_base;
  807. cparams.rope_freq_scale = params.rope_freq_scale;
  808. return cparams;
  809. }
  810. void llama_batch_clear(struct llama_batch & batch) {
  811. batch.n_tokens = 0;
  812. }
  813. void llama_batch_add(
  814. struct llama_batch & batch,
  815. llama_token id,
  816. llama_pos pos,
  817. const std::vector<llama_seq_id> & seq_ids,
  818. bool logits) {
  819. batch.token [batch.n_tokens] = id;
  820. batch.pos [batch.n_tokens] = pos,
  821. batch.n_seq_id[batch.n_tokens] = seq_ids.size();
  822. for (size_t i = 0; i < seq_ids.size(); ++i) {
  823. batch.seq_id[batch.n_tokens][i] = seq_ids[i];
  824. }
  825. batch.logits [batch.n_tokens] = logits;
  826. batch.n_tokens++;
  827. }
  828. std::tuple<struct llama_model *, struct llama_context *> llama_init_from_gpt_params(gpt_params & params) {
  829. auto mparams = llama_model_params_from_gpt_params(params);
  830. llama_model * model = llama_load_model_from_file(params.model.c_str(), mparams);
  831. if (model == NULL) {
  832. fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, params.model.c_str());
  833. return std::make_tuple(nullptr, nullptr);
  834. }
  835. auto cparams = llama_context_params_from_gpt_params(params);
  836. llama_context * lctx = llama_new_context_with_model(model, cparams);
  837. if (lctx == NULL) {
  838. fprintf(stderr, "%s: error: failed to create context with model '%s'\n", __func__, params.model.c_str());
  839. llama_free_model(model);
  840. return std::make_tuple(nullptr, nullptr);
  841. }
  842. for (unsigned int i = 0; i < params.lora_adapter.size(); ++i) {
  843. const std::string& lora_adapter = std::get<0>(params.lora_adapter[i]);
  844. float lora_scale = std::get<1>(params.lora_adapter[i]);
  845. int err = llama_model_apply_lora_from_file(model,
  846. lora_adapter.c_str(),
  847. lora_scale,
  848. ((i > 0) || params.lora_base.empty())
  849. ? NULL
  850. : params.lora_base.c_str(),
  851. params.n_threads);
  852. if (err != 0) {
  853. fprintf(stderr, "%s: error: failed to apply lora adapter\n", __func__);
  854. llama_free(lctx);
  855. llama_free_model(model);
  856. return std::make_tuple(nullptr, nullptr);
  857. }
  858. }
  859. if (params.ignore_eos) {
  860. params.sparams.logit_bias[llama_token_eos(model)] = -INFINITY;
  861. }
  862. {
  863. LOG("warming up the model with an empty run\n");
  864. std::vector<llama_token> tmp = { llama_token_bos(model), llama_token_eos(model), };
  865. llama_decode(lctx, llama_batch_get_one(tmp.data(), std::min(tmp.size(), (size_t) params.n_batch), 0, 0));
  866. llama_kv_cache_clear(lctx);
  867. llama_reset_timings(lctx);
  868. }
  869. return std::make_tuple(model, lctx);
  870. }
  871. //
  872. // Vocab utils
  873. //
  874. std::vector<llama_token> llama_tokenize(
  875. const struct llama_context * ctx,
  876. const std::string & text,
  877. bool add_bos,
  878. bool special) {
  879. return llama_tokenize(llama_get_model(ctx), text, add_bos, special);
  880. }
  881. std::vector<llama_token> llama_tokenize(
  882. const struct llama_model * model,
  883. const std::string & text,
  884. bool add_bos,
  885. bool special) {
  886. // upper limit for the number of tokens
  887. int n_tokens = text.length() + add_bos;
  888. std::vector<llama_token> result(n_tokens);
  889. n_tokens = llama_tokenize(model, text.data(), text.length(), result.data(), result.size(), add_bos, special);
  890. if (n_tokens < 0) {
  891. result.resize(-n_tokens);
  892. int check = llama_tokenize(model, text.data(), text.length(), result.data(), result.size(), add_bos, special);
  893. GGML_ASSERT(check == -n_tokens);
  894. } else {
  895. result.resize(n_tokens);
  896. }
  897. return result;
  898. }
  899. std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  900. std::vector<char> result(8, 0);
  901. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  902. if (n_tokens < 0) {
  903. result.resize(-n_tokens);
  904. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  905. GGML_ASSERT(check == -n_tokens);
  906. } else {
  907. result.resize(n_tokens);
  908. }
  909. return std::string(result.data(), result.size());
  910. }
  911. std::string llama_detokenize_spm(llama_context * ctx, const std::vector<llama_token> & tokens) {
  912. const llama_token bos_id = llama_token_bos(llama_get_model(ctx));
  913. std::string piece;
  914. std::string result;
  915. for (size_t i = 0; i < tokens.size(); ++i) {
  916. piece = llama_token_to_piece(ctx, tokens[i]);
  917. // remove the leading space of the first non-BOS token
  918. if (((tokens[0] == bos_id && i == 1) || (tokens[0] != bos_id && i == 0)) && piece[0] == ' ') {
  919. piece = piece.substr(1);
  920. }
  921. result += piece;
  922. }
  923. return result;
  924. }
  925. std::string llama_detokenize_bpe(llama_context * ctx, const std::vector<llama_token> & tokens) {
  926. std::string piece;
  927. std::string result;
  928. for (size_t i = 0; i < tokens.size(); ++i) {
  929. piece = llama_token_to_piece(ctx, tokens[i]);
  930. result += piece;
  931. }
  932. // NOTE: the original tokenizer decodes bytes after collecting the pieces.
  933. return result;
  934. }
  935. //
  936. // YAML utils
  937. //
  938. // returns true if successful, false otherwise
  939. bool create_directory_with_parents(const std::string & path) {
  940. #ifdef _WIN32
  941. std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
  942. std::wstring wpath = converter.from_bytes(path);
  943. // if the path already exists, check whether it's a directory
  944. const DWORD attributes = GetFileAttributesW(wpath.c_str());
  945. if ((attributes != INVALID_FILE_ATTRIBUTES) && (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  946. return true;
  947. }
  948. size_t pos_slash = 0;
  949. // process path from front to back, procedurally creating directories
  950. while ((pos_slash = path.find('\\', pos_slash)) != std::string::npos) {
  951. const std::wstring subpath = wpath.substr(0, pos_slash);
  952. const wchar_t * test = subpath.c_str();
  953. const bool success = CreateDirectoryW(test, NULL);
  954. if (!success) {
  955. const DWORD error = GetLastError();
  956. // if the path already exists, ensure that it's a directory
  957. if (error == ERROR_ALREADY_EXISTS) {
  958. const DWORD attributes = GetFileAttributesW(subpath.c_str());
  959. if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  960. return false;
  961. }
  962. } else {
  963. return false;
  964. }
  965. }
  966. pos_slash += 1;
  967. }
  968. return true;
  969. #else
  970. // if the path already exists, check whether it's a directory
  971. struct stat info;
  972. if (stat(path.c_str(), &info) == 0) {
  973. return S_ISDIR(info.st_mode);
  974. }
  975. size_t pos_slash = 1; // skip leading slashes for directory creation
  976. // process path from front to back, procedurally creating directories
  977. while ((pos_slash = path.find('/', pos_slash)) != std::string::npos) {
  978. const std::string subpath = path.substr(0, pos_slash);
  979. struct stat info;
  980. // if the path already exists, ensure that it's a directory
  981. if (stat(subpath.c_str(), &info) == 0) {
  982. if (!S_ISDIR(info.st_mode)) {
  983. return false;
  984. }
  985. } else {
  986. // create parent directories
  987. const int ret = mkdir(subpath.c_str(), 0755);
  988. if (ret != 0) {
  989. return false;
  990. }
  991. }
  992. pos_slash += 1;
  993. }
  994. return true;
  995. #endif // _WIN32
  996. }
  997. void dump_vector_float_yaml(FILE * stream, const char * prop_name, const std::vector<float> & data) {
  998. if (data.empty()) {
  999. fprintf(stream, "%s:\n", prop_name);
  1000. return;
  1001. }
  1002. fprintf(stream, "%s: [", prop_name);
  1003. for (size_t i = 0; i < data.size() - 1; ++i) {
  1004. fprintf(stream, "%e, ", data[i]);
  1005. }
  1006. fprintf(stream, "%e]\n", data.back());
  1007. }
  1008. void dump_vector_int_yaml(FILE * stream, const char * prop_name, const std::vector<int> & data) {
  1009. if (data.empty()) {
  1010. fprintf(stream, "%s:\n", prop_name);
  1011. return;
  1012. }
  1013. fprintf(stream, "%s: [", prop_name);
  1014. for (size_t i = 0; i < data.size() - 1; ++i) {
  1015. fprintf(stream, "%d, ", data[i]);
  1016. }
  1017. fprintf(stream, "%d]\n", data.back());
  1018. }
  1019. void dump_string_yaml_multiline(FILE * stream, const char * prop_name, const char * data) {
  1020. std::string data_str(data == NULL ? "" : data);
  1021. if (data_str.empty()) {
  1022. fprintf(stream, "%s:\n", prop_name);
  1023. return;
  1024. }
  1025. size_t pos_start = 0;
  1026. size_t pos_found = 0;
  1027. if (!data_str.empty() && (std::isspace(data_str[0]) || std::isspace(data_str.back()))) {
  1028. data_str = std::regex_replace(data_str, std::regex("\n"), "\\n");
  1029. data_str = std::regex_replace(data_str, std::regex("\""), "\\\"");
  1030. data_str = "\"" + data_str + "\"";
  1031. fprintf(stream, "%s: %s\n", prop_name, data_str.c_str());
  1032. return;
  1033. }
  1034. if (data_str.find('\n') == std::string::npos) {
  1035. fprintf(stream, "%s: %s\n", prop_name, data_str.c_str());
  1036. return;
  1037. }
  1038. fprintf(stream, "%s: |\n", prop_name);
  1039. while ((pos_found = data_str.find('\n', pos_start)) != std::string::npos) {
  1040. fprintf(stream, " %s\n", data_str.substr(pos_start, pos_found-pos_start).c_str());
  1041. pos_start = pos_found + 1;
  1042. }
  1043. }
  1044. std::string get_sortable_timestamp() {
  1045. using clock = std::chrono::system_clock;
  1046. const clock::time_point current_time = clock::now();
  1047. const time_t as_time_t = clock::to_time_t(current_time);
  1048. char timestamp_no_ns[100];
  1049. std::strftime(timestamp_no_ns, 100, "%Y_%m_%d-%H_%M_%S", std::localtime(&as_time_t));
  1050. const int64_t ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
  1051. current_time.time_since_epoch() % 1000000000).count();
  1052. char timestamp_ns[11];
  1053. snprintf(timestamp_ns, 11, "%09" PRId64, ns);
  1054. return std::string(timestamp_no_ns) + "." + std::string(timestamp_ns);
  1055. }
  1056. void dump_non_result_info_yaml(FILE * stream, const gpt_params & params, const llama_context * lctx,
  1057. const std::string & timestamp, const std::vector<int> & prompt_tokens, const char * model_desc) {
  1058. const llama_sampling_params & sparams = params.sparams;
  1059. fprintf(stream, "build_commit: %s\n", BUILD_COMMIT);
  1060. fprintf(stream, "build_number: %d\n", BUILD_NUMBER);
  1061. fprintf(stream, "cpu_has_arm_fma: %s\n", ggml_cpu_has_arm_fma() ? "true" : "false");
  1062. fprintf(stream, "cpu_has_avx: %s\n", ggml_cpu_has_avx() ? "true" : "false");
  1063. fprintf(stream, "cpu_has_avx2: %s\n", ggml_cpu_has_avx2() ? "true" : "false");
  1064. fprintf(stream, "cpu_has_avx512: %s\n", ggml_cpu_has_avx512() ? "true" : "false");
  1065. fprintf(stream, "cpu_has_avx512_vbmi: %s\n", ggml_cpu_has_avx512_vbmi() ? "true" : "false");
  1066. fprintf(stream, "cpu_has_avx512_vnni: %s\n", ggml_cpu_has_avx512_vnni() ? "true" : "false");
  1067. fprintf(stream, "cpu_has_blas: %s\n", ggml_cpu_has_blas() ? "true" : "false");
  1068. fprintf(stream, "cpu_has_cublas: %s\n", ggml_cpu_has_cublas() ? "true" : "false");
  1069. fprintf(stream, "cpu_has_clblast: %s\n", ggml_cpu_has_clblast() ? "true" : "false");
  1070. fprintf(stream, "cpu_has_fma: %s\n", ggml_cpu_has_fma() ? "true" : "false");
  1071. fprintf(stream, "cpu_has_gpublas: %s\n", ggml_cpu_has_gpublas() ? "true" : "false");
  1072. fprintf(stream, "cpu_has_neon: %s\n", ggml_cpu_has_neon() ? "true" : "false");
  1073. fprintf(stream, "cpu_has_f16c: %s\n", ggml_cpu_has_f16c() ? "true" : "false");
  1074. fprintf(stream, "cpu_has_fp16_va: %s\n", ggml_cpu_has_fp16_va() ? "true" : "false");
  1075. fprintf(stream, "cpu_has_wasm_simd: %s\n", ggml_cpu_has_wasm_simd() ? "true" : "false");
  1076. fprintf(stream, "cpu_has_blas: %s\n", ggml_cpu_has_blas() ? "true" : "false");
  1077. fprintf(stream, "cpu_has_sse3: %s\n", ggml_cpu_has_sse3() ? "true" : "false");
  1078. fprintf(stream, "cpu_has_vsx: %s\n", ggml_cpu_has_vsx() ? "true" : "false");
  1079. #ifdef NDEBUG
  1080. fprintf(stream, "debug: false\n");
  1081. #else
  1082. fprintf(stream, "debug: true\n");
  1083. #endif // NDEBUG
  1084. fprintf(stream, "model_desc: %s\n", model_desc);
  1085. fprintf(stream, "n_vocab: %d # output size of the final layer, 32001 for some models\n", llama_n_vocab(llama_get_model(lctx)));
  1086. #ifdef __OPTIMIZE__
  1087. fprintf(stream, "optimize: true\n");
  1088. #else
  1089. fprintf(stream, "optimize: false\n");
  1090. #endif // __OPTIMIZE__
  1091. fprintf(stream, "time: %s\n", timestamp.c_str());
  1092. fprintf(stream, "\n");
  1093. fprintf(stream, "###############\n");
  1094. fprintf(stream, "# User Inputs #\n");
  1095. fprintf(stream, "###############\n");
  1096. fprintf(stream, "\n");
  1097. fprintf(stream, "alias: %s # default: unknown\n", params.model_alias.c_str());
  1098. fprintf(stream, "batch_size: %d # default: 512\n", params.n_batch);
  1099. dump_string_yaml_multiline(stream, "cfg_negative_prompt", sparams.cfg_negative_prompt.c_str());
  1100. fprintf(stream, "cfg_scale: %f # default: 1.0\n", sparams.cfg_scale);
  1101. fprintf(stream, "chunks: %d # default: -1 (unlimited)\n", params.n_chunks);
  1102. fprintf(stream, "color: %s # default: false\n", params.use_color ? "true" : "false");
  1103. fprintf(stream, "ctx_size: %d # default: 512\n", params.n_ctx);
  1104. fprintf(stream, "escape: %s # default: false\n", params.escape ? "true" : "false");
  1105. fprintf(stream, "file: # never logged, see prompt instead. Can still be specified for input.\n");
  1106. fprintf(stream, "frequency_penalty: %f # default: 0.0 \n", sparams.penalty_freq);
  1107. dump_string_yaml_multiline(stream, "grammar", sparams.grammar.c_str());
  1108. fprintf(stream, "grammar-file: # never logged, see grammar instead. Can still be specified for input.\n");
  1109. fprintf(stream, "hellaswag: %s # default: false\n", params.hellaswag ? "true" : "false");
  1110. fprintf(stream, "hellaswag_tasks: %zu # default: 400\n", params.hellaswag_tasks);
  1111. const auto logit_bias_eos = sparams.logit_bias.find(llama_token_eos(llama_get_model(lctx)));
  1112. const bool ignore_eos = logit_bias_eos != sparams.logit_bias.end() && logit_bias_eos->second == -INFINITY;
  1113. fprintf(stream, "ignore_eos: %s # default: false\n", ignore_eos ? "true" : "false");
  1114. dump_string_yaml_multiline(stream, "in_prefix", params.input_prefix.c_str());
  1115. fprintf(stream, "in_prefix_bos: %s # default: false\n", params.input_prefix_bos ? "true" : "false");
  1116. dump_string_yaml_multiline(stream, "in_suffix", params.input_prefix.c_str());
  1117. fprintf(stream, "instruct: %s # default: false\n", params.instruct ? "true" : "false");
  1118. fprintf(stream, "interactive: %s # default: false\n", params.interactive ? "true" : "false");
  1119. fprintf(stream, "interactive_first: %s # default: false\n", params.interactive_first ? "true" : "false");
  1120. fprintf(stream, "keep: %d # default: 0\n", params.n_keep);
  1121. fprintf(stream, "logdir: %s # default: unset (no logging)\n", params.logdir.c_str());
  1122. fprintf(stream, "logit_bias:\n");
  1123. for (std::pair<llama_token, float> lb : sparams.logit_bias) {
  1124. if (ignore_eos && lb.first == logit_bias_eos->first) {
  1125. continue;
  1126. }
  1127. fprintf(stream, " %d: %f", lb.first, lb.second);
  1128. }
  1129. fprintf(stream, "lora:\n");
  1130. for (std::tuple<std::string, float> la : params.lora_adapter) {
  1131. if (std::get<1>(la) != 1.0f) {
  1132. continue;
  1133. }
  1134. fprintf(stream, " - %s\n", std::get<0>(la).c_str());
  1135. }
  1136. fprintf(stream, "lora_scaled:\n");
  1137. for (std::tuple<std::string, float> la : params.lora_adapter) {
  1138. if (std::get<1>(la) == 1.0f) {
  1139. continue;
  1140. }
  1141. fprintf(stream, " - %s: %f\n", std::get<0>(la).c_str(), std::get<1>(la));
  1142. }
  1143. fprintf(stream, "lora_base: %s\n", params.lora_base.c_str());
  1144. fprintf(stream, "main_gpu: %d # default: 0\n", params.main_gpu);
  1145. fprintf(stream, "memory_f32: %s # default: false\n", !params.memory_f16 ? "true" : "false");
  1146. fprintf(stream, "mirostat: %d # default: 0 (disabled)\n", sparams.mirostat);
  1147. fprintf(stream, "mirostat_ent: %f # default: 5.0\n", sparams.mirostat_tau);
  1148. fprintf(stream, "mirostat_lr: %f # default: 0.1\n", sparams.mirostat_eta);
  1149. fprintf(stream, "mlock: %s # default: false\n", params.use_mlock ? "true" : "false");
  1150. fprintf(stream, "model: %s # default: models/7B/ggml-model.bin\n", params.model.c_str());
  1151. fprintf(stream, "model_draft: %s # default:\n", params.model_draft.c_str());
  1152. fprintf(stream, "multiline_input: %s # default: false\n", params.multiline_input ? "true" : "false");
  1153. fprintf(stream, "n_gpu_layers: %d # default: -1\n", params.n_gpu_layers);
  1154. fprintf(stream, "n_predict: %d # default: -1 (unlimited)\n", params.n_predict);
  1155. fprintf(stream, "n_probs: %d # only used by server binary, default: 0\n", sparams.n_probs);
  1156. fprintf(stream, "no_mmap: %s # default: false\n", !params.use_mmap ? "true" : "false");
  1157. fprintf(stream, "no_mul_mat_q: %s # default: false\n", !params.mul_mat_q ? "true" : "false");
  1158. fprintf(stream, "no_penalize_nl: %s # default: false\n", !sparams.penalize_nl ? "true" : "false");
  1159. fprintf(stream, "numa: %s # default: false\n", params.numa ? "true" : "false");
  1160. fprintf(stream, "ppl_output_type: %d # default: 0\n", params.ppl_output_type);
  1161. fprintf(stream, "ppl_stride: %d # default: 0\n", params.ppl_stride);
  1162. fprintf(stream, "presence_penalty: %f # default: 0.0\n", sparams.penalty_present);
  1163. dump_string_yaml_multiline(stream, "prompt", params.prompt.c_str());
  1164. fprintf(stream, "prompt_cache: %s\n", params.path_prompt_cache.c_str());
  1165. fprintf(stream, "prompt_cache_all: %s # default: false\n", params.prompt_cache_all ? "true" : "false");
  1166. fprintf(stream, "prompt_cache_ro: %s # default: false\n", params.prompt_cache_ro ? "true" : "false");
  1167. dump_vector_int_yaml(stream, "prompt_tokens", prompt_tokens);
  1168. fprintf(stream, "random_prompt: %s # default: false\n", params.random_prompt ? "true" : "false");
  1169. fprintf(stream, "repeat_penalty: %f # default: 1.1\n", sparams.penalty_repeat);
  1170. fprintf(stream, "reverse_prompt:\n");
  1171. for (std::string ap : params.antiprompt) {
  1172. size_t pos = 0;
  1173. while ((pos = ap.find('\n', pos)) != std::string::npos) {
  1174. ap.replace(pos, 1, "\\n");
  1175. pos += 1;
  1176. }
  1177. fprintf(stream, " - %s\n", ap.c_str());
  1178. }
  1179. fprintf(stream, "rope_freq_base: %f # default: 10000.0\n", params.rope_freq_base);
  1180. fprintf(stream, "rope_freq_scale: %f # default: 1.0\n", params.rope_freq_scale);
  1181. fprintf(stream, "seed: %d # default: -1 (random seed)\n", params.seed);
  1182. fprintf(stream, "simple_io: %s # default: false\n", params.simple_io ? "true" : "false");
  1183. fprintf(stream, "cont_batching: %s # default: false\n", params.cont_batching ? "true" : "false");
  1184. fprintf(stream, "temp: %f # default: 0.8\n", sparams.temp);
  1185. const std::vector<float> tensor_split_vector(params.tensor_split, params.tensor_split + LLAMA_MAX_DEVICES);
  1186. dump_vector_float_yaml(stream, "tensor_split", tensor_split_vector);
  1187. fprintf(stream, "tfs: %f # default: 1.0\n", sparams.tfs_z);
  1188. fprintf(stream, "threads: %d # default: %d\n", params.n_threads, std::thread::hardware_concurrency());
  1189. fprintf(stream, "top_k: %d # default: 40\n", sparams.top_k);
  1190. fprintf(stream, "top_p: %f # default: 0.95\n", sparams.top_p);
  1191. fprintf(stream, "min_p: %f # default: 0.0\n", sparams.min_p);
  1192. fprintf(stream, "typical_p: %f # default: 1.0\n", sparams.typical_p);
  1193. fprintf(stream, "verbose_prompt: %s # default: false\n", params.verbose_prompt ? "true" : "false");
  1194. }