common.cpp 73 KB

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