1
0

common.cpp 74 KB

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