common.cpp 55 KB

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