common.cpp 59 KB

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