common.cpp 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737
  1. #include "common.h"
  2. #include "llama.h"
  3. #include <algorithm>
  4. #include <cassert>
  5. #include <cmath>
  6. #include <cstring>
  7. #include <ctime>
  8. #include <fstream>
  9. #include <iterator>
  10. #include <iostream>
  11. #include <regex>
  12. #include <sstream>
  13. #include <string>
  14. #include <unordered_map>
  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. #if (defined(GGML_USE_CUBLAS) || defined(GGML_USE_SYCL))
  41. #define GGML_USE_CUBLAS_SYCL
  42. #endif
  43. int32_t get_num_physical_cores() {
  44. #ifdef __linux__
  45. // enumerate the set of thread siblings, num entries is num cores
  46. std::unordered_set<std::string> siblings;
  47. for (uint32_t cpu=0; cpu < UINT32_MAX; ++cpu) {
  48. std::ifstream thread_siblings("/sys/devices/system/cpu"
  49. + std::to_string(cpu) + "/topology/thread_siblings");
  50. if (!thread_siblings.is_open()) {
  51. break; // no more cpus
  52. }
  53. std::string line;
  54. if (std::getline(thread_siblings, line)) {
  55. siblings.insert(line);
  56. }
  57. }
  58. if (!siblings.empty()) {
  59. return static_cast<int32_t>(siblings.size());
  60. }
  61. #elif defined(__APPLE__) && defined(__MACH__)
  62. int32_t num_physical_cores;
  63. size_t len = sizeof(num_physical_cores);
  64. int result = sysctlbyname("hw.perflevel0.physicalcpu", &num_physical_cores, &len, NULL, 0);
  65. if (result == 0) {
  66. return num_physical_cores;
  67. }
  68. result = sysctlbyname("hw.physicalcpu", &num_physical_cores, &len, NULL, 0);
  69. if (result == 0) {
  70. return num_physical_cores;
  71. }
  72. #elif defined(_WIN32)
  73. //TODO: Implement
  74. #endif
  75. unsigned int n_threads = std::thread::hardware_concurrency();
  76. return n_threads > 0 ? (n_threads <= 4 ? n_threads : n_threads / 2) : 4;
  77. }
  78. void process_escapes(std::string& input) {
  79. std::size_t input_len = input.length();
  80. std::size_t output_idx = 0;
  81. for (std::size_t input_idx = 0; input_idx < input_len; ++input_idx) {
  82. if (input[input_idx] == '\\' && input_idx + 1 < input_len) {
  83. switch (input[++input_idx]) {
  84. case 'n': input[output_idx++] = '\n'; break;
  85. case 'r': input[output_idx++] = '\r'; break;
  86. case 't': input[output_idx++] = '\t'; break;
  87. case '\'': input[output_idx++] = '\''; break;
  88. case '\"': input[output_idx++] = '\"'; break;
  89. case '\\': input[output_idx++] = '\\'; break;
  90. case 'x':
  91. // Handle \x12, etc
  92. if (input_idx + 2 < input_len) {
  93. const char x[3] = { input[input_idx + 1], input[input_idx + 2], 0 };
  94. char *err_p = nullptr;
  95. const long val = std::strtol(x, &err_p, 16);
  96. if (err_p == x + 2) {
  97. input_idx += 2;
  98. input[output_idx++] = char(val);
  99. break;
  100. }
  101. }
  102. // fall through
  103. default: input[output_idx++] = '\\';
  104. input[output_idx++] = input[input_idx]; break;
  105. }
  106. } else {
  107. input[output_idx++] = input[input_idx];
  108. }
  109. }
  110. input.resize(output_idx);
  111. }
  112. bool gpt_params_parse(int argc, char ** argv, gpt_params & params) {
  113. bool result = true;
  114. try {
  115. if (!gpt_params_parse_ex(argc, argv, params)) {
  116. gpt_print_usage(argc, argv, gpt_params());
  117. exit(0);
  118. }
  119. }
  120. catch (const std::invalid_argument & ex) {
  121. fprintf(stderr, "%s\n", ex.what());
  122. gpt_print_usage(argc, argv, gpt_params());
  123. exit(1);
  124. }
  125. return result;
  126. }
  127. bool gpt_params_parse_ex(int argc, char ** argv, gpt_params & params) {
  128. bool invalid_param = false;
  129. std::string arg;
  130. const std::string arg_prefix = "--";
  131. llama_sampling_params & sparams = params.sparams;
  132. for (int i = 1; i < argc; i++) {
  133. arg = argv[i];
  134. if (arg.compare(0, arg_prefix.size(), arg_prefix) == 0) {
  135. std::replace(arg.begin(), arg.end(), '_', '-');
  136. }
  137. if (arg == "-s" || arg == "--seed") {
  138. if (++i >= argc) {
  139. invalid_param = true;
  140. break;
  141. }
  142. params.seed = std::stoul(argv[i]);
  143. } else if (arg == "-t" || arg == "--threads") {
  144. if (++i >= argc) {
  145. invalid_param = true;
  146. break;
  147. }
  148. params.n_threads = std::stoi(argv[i]);
  149. if (params.n_threads <= 0) {
  150. params.n_threads = std::thread::hardware_concurrency();
  151. }
  152. } else if (arg == "-tb" || arg == "--threads-batch") {
  153. if (++i >= argc) {
  154. invalid_param = true;
  155. break;
  156. }
  157. params.n_threads_batch = std::stoi(argv[i]);
  158. if (params.n_threads_batch <= 0) {
  159. params.n_threads_batch = std::thread::hardware_concurrency();
  160. }
  161. } else if (arg == "-td" || arg == "--threads-draft") {
  162. if (++i >= argc) {
  163. invalid_param = true;
  164. break;
  165. }
  166. params.n_threads_draft = std::stoi(argv[i]);
  167. if (params.n_threads_draft <= 0) {
  168. params.n_threads_draft = std::thread::hardware_concurrency();
  169. }
  170. } else if (arg == "-tbd" || arg == "--threads-batch-draft") {
  171. if (++i >= argc) {
  172. invalid_param = true;
  173. break;
  174. }
  175. params.n_threads_batch_draft = std::stoi(argv[i]);
  176. if (params.n_threads_batch_draft <= 0) {
  177. params.n_threads_batch_draft = std::thread::hardware_concurrency();
  178. }
  179. } else if (arg == "-p" || arg == "--prompt") {
  180. if (++i >= argc) {
  181. invalid_param = true;
  182. break;
  183. }
  184. params.prompt = argv[i];
  185. } else if (arg == "-e" || arg == "--escape") {
  186. params.escape = true;
  187. } else if (arg == "--prompt-cache") {
  188. if (++i >= argc) {
  189. invalid_param = true;
  190. break;
  191. }
  192. params.path_prompt_cache = argv[i];
  193. } else if (arg == "--prompt-cache-all") {
  194. params.prompt_cache_all = true;
  195. } else if (arg == "--prompt-cache-ro") {
  196. params.prompt_cache_ro = true;
  197. } else if (arg == "-bf" || arg == "--binary-file") {
  198. if (++i >= argc) {
  199. invalid_param = true;
  200. break;
  201. }
  202. std::ifstream file(argv[i], std::ios::binary);
  203. if (!file) {
  204. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  205. invalid_param = true;
  206. break;
  207. }
  208. // store the external file name in params
  209. params.prompt_file = argv[i];
  210. std::ostringstream ss;
  211. ss << file.rdbuf();
  212. params.prompt = ss.str();
  213. fprintf(stderr, "Read %zu bytes from binary file %s\n", params.prompt.size(), argv[i]);
  214. } else if (arg == "-f" || arg == "--file") {
  215. if (++i >= argc) {
  216. invalid_param = true;
  217. break;
  218. }
  219. std::ifstream file(argv[i]);
  220. if (!file) {
  221. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  222. invalid_param = true;
  223. break;
  224. }
  225. // store the external file name in params
  226. params.prompt_file = argv[i];
  227. std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(params.prompt));
  228. if (!params.prompt.empty() && params.prompt.back() == '\n') {
  229. params.prompt.pop_back();
  230. }
  231. } else if (arg == "-n" || arg == "--n-predict") {
  232. if (++i >= argc) {
  233. invalid_param = true;
  234. break;
  235. }
  236. params.n_predict = std::stoi(argv[i]);
  237. } else if (arg == "--top-k") {
  238. if (++i >= argc) {
  239. invalid_param = true;
  240. break;
  241. }
  242. sparams.top_k = std::stoi(argv[i]);
  243. } else if (arg == "-c" || arg == "--ctx-size") {
  244. if (++i >= argc) {
  245. invalid_param = true;
  246. break;
  247. }
  248. params.n_ctx = std::stoi(argv[i]);
  249. } else if (arg == "--grp-attn-n" || arg == "-gan") {
  250. if (++i >= argc) {
  251. invalid_param = true;
  252. break;
  253. }
  254. params.grp_attn_n = std::stoi(argv[i]);
  255. } else if (arg == "--grp-attn-w" || arg == "-gaw") {
  256. if (++i >= argc) {
  257. invalid_param = true;
  258. break;
  259. }
  260. params.grp_attn_w = std::stoi(argv[i]);
  261. } else if (arg == "--rope-freq-base") {
  262. if (++i >= argc) {
  263. invalid_param = true;
  264. break;
  265. }
  266. params.rope_freq_base = std::stof(argv[i]);
  267. } else if (arg == "--rope-freq-scale") {
  268. if (++i >= argc) {
  269. invalid_param = true;
  270. break;
  271. }
  272. params.rope_freq_scale = std::stof(argv[i]);
  273. } else if (arg == "--rope-scaling") {
  274. if (++i >= argc) {
  275. invalid_param = true;
  276. break;
  277. }
  278. std::string value(argv[i]);
  279. /**/ if (value == "none") { params.rope_scaling_type = LLAMA_ROPE_SCALING_NONE; }
  280. else if (value == "linear") { params.rope_scaling_type = LLAMA_ROPE_SCALING_LINEAR; }
  281. else if (value == "yarn") { params.rope_scaling_type = LLAMA_ROPE_SCALING_YARN; }
  282. else { invalid_param = true; break; }
  283. } else if (arg == "--rope-scale") {
  284. if (++i >= argc) {
  285. invalid_param = true;
  286. break;
  287. }
  288. params.rope_freq_scale = 1.0f/std::stof(argv[i]);
  289. } else if (arg == "--yarn-orig-ctx") {
  290. if (++i >= argc) {
  291. invalid_param = true;
  292. break;
  293. }
  294. params.yarn_orig_ctx = std::stoi(argv[i]);
  295. } else if (arg == "--yarn-ext-factor") {
  296. if (++i >= argc) {
  297. invalid_param = true;
  298. break;
  299. }
  300. params.yarn_ext_factor = std::stof(argv[i]);
  301. } else if (arg == "--yarn-attn-factor") {
  302. if (++i >= argc) {
  303. invalid_param = true;
  304. break;
  305. }
  306. params.yarn_attn_factor = std::stof(argv[i]);
  307. } else if (arg == "--yarn-beta-fast") {
  308. if (++i >= argc) {
  309. invalid_param = true;
  310. break;
  311. }
  312. params.yarn_beta_fast = std::stof(argv[i]);
  313. } else if (arg == "--yarn-beta-slow") {
  314. if (++i >= argc) {
  315. invalid_param = true;
  316. break;
  317. }
  318. params.yarn_beta_slow = std::stof(argv[i]);
  319. } else if (arg == "--samplers") {
  320. if (++i >= argc) {
  321. invalid_param = true;
  322. break;
  323. }
  324. sparams.samplers_sequence = parse_samplers_input(argv[i]);
  325. } else if (arg == "--sampling-seq") {
  326. if (++i >= argc) {
  327. invalid_param = true;
  328. break;
  329. }
  330. sparams.samplers_sequence = argv[i];
  331. } else if (arg == "--top-p") {
  332. if (++i >= argc) {
  333. invalid_param = true;
  334. break;
  335. }
  336. sparams.top_p = std::stof(argv[i]);
  337. } else if (arg == "--min-p") {
  338. if (++i >= argc) {
  339. invalid_param = true;
  340. break;
  341. }
  342. sparams.min_p = std::stof(argv[i]);
  343. } else if (arg == "--temp") {
  344. if (++i >= argc) {
  345. invalid_param = true;
  346. break;
  347. }
  348. sparams.temp = std::stof(argv[i]);
  349. sparams.temp = std::max(sparams.temp, 0.0f);
  350. } else if (arg == "--tfs") {
  351. if (++i >= argc) {
  352. invalid_param = true;
  353. break;
  354. }
  355. sparams.tfs_z = std::stof(argv[i]);
  356. } else if (arg == "--typical") {
  357. if (++i >= argc) {
  358. invalid_param = true;
  359. break;
  360. }
  361. sparams.typical_p = std::stof(argv[i]);
  362. } else if (arg == "--repeat-last-n") {
  363. if (++i >= argc) {
  364. invalid_param = true;
  365. break;
  366. }
  367. sparams.penalty_last_n = std::stoi(argv[i]);
  368. sparams.n_prev = std::max(sparams.n_prev, sparams.penalty_last_n);
  369. } else if (arg == "--repeat-penalty") {
  370. if (++i >= argc) {
  371. invalid_param = true;
  372. break;
  373. }
  374. sparams.penalty_repeat = std::stof(argv[i]);
  375. } else if (arg == "--frequency-penalty") {
  376. if (++i >= argc) {
  377. invalid_param = true;
  378. break;
  379. }
  380. sparams.penalty_freq = std::stof(argv[i]);
  381. } else if (arg == "--presence-penalty") {
  382. if (++i >= argc) {
  383. invalid_param = true;
  384. break;
  385. }
  386. sparams.penalty_present = std::stof(argv[i]);
  387. } else if (arg == "--mirostat") {
  388. if (++i >= argc) {
  389. invalid_param = true;
  390. break;
  391. }
  392. sparams.mirostat = std::stoi(argv[i]);
  393. } else if (arg == "--mirostat-lr") {
  394. if (++i >= argc) {
  395. invalid_param = true;
  396. break;
  397. }
  398. sparams.mirostat_eta = std::stof(argv[i]);
  399. } else if (arg == "--mirostat-ent") {
  400. if (++i >= argc) {
  401. invalid_param = true;
  402. break;
  403. }
  404. sparams.mirostat_tau = std::stof(argv[i]);
  405. } else if (arg == "--cfg-negative-prompt") {
  406. if (++i >= argc) {
  407. invalid_param = true;
  408. break;
  409. }
  410. sparams.cfg_negative_prompt = argv[i];
  411. } else if (arg == "--cfg-negative-prompt-file") {
  412. if (++i >= argc) {
  413. invalid_param = true;
  414. break;
  415. }
  416. std::ifstream file(argv[i]);
  417. if (!file) {
  418. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  419. invalid_param = true;
  420. break;
  421. }
  422. std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(sparams.cfg_negative_prompt));
  423. if (!sparams.cfg_negative_prompt.empty() && sparams.cfg_negative_prompt.back() == '\n') {
  424. sparams.cfg_negative_prompt.pop_back();
  425. }
  426. } else if (arg == "--cfg-scale") {
  427. if (++i >= argc) {
  428. invalid_param = true;
  429. break;
  430. }
  431. sparams.cfg_scale = std::stof(argv[i]);
  432. } else if (arg == "-b" || arg == "--batch-size") {
  433. if (++i >= argc) {
  434. invalid_param = true;
  435. break;
  436. }
  437. params.n_batch = std::stoi(argv[i]);
  438. } else if (arg == "--keep") {
  439. if (++i >= argc) {
  440. invalid_param = true;
  441. break;
  442. }
  443. params.n_keep = std::stoi(argv[i]);
  444. } else if (arg == "--draft") {
  445. if (++i >= argc) {
  446. invalid_param = true;
  447. break;
  448. }
  449. params.n_draft = std::stoi(argv[i]);
  450. } else if (arg == "--chunks") {
  451. if (++i >= argc) {
  452. invalid_param = true;
  453. break;
  454. }
  455. params.n_chunks = std::stoi(argv[i]);
  456. } else if (arg == "-np" || arg == "--parallel") {
  457. if (++i >= argc) {
  458. invalid_param = true;
  459. break;
  460. }
  461. params.n_parallel = std::stoi(argv[i]);
  462. } else if (arg == "-ns" || arg == "--sequences") {
  463. if (++i >= argc) {
  464. invalid_param = true;
  465. break;
  466. }
  467. params.n_sequences = std::stoi(argv[i]);
  468. } else if (arg == "--p-accept" || arg == "-pa") {
  469. if (++i >= argc) {
  470. invalid_param = true;
  471. break;
  472. }
  473. params.p_accept = std::stof(argv[i]);
  474. } else if (arg == "--p-split" || arg == "-ps") {
  475. if (++i >= argc) {
  476. invalid_param = true;
  477. break;
  478. }
  479. params.p_split = std::stof(argv[i]);
  480. } else if (arg == "-m" || arg == "--model") {
  481. if (++i >= argc) {
  482. invalid_param = true;
  483. break;
  484. }
  485. params.model = argv[i];
  486. } else if (arg == "-md" || arg == "--model-draft") {
  487. if (++i >= argc) {
  488. invalid_param = true;
  489. break;
  490. }
  491. params.model_draft = argv[i];
  492. } else if (arg == "-a" || arg == "--alias") {
  493. if (++i >= argc) {
  494. invalid_param = true;
  495. break;
  496. }
  497. params.model_alias = argv[i];
  498. } else if (arg == "--lora") {
  499. if (++i >= argc) {
  500. invalid_param = true;
  501. break;
  502. }
  503. params.lora_adapter.push_back(std::make_tuple(argv[i], 1.0f));
  504. params.use_mmap = false;
  505. } else if (arg == "--lora-scaled") {
  506. if (++i >= argc) {
  507. invalid_param = true;
  508. break;
  509. }
  510. const char * lora_adapter = argv[i];
  511. if (++i >= argc) {
  512. invalid_param = true;
  513. break;
  514. }
  515. params.lora_adapter.push_back(std::make_tuple(lora_adapter, std::stof(argv[i])));
  516. params.use_mmap = false;
  517. } else if (arg == "--lora-base") {
  518. if (++i >= argc) {
  519. invalid_param = true;
  520. break;
  521. }
  522. params.lora_base = argv[i];
  523. } else if (arg == "--mmproj") {
  524. if (++i >= argc) {
  525. invalid_param = true;
  526. break;
  527. }
  528. params.mmproj = argv[i];
  529. } else if (arg == "--image") {
  530. if (++i >= argc) {
  531. invalid_param = true;
  532. break;
  533. }
  534. params.image = argv[i];
  535. } else if (arg == "-i" || arg == "--interactive") {
  536. params.interactive = true;
  537. } else if (arg == "--embedding") {
  538. params.embedding = true;
  539. } else if (arg == "--interactive-first") {
  540. params.interactive_first = true;
  541. } else if (arg == "-ins" || arg == "--instruct") {
  542. params.instruct = true;
  543. } else if (arg == "-cml" || arg == "--chatml") {
  544. params.chatml = true;
  545. } else if (arg == "--infill") {
  546. params.infill = true;
  547. } else if (arg == "-dkvc" || arg == "--dump-kv-cache") {
  548. params.dump_kv_cache = true;
  549. } else if (arg == "-nkvo" || arg == "--no-kv-offload") {
  550. params.no_kv_offload = true;
  551. } else if (arg == "-ctk" || arg == "--cache-type-k") {
  552. params.cache_type_k = argv[++i];
  553. } else if (arg == "-ctv" || arg == "--cache-type-v") {
  554. params.cache_type_v = argv[++i];
  555. } else if (arg == "--multiline-input") {
  556. params.multiline_input = true;
  557. } else if (arg == "--simple-io") {
  558. params.simple_io = true;
  559. } else if (arg == "-cb" || arg == "--cont-batching") {
  560. params.cont_batching = true;
  561. } else if (arg == "--color") {
  562. params.use_color = true;
  563. } else if (arg == "--mlock") {
  564. params.use_mlock = true;
  565. } else if (arg == "--gpu-layers" || arg == "-ngl" || arg == "--n-gpu-layers") {
  566. if (++i >= argc) {
  567. invalid_param = true;
  568. break;
  569. }
  570. params.n_gpu_layers = std::stoi(argv[i]);
  571. #ifndef LLAMA_SUPPORTS_GPU_OFFLOAD
  572. fprintf(stderr, "warning: not compiled with GPU offload support, --n-gpu-layers option will be ignored\n");
  573. fprintf(stderr, "warning: see main README.md for information on enabling GPU BLAS support\n");
  574. #endif
  575. } else if (arg == "--gpu-layers-draft" || arg == "-ngld" || arg == "--n-gpu-layers-draft") {
  576. if (++i >= argc) {
  577. invalid_param = true;
  578. break;
  579. }
  580. params.n_gpu_layers_draft = std::stoi(argv[i]);
  581. #ifndef LLAMA_SUPPORTS_GPU_OFFLOAD
  582. fprintf(stderr, "warning: not compiled with GPU offload support, --n-gpu-layers-draft option will be ignored\n");
  583. fprintf(stderr, "warning: see main README.md for information on enabling GPU BLAS support\n");
  584. #endif
  585. } else if (arg == "--main-gpu" || arg == "-mg") {
  586. if (++i >= argc) {
  587. invalid_param = true;
  588. break;
  589. }
  590. params.main_gpu = std::stoi(argv[i]);
  591. #ifndef GGML_USE_CUBLAS_SYCL
  592. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS/SYCL. Setting the main GPU has no effect.\n");
  593. #endif // GGML_USE_CUBLAS_SYCL
  594. } else if (arg == "--split-mode" || arg == "-sm") {
  595. if (++i >= argc) {
  596. invalid_param = true;
  597. break;
  598. }
  599. std::string arg_next = argv[i];
  600. if (arg_next == "none") {
  601. params.split_mode = LLAMA_SPLIT_NONE;
  602. } else if (arg_next == "layer") {
  603. params.split_mode = LLAMA_SPLIT_LAYER;
  604. } else if (arg_next == "row") {
  605. params.split_mode = LLAMA_SPLIT_ROW;
  606. } else {
  607. invalid_param = true;
  608. break;
  609. }
  610. #ifndef GGML_USE_CUBLAS_SYCL
  611. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS/SYCL. Setting the split mode has no effect.\n");
  612. #endif // GGML_USE_CUBLAS_SYCL
  613. } else if (arg == "--tensor-split" || arg == "-ts") {
  614. if (++i >= argc) {
  615. invalid_param = true;
  616. break;
  617. }
  618. std::string arg_next = argv[i];
  619. // split string by , and /
  620. const std::regex regex{R"([,/]+)"};
  621. std::sregex_token_iterator it{arg_next.begin(), arg_next.end(), regex, -1};
  622. std::vector<std::string> split_arg{it, {}};
  623. if (split_arg.size() >= LLAMA_MAX_DEVICES) {
  624. invalid_param = true;
  625. break;
  626. }
  627. for (size_t i = 0; i < LLAMA_MAX_DEVICES; ++i) {
  628. if (i < split_arg.size()) {
  629. params.tensor_split[i] = std::stof(split_arg[i]);
  630. } else {
  631. params.tensor_split[i] = 0.0f;
  632. }
  633. }
  634. #ifndef GGML_USE_CUBLAS_SYCL
  635. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS/SYCL. Setting a tensor split has no effect.\n");
  636. #endif // GGML_USE_CUBLAS_SYCL
  637. } else if (arg == "--no-mmap") {
  638. params.use_mmap = false;
  639. } else if (arg == "--numa") {
  640. params.numa = true;
  641. } else if (arg == "--verbose-prompt") {
  642. params.verbose_prompt = true;
  643. } else if (arg == "--no-display-prompt") {
  644. params.display_prompt = false;
  645. } else if (arg == "-r" || arg == "--reverse-prompt") {
  646. if (++i >= argc) {
  647. invalid_param = true;
  648. break;
  649. }
  650. params.antiprompt.push_back(argv[i]);
  651. } else if (arg == "-ld" || arg == "--logdir") {
  652. if (++i >= argc) {
  653. invalid_param = true;
  654. break;
  655. }
  656. params.logdir = argv[i];
  657. if (params.logdir.back() != DIRECTORY_SEPARATOR) {
  658. params.logdir += DIRECTORY_SEPARATOR;
  659. }
  660. } else if (arg == "--save-all-logits" || arg == "--kl-divergence-base") {
  661. if (++i >= argc) {
  662. invalid_param = true;
  663. break;
  664. }
  665. params.logits_file = argv[i];
  666. } else if (arg == "--perplexity" || arg == "--all-logits") {
  667. params.logits_all = true;
  668. } else if (arg == "--ppl-stride") {
  669. if (++i >= argc) {
  670. invalid_param = true;
  671. break;
  672. }
  673. params.ppl_stride = std::stoi(argv[i]);
  674. } else if (arg == "-ptc" || arg == "--print-token-count") {
  675. if (++i >= argc) {
  676. invalid_param = true;
  677. break;
  678. }
  679. params.n_print = std::stoi(argv[i]);
  680. } else if (arg == "--ppl-output-type") {
  681. if (++i >= argc) {
  682. invalid_param = true;
  683. break;
  684. }
  685. params.ppl_output_type = std::stoi(argv[i]);
  686. } else if (arg == "--hellaswag") {
  687. params.hellaswag = true;
  688. } else if (arg == "--hellaswag-tasks") {
  689. if (++i >= argc) {
  690. invalid_param = true;
  691. break;
  692. }
  693. params.hellaswag_tasks = std::stoi(argv[i]);
  694. } else if (arg == "--winogrande") {
  695. params.winogrande = true;
  696. } else if (arg == "--winogrande-tasks") {
  697. if (++i >= argc) {
  698. invalid_param = true;
  699. break;
  700. }
  701. params.winogrande_tasks = std::stoi(argv[i]);
  702. } else if (arg == "--multiple-choice") {
  703. params.multiple_choice = true;
  704. } else if (arg == "--multiple-choice-tasks") {
  705. if (++i >= argc) {
  706. invalid_param = true;
  707. break;
  708. }
  709. params.multiple_choice_tasks = std::stoi(argv[i]);
  710. } else if (arg == "--kl-divergence") {
  711. params.kl_divergence = true;
  712. } else if (arg == "--ignore-eos") {
  713. params.ignore_eos = true;
  714. } else if (arg == "--no-penalize-nl") {
  715. sparams.penalize_nl = false;
  716. } else if (arg == "-l" || arg == "--logit-bias") {
  717. if (++i >= argc) {
  718. invalid_param = true;
  719. break;
  720. }
  721. std::stringstream ss(argv[i]);
  722. llama_token key;
  723. char sign;
  724. std::string value_str;
  725. try {
  726. if (ss >> key && ss >> sign && std::getline(ss, value_str) && (sign == '+' || sign == '-')) {
  727. sparams.logit_bias[key] = std::stof(value_str) * ((sign == '-') ? -1.0f : 1.0f);
  728. } else {
  729. throw std::exception();
  730. }
  731. } catch (const std::exception&) {
  732. invalid_param = true;
  733. break;
  734. }
  735. } else if (arg == "-h" || arg == "--help") {
  736. return false;
  737. } else if (arg == "--version") {
  738. fprintf(stderr, "version: %d (%s)\n", LLAMA_BUILD_NUMBER, LLAMA_COMMIT);
  739. fprintf(stderr, "built with %s for %s\n", LLAMA_COMPILER, LLAMA_BUILD_TARGET);
  740. exit(0);
  741. } else if (arg == "--random-prompt") {
  742. params.random_prompt = true;
  743. } else if (arg == "--in-prefix-bos") {
  744. params.input_prefix_bos = true;
  745. } else if (arg == "--in-prefix") {
  746. if (++i >= argc) {
  747. invalid_param = true;
  748. break;
  749. }
  750. params.input_prefix = argv[i];
  751. } else if (arg == "--in-suffix") {
  752. if (++i >= argc) {
  753. invalid_param = true;
  754. break;
  755. }
  756. params.input_suffix = argv[i];
  757. } else if (arg == "--grammar") {
  758. if (++i >= argc) {
  759. invalid_param = true;
  760. break;
  761. }
  762. sparams.grammar = argv[i];
  763. } else if (arg == "--grammar-file") {
  764. if (++i >= argc) {
  765. invalid_param = true;
  766. break;
  767. }
  768. std::ifstream file(argv[i]);
  769. if (!file) {
  770. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  771. invalid_param = true;
  772. break;
  773. }
  774. std::copy(
  775. std::istreambuf_iterator<char>(file),
  776. std::istreambuf_iterator<char>(),
  777. std::back_inserter(sparams.grammar)
  778. );
  779. } else if (arg == "--override-kv") {
  780. if (++i >= argc) {
  781. invalid_param = true;
  782. break;
  783. }
  784. char * sep = strchr(argv[i], '=');
  785. if (sep == nullptr || sep - argv[i] >= 128) {
  786. fprintf(stderr, "error: Malformed KV override: %s\n", argv[i]);
  787. invalid_param = true;
  788. break;
  789. }
  790. struct llama_model_kv_override kvo;
  791. std::strncpy(kvo.key, argv[i], sep - argv[i]);
  792. kvo.key[sep - argv[i]] = 0;
  793. sep++;
  794. if (strncmp(sep, "int:", 4) == 0) {
  795. sep += 4;
  796. kvo.tag = LLAMA_KV_OVERRIDE_INT;
  797. kvo.int_value = std::atol(sep);
  798. } else if (strncmp(sep, "float:", 6) == 0) {
  799. sep += 6;
  800. kvo.tag = LLAMA_KV_OVERRIDE_FLOAT;
  801. kvo.float_value = std::atof(sep);
  802. } else if (strncmp(sep, "bool:", 5) == 0) {
  803. sep += 5;
  804. kvo.tag = LLAMA_KV_OVERRIDE_BOOL;
  805. if (std::strcmp(sep, "true") == 0) {
  806. kvo.bool_value = true;
  807. } else if (std::strcmp(sep, "false") == 0) {
  808. kvo.bool_value = false;
  809. } else {
  810. fprintf(stderr, "error: Invalid boolean value for KV override: %s\n", argv[i]);
  811. invalid_param = true;
  812. break;
  813. }
  814. } else {
  815. fprintf(stderr, "error: Invalid type for KV override: %s\n", argv[i]);
  816. invalid_param = true;
  817. break;
  818. }
  819. params.kv_overrides.push_back(kvo);
  820. #ifndef LOG_DISABLE_LOGS
  821. // Parse args for logging parameters
  822. } else if ( log_param_single_parse( argv[i] ) ) {
  823. // Do nothing, log_param_single_parse automatically does it's thing
  824. // and returns if a match was found and parsed.
  825. } else if ( log_param_pair_parse( /*check_but_dont_parse*/ true, argv[i] ) ) {
  826. // We have a matching known parameter requiring an argument,
  827. // now we need to check if there is anything after this argv
  828. // and flag invalid_param or parse it.
  829. if (++i >= argc) {
  830. invalid_param = true;
  831. break;
  832. }
  833. if( !log_param_pair_parse( /*check_but_dont_parse*/ false, argv[i-1], argv[i]) ) {
  834. invalid_param = true;
  835. break;
  836. }
  837. // End of Parse args for logging parameters
  838. #endif // LOG_DISABLE_LOGS
  839. } else {
  840. throw std::invalid_argument("error: unknown argument: " + arg);
  841. }
  842. }
  843. if (invalid_param) {
  844. throw std::invalid_argument("error: invalid parameter for argument: " + arg);
  845. }
  846. if (params.prompt_cache_all &&
  847. (params.interactive || params.interactive_first ||
  848. params.instruct)) {
  849. throw std::invalid_argument("error: --prompt-cache-all not supported in interactive mode yet\n");
  850. }
  851. if (params.escape) {
  852. process_escapes(params.prompt);
  853. process_escapes(params.input_prefix);
  854. process_escapes(params.input_suffix);
  855. process_escapes(sparams.cfg_negative_prompt);
  856. for (auto & antiprompt : params.antiprompt) {
  857. process_escapes(antiprompt);
  858. }
  859. }
  860. if (!params.kv_overrides.empty()) {
  861. params.kv_overrides.emplace_back(llama_model_kv_override());
  862. params.kv_overrides.back().key[0] = 0;
  863. }
  864. return true;
  865. }
  866. void gpt_print_usage(int /*argc*/, char ** argv, const gpt_params & params) {
  867. const llama_sampling_params & sparams = params.sparams;
  868. printf("\n");
  869. printf("usage: %s [options]\n", argv[0]);
  870. printf("\n");
  871. printf("options:\n");
  872. printf(" -h, --help show this help message and exit\n");
  873. printf(" --version show version and build info\n");
  874. printf(" -i, --interactive run in interactive mode\n");
  875. printf(" --interactive-first run in interactive mode and wait for input right away\n");
  876. printf(" -ins, --instruct run in instruction mode (use with Alpaca models)\n");
  877. printf(" -cml, --chatml run in chatml mode (use with ChatML-compatible models)\n");
  878. printf(" --multiline-input allows you to write or paste multiple lines without ending each in '\\'\n");
  879. printf(" -r PROMPT, --reverse-prompt PROMPT\n");
  880. printf(" halt generation at PROMPT, return control in interactive mode\n");
  881. printf(" (can be specified more than once for multiple prompts).\n");
  882. printf(" --color colorise output to distinguish prompt and user input from generations\n");
  883. printf(" -s SEED, --seed SEED RNG seed (default: -1, use random seed for < 0)\n");
  884. printf(" -t N, --threads N number of threads to use during generation (default: %d)\n", params.n_threads);
  885. printf(" -tb N, --threads-batch N\n");
  886. printf(" number of threads to use during batch and prompt processing (default: same as --threads)\n");
  887. printf(" -td N, --threads-draft N");
  888. printf(" number of threads to use during generation (default: same as --threads)");
  889. printf(" -tbd N, --threads-batch-draft N\n");
  890. printf(" number of threads to use during batch and prompt processing (default: same as --threads-draft)\n");
  891. printf(" -p PROMPT, --prompt PROMPT\n");
  892. printf(" prompt to start generation with (default: empty)\n");
  893. printf(" -e, --escape process prompt escapes sequences (\\n, \\r, \\t, \\', \\\", \\\\)\n");
  894. printf(" --prompt-cache FNAME file to cache prompt state for faster startup (default: none)\n");
  895. printf(" --prompt-cache-all if specified, saves user input and generations to cache as well.\n");
  896. printf(" not supported with --interactive or other interactive options\n");
  897. printf(" --prompt-cache-ro if specified, uses the prompt cache but does not update it.\n");
  898. printf(" --random-prompt start with a randomized prompt.\n");
  899. printf(" --in-prefix-bos prefix BOS to user inputs, preceding the `--in-prefix` string\n");
  900. printf(" --in-prefix STRING string to prefix user inputs with (default: empty)\n");
  901. printf(" --in-suffix STRING string to suffix after user inputs with (default: empty)\n");
  902. printf(" -f FNAME, --file FNAME\n");
  903. printf(" prompt file to start generation.\n");
  904. printf(" -bf FNAME, --binary-file FNAME\n");
  905. printf(" binary file containing multiple choice tasks.\n");
  906. printf(" -n N, --n-predict N number of tokens to predict (default: %d, -1 = infinity, -2 = until context filled)\n", params.n_predict);
  907. printf(" -c N, --ctx-size N size of the prompt context (default: %d, 0 = loaded from model)\n", params.n_ctx);
  908. printf(" -b N, --batch-size N batch size for prompt processing (default: %d)\n", params.n_batch);
  909. printf(" --samplers samplers that will be used for generation in the order, separated by \';\', for example: \"top_k;tfs;typical;top_p;min_p;temp\"\n");
  910. printf(" --sampling-seq simplified sequence for samplers that will be used (default: %s)\n", sparams.samplers_sequence.c_str());
  911. printf(" --top-k N top-k sampling (default: %d, 0 = disabled)\n", sparams.top_k);
  912. printf(" --top-p N top-p sampling (default: %.1f, 1.0 = disabled)\n", (double)sparams.top_p);
  913. printf(" --min-p N min-p sampling (default: %.1f, 0.0 = disabled)\n", (double)sparams.min_p);
  914. printf(" --tfs N tail free sampling, parameter z (default: %.1f, 1.0 = disabled)\n", (double)sparams.tfs_z);
  915. printf(" --typical N locally typical sampling, parameter p (default: %.1f, 1.0 = disabled)\n", (double)sparams.typical_p);
  916. printf(" --repeat-last-n N last n tokens to consider for penalize (default: %d, 0 = disabled, -1 = ctx_size)\n", sparams.penalty_last_n);
  917. printf(" --repeat-penalty N penalize repeat sequence of tokens (default: %.1f, 1.0 = disabled)\n", (double)sparams.penalty_repeat);
  918. printf(" --presence-penalty N repeat alpha presence penalty (default: %.1f, 0.0 = disabled)\n", (double)sparams.penalty_present);
  919. printf(" --frequency-penalty N repeat alpha frequency penalty (default: %.1f, 0.0 = disabled)\n", (double)sparams.penalty_freq);
  920. printf(" --mirostat N use Mirostat sampling.\n");
  921. printf(" Top K, Nucleus, Tail Free and Locally Typical samplers are ignored if used.\n");
  922. printf(" (default: %d, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)\n", sparams.mirostat);
  923. printf(" --mirostat-lr N Mirostat learning rate, parameter eta (default: %.1f)\n", (double)sparams.mirostat_eta);
  924. printf(" --mirostat-ent N Mirostat target entropy, parameter tau (default: %.1f)\n", (double)sparams.mirostat_tau);
  925. printf(" -l TOKEN_ID(+/-)BIAS, --logit-bias TOKEN_ID(+/-)BIAS\n");
  926. printf(" modifies the likelihood of token appearing in the completion,\n");
  927. printf(" i.e. `--logit-bias 15043+1` to increase likelihood of token ' Hello',\n");
  928. printf(" or `--logit-bias 15043-1` to decrease likelihood of token ' Hello'\n");
  929. printf(" --grammar GRAMMAR BNF-like grammar to constrain generations (see samples in grammars/ dir)\n");
  930. printf(" --grammar-file FNAME file to read grammar from\n");
  931. printf(" --cfg-negative-prompt PROMPT\n");
  932. printf(" negative prompt to use for guidance. (default: empty)\n");
  933. printf(" --cfg-negative-prompt-file FNAME\n");
  934. printf(" negative prompt file to use for guidance. (default: empty)\n");
  935. printf(" --cfg-scale N strength of guidance (default: %f, 1.0 = disable)\n", sparams.cfg_scale);
  936. printf(" --rope-scaling {none,linear,yarn}\n");
  937. printf(" RoPE frequency scaling method, defaults to linear unless specified by the model\n");
  938. printf(" --rope-scale N RoPE context scaling factor, expands context by a factor of N\n");
  939. printf(" --rope-freq-base N RoPE base frequency, used by NTK-aware scaling (default: loaded from model)\n");
  940. printf(" --rope-freq-scale N RoPE frequency scaling factor, expands context by a factor of 1/N\n");
  941. printf(" --yarn-orig-ctx N YaRN: original context size of model (default: 0 = model training context size)\n");
  942. printf(" --yarn-ext-factor N YaRN: extrapolation mix factor (default: 1.0, 0.0 = full interpolation)\n");
  943. printf(" --yarn-attn-factor N YaRN: scale sqrt(t) or attention magnitude (default: 1.0)\n");
  944. printf(" --yarn-beta-slow N YaRN: high correction dim or alpha (default: %.1f)\n", params.yarn_beta_slow);
  945. printf(" --yarn-beta-fast N YaRN: low correction dim or beta (default: %.1f)\n", params.yarn_beta_fast);
  946. printf(" --ignore-eos ignore end of stream token and continue generating (implies --logit-bias 2-inf)\n");
  947. printf(" --no-penalize-nl do not penalize newline token\n");
  948. printf(" --temp N temperature (default: %.1f)\n", (double)sparams.temp);
  949. printf(" --logits-all return logits for all tokens in the batch (default: disabled)\n");
  950. printf(" --hellaswag compute HellaSwag score over random tasks from datafile supplied with -f\n");
  951. printf(" --hellaswag-tasks N number of tasks to use when computing the HellaSwag score (default: %zu)\n", params.hellaswag_tasks);
  952. printf(" --winogrande compute Winogrande score over random tasks from datafile supplied with -f\n");
  953. printf(" --winogrande-tasks N number of tasks to use when computing the Winogrande score (default: %zu)\n", params.winogrande_tasks);
  954. printf(" --multiple-choice compute multiple choice score over random tasks from datafile supplied with -f\n");
  955. printf(" --multiple-choice-tasks N number of tasks to use when computing the multiple choice score (default: %zu)\n", params.winogrande_tasks);
  956. printf(" --kl-divergence computes KL-divergence to logits provided via --kl-divergence-base");
  957. printf(" --keep N number of tokens to keep from the initial prompt (default: %d, -1 = all)\n", params.n_keep);
  958. printf(" --draft N number of tokens to draft for speculative decoding (default: %d)\n", params.n_draft);
  959. printf(" --chunks N max number of chunks to process (default: %d, -1 = all)\n", params.n_chunks);
  960. printf(" -np N, --parallel N number of parallel sequences to decode (default: %d)\n", params.n_parallel);
  961. printf(" -ns N, --sequences N number of sequences to decode (default: %d)\n", params.n_sequences);
  962. printf(" -pa N, --p-accept N speculative decoding accept probability (default: %.1f)\n", (double)params.p_accept);
  963. printf(" -ps N, --p-split N speculative decoding split probability (default: %.1f)\n", (double)params.p_split);
  964. printf(" -cb, --cont-batching enable continuous batching (a.k.a dynamic batching) (default: disabled)\n");
  965. printf(" --mmproj MMPROJ_FILE path to a multimodal projector file for LLaVA. see examples/llava/README.md\n");
  966. printf(" --image IMAGE_FILE path to an image file. use with multimodal models\n");
  967. if (llama_mlock_supported()) {
  968. printf(" --mlock force system to keep model in RAM rather than swapping or compressing\n");
  969. }
  970. if (llama_mmap_supported()) {
  971. printf(" --no-mmap do not memory-map model (slower load but may reduce pageouts if not using mlock)\n");
  972. }
  973. printf(" --numa attempt optimizations that help on some NUMA systems\n");
  974. printf(" if run without this previously, it is recommended to drop the system page cache before using this\n");
  975. printf(" see https://github.com/ggerganov/llama.cpp/issues/1437\n");
  976. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  977. printf(" -ngl N, --n-gpu-layers N\n");
  978. printf(" number of layers to store in VRAM\n");
  979. printf(" -ngld N, --n-gpu-layers-draft N\n");
  980. printf(" number of layers to store in VRAM for the draft model\n");
  981. printf(" -sm SPLIT_MODE, --split-mode SPLIT_MODE\n");
  982. printf(" how to split the model across multiple GPUs, one of:\n");
  983. printf(" - none: use one GPU only\n");
  984. printf(" - layer (default): split layers and KV across GPUs\n");
  985. printf(" - row: split rows across GPUs\n");
  986. printf(" -ts SPLIT, --tensor-split SPLIT\n");
  987. printf(" fraction of the model to offload to each GPU, comma-separated list of proportions, e.g. 3,1\n");
  988. printf(" -mg i, --main-gpu i the GPU to use for the model (with split-mode = none),\n");
  989. printf(" or for intermediate results and KV (with split-mode = row) (default: %d)\n", params.main_gpu);
  990. #endif // LLAMA_SUPPORTS_GPU_OFFLOAD
  991. printf(" --verbose-prompt print a verbose prompt before generation (default: %s)\n", params.verbose_prompt ? "true" : "false");
  992. printf(" --no-display-prompt don't print prompt at generation (default: %s)\n", !params.display_prompt ? "true" : "false");
  993. printf(" -gan N, --grp-attn-n N\n");
  994. printf(" group-attention factor (default: %d)\n", params.grp_attn_n);
  995. printf(" -gaw N, --grp-attn-w N\n");
  996. printf(" group-attention width (default: %.1f)\n", (double)params.grp_attn_w);
  997. printf(" -dkvc, --dump-kv-cache\n");
  998. printf(" verbose print of the KV cache\n");
  999. printf(" -nkvo, --no-kv-offload\n");
  1000. printf(" disable KV offload\n");
  1001. printf(" -ctk TYPE, --cache-type-k TYPE\n");
  1002. printf(" KV cache data type for K (default: %s)\n", params.cache_type_k.c_str());
  1003. printf(" -ctv TYPE, --cache-type-v TYPE\n");
  1004. printf(" KV cache data type for V (default: %s)\n", params.cache_type_v.c_str());
  1005. printf(" --simple-io use basic IO for better compatibility in subprocesses and limited consoles\n");
  1006. printf(" --lora FNAME apply LoRA adapter (implies --no-mmap)\n");
  1007. printf(" --lora-scaled FNAME S apply LoRA adapter with user defined scaling S (implies --no-mmap)\n");
  1008. printf(" --lora-base FNAME optional model to use as a base for the layers modified by the LoRA adapter\n");
  1009. printf(" -m FNAME, --model FNAME\n");
  1010. printf(" model path (default: %s)\n", params.model.c_str());
  1011. printf(" -md FNAME, --model-draft FNAME\n");
  1012. printf(" draft model for speculative decoding\n");
  1013. printf(" -ld LOGDIR, --logdir LOGDIR\n");
  1014. printf(" path under which to save YAML logs (no logging if unset)\n");
  1015. printf(" --override-kv KEY=TYPE:VALUE\n");
  1016. printf(" advanced option to override model metadata by key. may be specified multiple times.\n");
  1017. printf(" types: int, float, bool. example: --override-kv tokenizer.ggml.add_bos_token=bool:false\n");
  1018. printf(" -ptc N, --print-token-count N\n");
  1019. printf(" print token count every N tokens (default: %d)\n", params.n_print);
  1020. printf("\n");
  1021. #ifndef LOG_DISABLE_LOGS
  1022. log_print_usage();
  1023. #endif // LOG_DISABLE_LOGS
  1024. }
  1025. std::string get_system_info(const gpt_params & params) {
  1026. std::ostringstream os;
  1027. os << "system_info: n_threads = " << params.n_threads;
  1028. if (params.n_threads_batch != -1) {
  1029. os << " (n_threads_batch = " << params.n_threads_batch << ")";
  1030. }
  1031. os << " / " << std::thread::hardware_concurrency() << " | " << llama_print_system_info();
  1032. return os.str();
  1033. }
  1034. std::string gpt_random_prompt(std::mt19937 & rng) {
  1035. const int r = rng() % 10;
  1036. switch (r) {
  1037. case 0: return "So";
  1038. case 1: return "Once upon a time";
  1039. case 2: return "When";
  1040. case 3: return "The";
  1041. case 4: return "After";
  1042. case 5: return "If";
  1043. case 6: return "import";
  1044. case 7: return "He";
  1045. case 8: return "She";
  1046. case 9: return "They";
  1047. }
  1048. GGML_UNREACHABLE();
  1049. }
  1050. //
  1051. // String parsing
  1052. //
  1053. std::string parse_samplers_input(std::string input) {
  1054. std::string output = "";
  1055. // since samplers names are written multiple ways
  1056. // make it ready for both system names and input names
  1057. std::unordered_map<std::string, char> samplers_symbols {
  1058. {"top_k", 'k'},
  1059. {"top-k", 'k'},
  1060. {"top_p", 'p'},
  1061. {"top-p", 'p'},
  1062. {"nucleus", 'p'},
  1063. {"typical_p", 'y'},
  1064. {"typical-p", 'y'},
  1065. {"typical", 'y'},
  1066. {"min_p", 'm'},
  1067. {"min-p", 'm'},
  1068. {"tfs_z", 'f'},
  1069. {"tfs-z", 'f'},
  1070. {"tfs", 'f'},
  1071. {"temp", 't'},
  1072. {"temperature",'t'}
  1073. };
  1074. // expected format example: "temp;top_k;tfs_z;typical_p;top_p;min_p"
  1075. size_t separator = input.find(';');
  1076. while (separator != input.npos) {
  1077. std::string name = input.substr(0,separator);
  1078. input = input.substr(separator+1);
  1079. separator = input.find(';');
  1080. if (samplers_symbols.find(name) != samplers_symbols.end()) {
  1081. output += samplers_symbols[name];
  1082. }
  1083. }
  1084. if (samplers_symbols.find(input) != samplers_symbols.end()) {
  1085. output += samplers_symbols[input];
  1086. }
  1087. return output;
  1088. }
  1089. //
  1090. // Model utils
  1091. //
  1092. struct llama_model_params llama_model_params_from_gpt_params(const gpt_params & params) {
  1093. auto mparams = llama_model_default_params();
  1094. if (params.n_gpu_layers != -1) {
  1095. mparams.n_gpu_layers = params.n_gpu_layers;
  1096. }
  1097. mparams.main_gpu = params.main_gpu;
  1098. mparams.split_mode = params.split_mode;
  1099. mparams.tensor_split = params.tensor_split;
  1100. mparams.use_mmap = params.use_mmap;
  1101. mparams.use_mlock = params.use_mlock;
  1102. if (params.kv_overrides.empty()) {
  1103. mparams.kv_overrides = NULL;
  1104. } else {
  1105. GGML_ASSERT(params.kv_overrides.back().key[0] == 0 && "KV overrides not terminated with empty key");
  1106. mparams.kv_overrides = params.kv_overrides.data();
  1107. }
  1108. return mparams;
  1109. }
  1110. static ggml_type kv_cache_type_from_str(const std::string & s) {
  1111. if (s == "f32") {
  1112. return GGML_TYPE_F32;
  1113. }
  1114. if (s == "f16") {
  1115. return GGML_TYPE_F16;
  1116. }
  1117. if (s == "q8_0") {
  1118. return GGML_TYPE_Q8_0;
  1119. }
  1120. if (s == "q4_0") {
  1121. return GGML_TYPE_Q4_0;
  1122. }
  1123. if (s == "q4_1") {
  1124. return GGML_TYPE_Q4_1;
  1125. }
  1126. if (s == "q5_0") {
  1127. return GGML_TYPE_Q5_0;
  1128. }
  1129. if (s == "q5_1") {
  1130. return GGML_TYPE_Q5_1;
  1131. }
  1132. throw std::runtime_error("Invalid cache type: " + s);
  1133. }
  1134. struct llama_context_params llama_context_params_from_gpt_params(const gpt_params & params) {
  1135. auto cparams = llama_context_default_params();
  1136. cparams.n_ctx = params.n_ctx;
  1137. cparams.n_batch = params.n_batch;
  1138. cparams.n_threads = params.n_threads;
  1139. cparams.n_threads_batch = params.n_threads_batch == -1 ? params.n_threads : params.n_threads_batch;
  1140. cparams.mul_mat_q = params.mul_mat_q;
  1141. cparams.seed = params.seed;
  1142. cparams.logits_all = params.logits_all;
  1143. cparams.embedding = params.embedding;
  1144. cparams.rope_scaling_type = params.rope_scaling_type;
  1145. cparams.rope_freq_base = params.rope_freq_base;
  1146. cparams.rope_freq_scale = params.rope_freq_scale;
  1147. cparams.yarn_ext_factor = params.yarn_ext_factor;
  1148. cparams.yarn_attn_factor = params.yarn_attn_factor;
  1149. cparams.yarn_beta_fast = params.yarn_beta_fast;
  1150. cparams.yarn_beta_slow = params.yarn_beta_slow;
  1151. cparams.yarn_orig_ctx = params.yarn_orig_ctx;
  1152. cparams.offload_kqv = !params.no_kv_offload;
  1153. cparams.type_k = kv_cache_type_from_str(params.cache_type_k);
  1154. cparams.type_v = kv_cache_type_from_str(params.cache_type_v);
  1155. return cparams;
  1156. }
  1157. void llama_batch_clear(struct llama_batch & batch) {
  1158. batch.n_tokens = 0;
  1159. }
  1160. void llama_batch_add(
  1161. struct llama_batch & batch,
  1162. llama_token id,
  1163. llama_pos pos,
  1164. const std::vector<llama_seq_id> & seq_ids,
  1165. bool logits) {
  1166. batch.token [batch.n_tokens] = id;
  1167. batch.pos [batch.n_tokens] = pos;
  1168. batch.n_seq_id[batch.n_tokens] = seq_ids.size();
  1169. for (size_t i = 0; i < seq_ids.size(); ++i) {
  1170. batch.seq_id[batch.n_tokens][i] = seq_ids[i];
  1171. }
  1172. batch.logits [batch.n_tokens] = logits;
  1173. batch.n_tokens++;
  1174. }
  1175. std::tuple<struct llama_model *, struct llama_context *> llama_init_from_gpt_params(gpt_params & params) {
  1176. auto mparams = llama_model_params_from_gpt_params(params);
  1177. llama_model * model = llama_load_model_from_file(params.model.c_str(), mparams);
  1178. if (model == NULL) {
  1179. fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, params.model.c_str());
  1180. return std::make_tuple(nullptr, nullptr);
  1181. }
  1182. auto cparams = llama_context_params_from_gpt_params(params);
  1183. llama_context * lctx = llama_new_context_with_model(model, cparams);
  1184. if (lctx == NULL) {
  1185. fprintf(stderr, "%s: error: failed to create context with model '%s'\n", __func__, params.model.c_str());
  1186. llama_free_model(model);
  1187. return std::make_tuple(nullptr, nullptr);
  1188. }
  1189. for (unsigned int i = 0; i < params.lora_adapter.size(); ++i) {
  1190. const std::string& lora_adapter = std::get<0>(params.lora_adapter[i]);
  1191. float lora_scale = std::get<1>(params.lora_adapter[i]);
  1192. int err = llama_model_apply_lora_from_file(model,
  1193. lora_adapter.c_str(),
  1194. lora_scale,
  1195. ((i > 0) || params.lora_base.empty())
  1196. ? NULL
  1197. : params.lora_base.c_str(),
  1198. params.n_threads);
  1199. if (err != 0) {
  1200. fprintf(stderr, "%s: error: failed to apply lora adapter\n", __func__);
  1201. llama_free(lctx);
  1202. llama_free_model(model);
  1203. return std::make_tuple(nullptr, nullptr);
  1204. }
  1205. }
  1206. if (params.ignore_eos) {
  1207. params.sparams.logit_bias[llama_token_eos(model)] = -INFINITY;
  1208. }
  1209. {
  1210. LOG("warming up the model with an empty run\n");
  1211. std::vector<llama_token> tmp = { llama_token_bos(model), llama_token_eos(model), };
  1212. llama_decode(lctx, llama_batch_get_one(tmp.data(), std::min(tmp.size(), (size_t) params.n_batch), 0, 0));
  1213. llama_kv_cache_clear(lctx);
  1214. llama_reset_timings(lctx);
  1215. }
  1216. return std::make_tuple(model, lctx);
  1217. }
  1218. //
  1219. // Vocab utils
  1220. //
  1221. std::vector<llama_token> llama_tokenize(
  1222. const struct llama_context * ctx,
  1223. const std::string & text,
  1224. bool add_bos,
  1225. bool special) {
  1226. return llama_tokenize(llama_get_model(ctx), text, add_bos, special);
  1227. }
  1228. std::vector<llama_token> llama_tokenize(
  1229. const struct llama_model * model,
  1230. const std::string & text,
  1231. bool add_bos,
  1232. bool special) {
  1233. // upper limit for the number of tokens
  1234. int n_tokens = text.length() + add_bos;
  1235. std::vector<llama_token> result(n_tokens);
  1236. n_tokens = llama_tokenize(model, text.data(), text.length(), result.data(), result.size(), add_bos, special);
  1237. if (n_tokens < 0) {
  1238. result.resize(-n_tokens);
  1239. int check = llama_tokenize(model, text.data(), text.length(), result.data(), result.size(), add_bos, special);
  1240. GGML_ASSERT(check == -n_tokens);
  1241. } else {
  1242. result.resize(n_tokens);
  1243. }
  1244. return result;
  1245. }
  1246. std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  1247. std::vector<char> result(8, 0);
  1248. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1249. if (n_tokens < 0) {
  1250. result.resize(-n_tokens);
  1251. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1252. GGML_ASSERT(check == -n_tokens);
  1253. } else {
  1254. result.resize(n_tokens);
  1255. }
  1256. return std::string(result.data(), result.size());
  1257. }
  1258. std::string llama_detokenize_spm(llama_context * ctx, const std::vector<llama_token> & tokens) {
  1259. const llama_token bos_id = llama_token_bos(llama_get_model(ctx));
  1260. std::string piece;
  1261. std::string result;
  1262. for (size_t i = 0; i < tokens.size(); ++i) {
  1263. piece = llama_token_to_piece(ctx, tokens[i]);
  1264. // remove the leading space of the first non-BOS token
  1265. if (((tokens[0] == bos_id && i == 1) || (tokens[0] != bos_id && i == 0)) && piece[0] == ' ') {
  1266. piece = piece.substr(1);
  1267. }
  1268. result += piece;
  1269. }
  1270. return result;
  1271. }
  1272. std::string llama_detokenize_bpe(llama_context * ctx, const std::vector<llama_token> & tokens) {
  1273. std::string piece;
  1274. std::string result;
  1275. for (size_t i = 0; i < tokens.size(); ++i) {
  1276. piece = llama_token_to_piece(ctx, tokens[i]);
  1277. result += piece;
  1278. }
  1279. // NOTE: the original tokenizer decodes bytes after collecting the pieces.
  1280. return result;
  1281. }
  1282. bool llama_should_add_bos_token(const llama_model * model) {
  1283. const int add_bos = llama_add_bos_token(model);
  1284. return add_bos != -1 ? bool(add_bos) : (llama_vocab_type(model) == LLAMA_VOCAB_TYPE_SPM);
  1285. }
  1286. //
  1287. // YAML utils
  1288. //
  1289. // returns true if successful, false otherwise
  1290. bool create_directory_with_parents(const std::string & path) {
  1291. #ifdef _WIN32
  1292. std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
  1293. std::wstring wpath = converter.from_bytes(path);
  1294. // if the path already exists, check whether it's a directory
  1295. const DWORD attributes = GetFileAttributesW(wpath.c_str());
  1296. if ((attributes != INVALID_FILE_ATTRIBUTES) && (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  1297. return true;
  1298. }
  1299. size_t pos_slash = 0;
  1300. // process path from front to back, procedurally creating directories
  1301. while ((pos_slash = path.find('\\', pos_slash)) != std::string::npos) {
  1302. const std::wstring subpath = wpath.substr(0, pos_slash);
  1303. const wchar_t * test = subpath.c_str();
  1304. const bool success = CreateDirectoryW(test, NULL);
  1305. if (!success) {
  1306. const DWORD error = GetLastError();
  1307. // if the path already exists, ensure that it's a directory
  1308. if (error == ERROR_ALREADY_EXISTS) {
  1309. const DWORD attributes = GetFileAttributesW(subpath.c_str());
  1310. if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  1311. return false;
  1312. }
  1313. } else {
  1314. return false;
  1315. }
  1316. }
  1317. pos_slash += 1;
  1318. }
  1319. return true;
  1320. #else
  1321. // if the path already exists, check whether it's a directory
  1322. struct stat info;
  1323. if (stat(path.c_str(), &info) == 0) {
  1324. return S_ISDIR(info.st_mode);
  1325. }
  1326. size_t pos_slash = 1; // skip leading slashes for directory creation
  1327. // process path from front to back, procedurally creating directories
  1328. while ((pos_slash = path.find('/', pos_slash)) != std::string::npos) {
  1329. const std::string subpath = path.substr(0, pos_slash);
  1330. struct stat info;
  1331. // if the path already exists, ensure that it's a directory
  1332. if (stat(subpath.c_str(), &info) == 0) {
  1333. if (!S_ISDIR(info.st_mode)) {
  1334. return false;
  1335. }
  1336. } else {
  1337. // create parent directories
  1338. const int ret = mkdir(subpath.c_str(), 0755);
  1339. if (ret != 0) {
  1340. return false;
  1341. }
  1342. }
  1343. pos_slash += 1;
  1344. }
  1345. return true;
  1346. #endif // _WIN32
  1347. }
  1348. void dump_vector_float_yaml(FILE * stream, const char * prop_name, const std::vector<float> & data) {
  1349. if (data.empty()) {
  1350. fprintf(stream, "%s:\n", prop_name);
  1351. return;
  1352. }
  1353. fprintf(stream, "%s: [", prop_name);
  1354. for (size_t i = 0; i < data.size() - 1; ++i) {
  1355. fprintf(stream, "%e, ", data[i]);
  1356. }
  1357. fprintf(stream, "%e]\n", data.back());
  1358. }
  1359. void dump_vector_int_yaml(FILE * stream, const char * prop_name, const std::vector<int> & data) {
  1360. if (data.empty()) {
  1361. fprintf(stream, "%s:\n", prop_name);
  1362. return;
  1363. }
  1364. fprintf(stream, "%s: [", prop_name);
  1365. for (size_t i = 0; i < data.size() - 1; ++i) {
  1366. fprintf(stream, "%d, ", data[i]);
  1367. }
  1368. fprintf(stream, "%d]\n", data.back());
  1369. }
  1370. void dump_string_yaml_multiline(FILE * stream, const char * prop_name, const char * data) {
  1371. std::string data_str(data == NULL ? "" : data);
  1372. if (data_str.empty()) {
  1373. fprintf(stream, "%s:\n", prop_name);
  1374. return;
  1375. }
  1376. size_t pos_start = 0;
  1377. size_t pos_found = 0;
  1378. if (!data_str.empty() && (std::isspace(data_str[0]) || std::isspace(data_str.back()))) {
  1379. data_str = std::regex_replace(data_str, std::regex("\n"), "\\n");
  1380. data_str = std::regex_replace(data_str, std::regex("\""), "\\\"");
  1381. data_str = std::regex_replace(data_str, std::regex(R"(\\[^n"])"), R"(\$&)");
  1382. data_str = "\"" + data_str + "\"";
  1383. fprintf(stream, "%s: %s\n", prop_name, data_str.c_str());
  1384. return;
  1385. }
  1386. if (data_str.find('\n') == std::string::npos) {
  1387. fprintf(stream, "%s: %s\n", prop_name, data_str.c_str());
  1388. return;
  1389. }
  1390. fprintf(stream, "%s: |\n", prop_name);
  1391. while ((pos_found = data_str.find('\n', pos_start)) != std::string::npos) {
  1392. fprintf(stream, " %s\n", data_str.substr(pos_start, pos_found-pos_start).c_str());
  1393. pos_start = pos_found + 1;
  1394. }
  1395. }
  1396. std::string get_sortable_timestamp() {
  1397. using clock = std::chrono::system_clock;
  1398. const clock::time_point current_time = clock::now();
  1399. const time_t as_time_t = clock::to_time_t(current_time);
  1400. char timestamp_no_ns[100];
  1401. std::strftime(timestamp_no_ns, 100, "%Y_%m_%d-%H_%M_%S", std::localtime(&as_time_t));
  1402. const int64_t ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
  1403. current_time.time_since_epoch() % 1000000000).count();
  1404. char timestamp_ns[11];
  1405. snprintf(timestamp_ns, 11, "%09" PRId64, ns);
  1406. return std::string(timestamp_no_ns) + "." + std::string(timestamp_ns);
  1407. }
  1408. void dump_non_result_info_yaml(FILE * stream, const gpt_params & params, const llama_context * lctx,
  1409. const std::string & timestamp, const std::vector<int> & prompt_tokens, const char * model_desc) {
  1410. const llama_sampling_params & sparams = params.sparams;
  1411. fprintf(stream, "build_commit: %s\n", LLAMA_COMMIT);
  1412. fprintf(stream, "build_number: %d\n", LLAMA_BUILD_NUMBER);
  1413. fprintf(stream, "cpu_has_arm_fma: %s\n", ggml_cpu_has_arm_fma() ? "true" : "false");
  1414. fprintf(stream, "cpu_has_avx: %s\n", ggml_cpu_has_avx() ? "true" : "false");
  1415. fprintf(stream, "cpu_has_avx_vnni: %s\n", ggml_cpu_has_avx_vnni() ? "true" : "false");
  1416. fprintf(stream, "cpu_has_avx2: %s\n", ggml_cpu_has_avx2() ? "true" : "false");
  1417. fprintf(stream, "cpu_has_avx512: %s\n", ggml_cpu_has_avx512() ? "true" : "false");
  1418. fprintf(stream, "cpu_has_avx512_vbmi: %s\n", ggml_cpu_has_avx512_vbmi() ? "true" : "false");
  1419. fprintf(stream, "cpu_has_avx512_vnni: %s\n", ggml_cpu_has_avx512_vnni() ? "true" : "false");
  1420. fprintf(stream, "cpu_has_cublas: %s\n", ggml_cpu_has_cublas() ? "true" : "false");
  1421. fprintf(stream, "cpu_has_clblast: %s\n", ggml_cpu_has_clblast() ? "true" : "false");
  1422. fprintf(stream, "cpu_has_fma: %s\n", ggml_cpu_has_fma() ? "true" : "false");
  1423. fprintf(stream, "cpu_has_gpublas: %s\n", ggml_cpu_has_gpublas() ? "true" : "false");
  1424. fprintf(stream, "cpu_has_neon: %s\n", ggml_cpu_has_neon() ? "true" : "false");
  1425. fprintf(stream, "cpu_has_f16c: %s\n", ggml_cpu_has_f16c() ? "true" : "false");
  1426. fprintf(stream, "cpu_has_fp16_va: %s\n", ggml_cpu_has_fp16_va() ? "true" : "false");
  1427. fprintf(stream, "cpu_has_wasm_simd: %s\n", ggml_cpu_has_wasm_simd() ? "true" : "false");
  1428. fprintf(stream, "cpu_has_blas: %s\n", ggml_cpu_has_blas() ? "true" : "false");
  1429. fprintf(stream, "cpu_has_sse3: %s\n", ggml_cpu_has_sse3() ? "true" : "false");
  1430. fprintf(stream, "cpu_has_vsx: %s\n", ggml_cpu_has_vsx() ? "true" : "false");
  1431. #ifdef NDEBUG
  1432. fprintf(stream, "debug: false\n");
  1433. #else
  1434. fprintf(stream, "debug: true\n");
  1435. #endif // NDEBUG
  1436. fprintf(stream, "model_desc: %s\n", model_desc);
  1437. fprintf(stream, "n_vocab: %d # output size of the final layer, 32001 for some models\n", llama_n_vocab(llama_get_model(lctx)));
  1438. #ifdef __OPTIMIZE__
  1439. fprintf(stream, "optimize: true\n");
  1440. #else
  1441. fprintf(stream, "optimize: false\n");
  1442. #endif // __OPTIMIZE__
  1443. fprintf(stream, "time: %s\n", timestamp.c_str());
  1444. fprintf(stream, "\n");
  1445. fprintf(stream, "###############\n");
  1446. fprintf(stream, "# User Inputs #\n");
  1447. fprintf(stream, "###############\n");
  1448. fprintf(stream, "\n");
  1449. fprintf(stream, "alias: %s # default: unknown\n", params.model_alias.c_str());
  1450. fprintf(stream, "batch_size: %d # default: 512\n", params.n_batch);
  1451. dump_string_yaml_multiline(stream, "cfg_negative_prompt", sparams.cfg_negative_prompt.c_str());
  1452. fprintf(stream, "cfg_scale: %f # default: 1.0\n", sparams.cfg_scale);
  1453. fprintf(stream, "chunks: %d # default: -1 (unlimited)\n", params.n_chunks);
  1454. fprintf(stream, "color: %s # default: false\n", params.use_color ? "true" : "false");
  1455. fprintf(stream, "ctx_size: %d # default: 512\n", params.n_ctx);
  1456. fprintf(stream, "escape: %s # default: false\n", params.escape ? "true" : "false");
  1457. fprintf(stream, "file: # never logged, see prompt instead. Can still be specified for input.\n");
  1458. fprintf(stream, "frequency_penalty: %f # default: 0.0 \n", sparams.penalty_freq);
  1459. dump_string_yaml_multiline(stream, "grammar", sparams.grammar.c_str());
  1460. fprintf(stream, "grammar-file: # never logged, see grammar instead. Can still be specified for input.\n");
  1461. fprintf(stream, "hellaswag: %s # default: false\n", params.hellaswag ? "true" : "false");
  1462. fprintf(stream, "hellaswag_tasks: %zu # default: 400\n", params.hellaswag_tasks);
  1463. const auto logit_bias_eos = sparams.logit_bias.find(llama_token_eos(llama_get_model(lctx)));
  1464. const bool ignore_eos = logit_bias_eos != sparams.logit_bias.end() && logit_bias_eos->second == -INFINITY;
  1465. fprintf(stream, "ignore_eos: %s # default: false\n", ignore_eos ? "true" : "false");
  1466. dump_string_yaml_multiline(stream, "in_prefix", params.input_prefix.c_str());
  1467. fprintf(stream, "in_prefix_bos: %s # default: false\n", params.input_prefix_bos ? "true" : "false");
  1468. dump_string_yaml_multiline(stream, "in_suffix", params.input_prefix.c_str());
  1469. fprintf(stream, "instruct: %s # default: false\n", params.instruct ? "true" : "false");
  1470. fprintf(stream, "interactive: %s # default: false\n", params.interactive ? "true" : "false");
  1471. fprintf(stream, "interactive_first: %s # default: false\n", params.interactive_first ? "true" : "false");
  1472. fprintf(stream, "keep: %d # default: 0\n", params.n_keep);
  1473. fprintf(stream, "logdir: %s # default: unset (no logging)\n", params.logdir.c_str());
  1474. fprintf(stream, "logit_bias:\n");
  1475. for (std::pair<llama_token, float> lb : sparams.logit_bias) {
  1476. if (ignore_eos && lb.first == logit_bias_eos->first) {
  1477. continue;
  1478. }
  1479. fprintf(stream, " %d: %f", lb.first, lb.second);
  1480. }
  1481. fprintf(stream, "lora:\n");
  1482. for (std::tuple<std::string, float> la : params.lora_adapter) {
  1483. if (std::get<1>(la) != 1.0f) {
  1484. continue;
  1485. }
  1486. fprintf(stream, " - %s\n", std::get<0>(la).c_str());
  1487. }
  1488. fprintf(stream, "lora_scaled:\n");
  1489. for (std::tuple<std::string, float> la : params.lora_adapter) {
  1490. if (std::get<1>(la) == 1.0f) {
  1491. continue;
  1492. }
  1493. fprintf(stream, " - %s: %f\n", std::get<0>(la).c_str(), std::get<1>(la));
  1494. }
  1495. fprintf(stream, "lora_base: %s\n", params.lora_base.c_str());
  1496. fprintf(stream, "main_gpu: %d # default: 0\n", params.main_gpu);
  1497. fprintf(stream, "mirostat: %d # default: 0 (disabled)\n", sparams.mirostat);
  1498. fprintf(stream, "mirostat_ent: %f # default: 5.0\n", sparams.mirostat_tau);
  1499. fprintf(stream, "mirostat_lr: %f # default: 0.1\n", sparams.mirostat_eta);
  1500. fprintf(stream, "mlock: %s # default: false\n", params.use_mlock ? "true" : "false");
  1501. fprintf(stream, "model: %s # default: models/7B/ggml-model.bin\n", params.model.c_str());
  1502. fprintf(stream, "model_draft: %s # default:\n", params.model_draft.c_str());
  1503. fprintf(stream, "multiline_input: %s # default: false\n", params.multiline_input ? "true" : "false");
  1504. fprintf(stream, "n_gpu_layers: %d # default: -1\n", params.n_gpu_layers);
  1505. fprintf(stream, "n_predict: %d # default: -1 (unlimited)\n", params.n_predict);
  1506. fprintf(stream, "n_probs: %d # only used by server binary, default: 0\n", sparams.n_probs);
  1507. fprintf(stream, "no_mmap: %s # default: false\n", !params.use_mmap ? "true" : "false");
  1508. fprintf(stream, "no_mul_mat_q: %s # default: false\n", !params.mul_mat_q ? "true" : "false");
  1509. fprintf(stream, "no_penalize_nl: %s # default: false\n", !sparams.penalize_nl ? "true" : "false");
  1510. fprintf(stream, "numa: %s # default: false\n", params.numa ? "true" : "false");
  1511. fprintf(stream, "ppl_output_type: %d # default: 0\n", params.ppl_output_type);
  1512. fprintf(stream, "ppl_stride: %d # default: 0\n", params.ppl_stride);
  1513. fprintf(stream, "presence_penalty: %f # default: 0.0\n", sparams.penalty_present);
  1514. dump_string_yaml_multiline(stream, "prompt", params.prompt.c_str());
  1515. fprintf(stream, "prompt_cache: %s\n", params.path_prompt_cache.c_str());
  1516. fprintf(stream, "prompt_cache_all: %s # default: false\n", params.prompt_cache_all ? "true" : "false");
  1517. fprintf(stream, "prompt_cache_ro: %s # default: false\n", params.prompt_cache_ro ? "true" : "false");
  1518. dump_vector_int_yaml(stream, "prompt_tokens", prompt_tokens);
  1519. fprintf(stream, "random_prompt: %s # default: false\n", params.random_prompt ? "true" : "false");
  1520. fprintf(stream, "repeat_penalty: %f # default: 1.1\n", sparams.penalty_repeat);
  1521. fprintf(stream, "reverse_prompt:\n");
  1522. for (std::string ap : params.antiprompt) {
  1523. size_t pos = 0;
  1524. while ((pos = ap.find('\n', pos)) != std::string::npos) {
  1525. ap.replace(pos, 1, "\\n");
  1526. pos += 1;
  1527. }
  1528. fprintf(stream, " - %s\n", ap.c_str());
  1529. }
  1530. fprintf(stream, "rope_freq_base: %f # default: 10000.0\n", params.rope_freq_base);
  1531. fprintf(stream, "rope_freq_scale: %f # default: 1.0\n", params.rope_freq_scale);
  1532. fprintf(stream, "seed: %d # default: -1 (random seed)\n", params.seed);
  1533. fprintf(stream, "simple_io: %s # default: false\n", params.simple_io ? "true" : "false");
  1534. fprintf(stream, "cont_batching: %s # default: false\n", params.cont_batching ? "true" : "false");
  1535. fprintf(stream, "temp: %f # default: 0.8\n", sparams.temp);
  1536. const std::vector<float> tensor_split_vector(params.tensor_split, params.tensor_split + LLAMA_MAX_DEVICES);
  1537. dump_vector_float_yaml(stream, "tensor_split", tensor_split_vector);
  1538. fprintf(stream, "tfs: %f # default: 1.0\n", sparams.tfs_z);
  1539. fprintf(stream, "threads: %d # default: %d\n", params.n_threads, std::thread::hardware_concurrency());
  1540. fprintf(stream, "top_k: %d # default: 40\n", sparams.top_k);
  1541. fprintf(stream, "top_p: %f # default: 0.95\n", sparams.top_p);
  1542. fprintf(stream, "min_p: %f # default: 0.0\n", sparams.min_p);
  1543. fprintf(stream, "typical_p: %f # default: 1.0\n", sparams.typical_p);
  1544. fprintf(stream, "verbose_prompt: %s # default: false\n", params.verbose_prompt ? "true" : "false");
  1545. fprintf(stream, "display_prompt: %s # default: true\n", params.display_prompt ? "true" : "false");
  1546. }
  1547. //
  1548. // KV cache utils
  1549. //
  1550. void dump_kv_cache_view(const llama_kv_cache_view & view, int row_size) {
  1551. static const char slot_chars[] = ".123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+";
  1552. printf("=== Dumping KV cache. total cells %d, max sequences per cell %d, populated cells %d, total tokens in cache %d, largest empty slot=%d @ %d",
  1553. view.n_cells, view.n_max_seq, view.used_cells, view.token_count, view.max_contiguous, view.max_contiguous_idx);
  1554. llama_kv_cache_view_cell * c_curr = view.cells;
  1555. llama_seq_id * cs_curr = view.cells_sequences;
  1556. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_max_seq) {
  1557. if (i % row_size == 0) {
  1558. printf("\n%5d: ", i);
  1559. }
  1560. int seq_count = 0;
  1561. for (int j = 0; j < view.n_max_seq; j++) {
  1562. if (cs_curr[j] >= 0) { seq_count++; }
  1563. }
  1564. putchar(slot_chars[std::min(sizeof(slot_chars) - 2, size_t(seq_count))]);
  1565. }
  1566. printf("\n=== Done dumping\n");
  1567. }
  1568. void dump_kv_cache_view_seqs(const llama_kv_cache_view & view, int row_size) {
  1569. static const char slot_chars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  1570. printf("=== Dumping KV cache. total cells %d, max sequences per cell %d, populated cells %d, total tokens in cache %d, largest empty slot=%d @ %d\n",
  1571. view.n_cells, view.n_max_seq, view.used_cells, view.token_count, view.max_contiguous, view.max_contiguous_idx);
  1572. std::unordered_map<llama_seq_id, size_t> seqs;
  1573. llama_kv_cache_view_cell * c_curr = view.cells;
  1574. llama_seq_id * cs_curr = view.cells_sequences;
  1575. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_max_seq) {
  1576. for (int j = 0; j < view.n_max_seq; j++) {
  1577. if (cs_curr[j] < 0) { continue; }
  1578. if (seqs.find(cs_curr[j]) == seqs.end()) {
  1579. if (seqs.size() + 1 >= sizeof(slot_chars)) { break; }
  1580. seqs[cs_curr[j]] = seqs.size();
  1581. }
  1582. }
  1583. if (seqs.size() + 1 >= sizeof(slot_chars)) { break; }
  1584. }
  1585. printf("=== Sequence legend: ");
  1586. for (const auto & it : seqs) {
  1587. printf("%zu=%d, ", it.second, it.first);
  1588. }
  1589. printf("'+'=other sequence ids");
  1590. c_curr = view.cells;
  1591. cs_curr = view.cells_sequences;
  1592. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_max_seq) {
  1593. if (i % row_size == 0) {
  1594. printf("\n%5d: ", i);
  1595. }
  1596. for (int j = 0; j < view.n_max_seq; j++) {
  1597. if (cs_curr[j] >= 0) {
  1598. const auto & it = seqs.find(cs_curr[j]);
  1599. putchar(it != seqs.end() ? int(slot_chars[it->second]) : '+');
  1600. } else {
  1601. putchar('.');
  1602. }
  1603. }
  1604. putchar(' ');
  1605. }
  1606. printf("\n=== Done dumping\n");
  1607. }