common.cpp 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  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.size() > 0) {
  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 == "-m" || arg == "--model") {
  310. if (++i >= argc) {
  311. invalid_param = true;
  312. break;
  313. }
  314. params.model = argv[i];
  315. } else if (arg == "-md" || arg == "--model-draft") {
  316. if (++i >= argc) {
  317. invalid_param = true;
  318. break;
  319. }
  320. params.model_draft = argv[i];
  321. } else if (arg == "-a" || arg == "--alias") {
  322. if (++i >= argc) {
  323. invalid_param = true;
  324. break;
  325. }
  326. params.model_alias = argv[i];
  327. } else if (arg == "--lora") {
  328. if (++i >= argc) {
  329. invalid_param = true;
  330. break;
  331. }
  332. params.lora_adapter = argv[i];
  333. params.use_mmap = false;
  334. } else if (arg == "--lora-base") {
  335. if (++i >= argc) {
  336. invalid_param = true;
  337. break;
  338. }
  339. params.lora_base = argv[i];
  340. } else if (arg == "-i" || arg == "--interactive") {
  341. params.interactive = true;
  342. } else if (arg == "--embedding") {
  343. params.embedding = true;
  344. } else if (arg == "--interactive-first") {
  345. params.interactive_first = true;
  346. } else if (arg == "-ins" || arg == "--instruct") {
  347. params.instruct = true;
  348. } else if (arg == "--multiline-input") {
  349. params.multiline_input = true;
  350. } else if (arg == "--simple-io") {
  351. params.simple_io = true;
  352. } else if (arg == "--color") {
  353. params.use_color = true;
  354. } else if (arg == "--mlock") {
  355. params.use_mlock = true;
  356. } else if (arg == "--gpu-layers" || arg == "-ngl" || arg == "--n-gpu-layers") {
  357. if (++i >= argc) {
  358. invalid_param = true;
  359. break;
  360. }
  361. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  362. params.n_gpu_layers = std::stoi(argv[i]);
  363. #else
  364. fprintf(stderr, "warning: not compiled with GPU offload support, --n-gpu-layers option will be ignored\n");
  365. fprintf(stderr, "warning: see main README.md for information on enabling GPU BLAS support\n");
  366. #endif
  367. } else if (arg == "--main-gpu" || arg == "-mg") {
  368. if (++i >= argc) {
  369. invalid_param = true;
  370. break;
  371. }
  372. #ifdef GGML_USE_CUBLAS
  373. params.main_gpu = std::stoi(argv[i]);
  374. #else
  375. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set a main GPU.\n");
  376. #endif
  377. } else if (arg == "--tensor-split" || arg == "-ts") {
  378. if (++i >= argc) {
  379. invalid_param = true;
  380. break;
  381. }
  382. #ifdef GGML_USE_CUBLAS
  383. std::string arg_next = argv[i];
  384. // split string by , and /
  385. const std::regex regex{R"([,/]+)"};
  386. std::sregex_token_iterator it{arg_next.begin(), arg_next.end(), regex, -1};
  387. std::vector<std::string> split_arg{it, {}};
  388. GGML_ASSERT(split_arg.size() <= LLAMA_MAX_DEVICES);
  389. for (size_t i = 0; i < LLAMA_MAX_DEVICES; ++i) {
  390. if (i < split_arg.size()) {
  391. params.tensor_split[i] = std::stof(split_arg[i]);
  392. } else {
  393. params.tensor_split[i] = 0.0f;
  394. }
  395. }
  396. #else
  397. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set a tensor split.\n");
  398. #endif // GGML_USE_CUBLAS
  399. } else if (arg == "--no-mul-mat-q" || arg == "-nommq") {
  400. #ifdef GGML_USE_CUBLAS
  401. params.mul_mat_q = false;
  402. #else
  403. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. Disabling mul_mat_q kernels has no effect.\n");
  404. #endif // GGML_USE_CUBLAS
  405. } else if (arg == "--low-vram" || arg == "-lv") {
  406. #ifdef GGML_USE_CUBLAS
  407. params.low_vram = true;
  408. #else
  409. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set lower vram usage.\n");
  410. #endif // GGML_USE_CUBLAS
  411. } else if (arg == "--no-mmap") {
  412. params.use_mmap = false;
  413. } else if (arg == "--mtest") {
  414. params.mem_test = true;
  415. } else if (arg == "--numa") {
  416. params.numa = true;
  417. } else if (arg == "--export") {
  418. params.export_cgraph = true;
  419. } else if (arg == "--verbose-prompt") {
  420. params.verbose_prompt = true;
  421. } else if (arg == "-r" || arg == "--reverse-prompt") {
  422. if (++i >= argc) {
  423. invalid_param = true;
  424. break;
  425. }
  426. params.antiprompt.push_back(argv[i]);
  427. } else if (arg == "-ld" || arg == "--logdir") {
  428. if (++i >= argc) {
  429. invalid_param = true;
  430. break;
  431. }
  432. params.logdir = argv[i];
  433. if (params.logdir.back() != DIRECTORY_SEPARATOR) {
  434. params.logdir += DIRECTORY_SEPARATOR;
  435. }
  436. } else if (arg == "--perplexity") {
  437. params.perplexity = true;
  438. } else if (arg == "--ppl-stride") {
  439. if (++i >= argc) {
  440. invalid_param = true;
  441. break;
  442. }
  443. params.ppl_stride = std::stoi(argv[i]);
  444. } else if (arg == "--ppl-output-type") {
  445. if (++i >= argc) {
  446. invalid_param = true;
  447. break;
  448. }
  449. params.ppl_output_type = std::stoi(argv[i]);
  450. } else if (arg == "--hellaswag") {
  451. params.hellaswag = true;
  452. } else if (arg == "--hellaswag-tasks") {
  453. if (++i >= argc) {
  454. invalid_param = true;
  455. break;
  456. }
  457. params.hellaswag_tasks = std::stoi(argv[i]);
  458. } else if (arg == "--ignore-eos") {
  459. params.ignore_eos = true;
  460. } else if (arg == "--no-penalize-nl") {
  461. params.penalize_nl = false;
  462. } else if (arg == "-l" || arg == "--logit-bias") {
  463. if (++i >= argc) {
  464. invalid_param = true;
  465. break;
  466. }
  467. std::stringstream ss(argv[i]);
  468. llama_token key;
  469. char sign;
  470. std::string value_str;
  471. try {
  472. if (ss >> key && ss >> sign && std::getline(ss, value_str) && (sign == '+' || sign == '-')) {
  473. params.logit_bias[key] = std::stof(value_str) * ((sign == '-') ? -1.0f : 1.0f);
  474. } else {
  475. throw std::exception();
  476. }
  477. } catch (const std::exception&) {
  478. invalid_param = true;
  479. break;
  480. }
  481. } else if (arg == "-h" || arg == "--help") {
  482. gpt_print_usage(argc, argv, default_params);
  483. #ifndef LOG_DISABLE_LOGS
  484. log_print_usage();
  485. #endif // LOG_DISABLE_LOGS
  486. exit(0);
  487. } else if (arg == "--random-prompt") {
  488. params.random_prompt = true;
  489. } else if (arg == "--in-prefix-bos") {
  490. params.input_prefix_bos = true;
  491. } else if (arg == "--in-prefix") {
  492. if (++i >= argc) {
  493. invalid_param = true;
  494. break;
  495. }
  496. params.input_prefix = argv[i];
  497. } else if (arg == "--in-suffix") {
  498. if (++i >= argc) {
  499. invalid_param = true;
  500. break;
  501. }
  502. params.input_suffix = argv[i];
  503. } else if (arg == "--grammar") {
  504. if (++i >= argc) {
  505. invalid_param = true;
  506. break;
  507. }
  508. params.grammar = argv[i];
  509. } else if (arg == "--grammar-file") {
  510. if (++i >= argc) {
  511. invalid_param = true;
  512. break;
  513. }
  514. std::ifstream file(argv[i]);
  515. if (!file) {
  516. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  517. invalid_param = true;
  518. break;
  519. }
  520. std::copy(
  521. std::istreambuf_iterator<char>(file),
  522. std::istreambuf_iterator<char>(),
  523. std::back_inserter(params.grammar)
  524. );
  525. #ifndef LOG_DISABLE_LOGS
  526. // Parse args for logging parameters
  527. } else if ( log_param_single_parse( argv[i] ) ) {
  528. // Do nothing, log_param_single_parse automatically does it's thing
  529. // and returns if a match was found and parsed.
  530. } else if ( log_param_pair_parse( /*check_but_dont_parse*/ true, argv[i] ) ) {
  531. // We have a matching known parameter requiring an argument,
  532. // now we need to check if there is anything after this argv
  533. // and flag invalid_param or parse it.
  534. if (++i >= argc) {
  535. invalid_param = true;
  536. break;
  537. }
  538. if( !log_param_pair_parse( /*check_but_dont_parse*/ false, argv[i-1], argv[i]) ) {
  539. invalid_param = true;
  540. break;
  541. }
  542. // End of Parse args for logging parameters
  543. #endif // LOG_DISABLE_LOGS
  544. } else {
  545. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  546. gpt_print_usage(argc, argv, default_params);
  547. exit(1);
  548. }
  549. }
  550. if (invalid_param) {
  551. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  552. gpt_print_usage(argc, argv, default_params);
  553. exit(1);
  554. }
  555. if (params.prompt_cache_all &&
  556. (params.interactive || params.interactive_first ||
  557. params.instruct)) {
  558. fprintf(stderr, "error: --prompt-cache-all not supported in interactive mode yet\n");
  559. gpt_print_usage(argc, argv, default_params);
  560. exit(1);
  561. }
  562. if (params.escape) {
  563. process_escapes(params.prompt);
  564. process_escapes(params.input_prefix);
  565. process_escapes(params.input_suffix);
  566. }
  567. return true;
  568. }
  569. void gpt_print_usage(int /*argc*/, char ** argv, const gpt_params & params) {
  570. fprintf(stdout, "usage: %s [options]\n", argv[0]);
  571. fprintf(stdout, "\n");
  572. fprintf(stdout, "options:\n");
  573. fprintf(stdout, " -h, --help show this help message and exit\n");
  574. fprintf(stdout, " -i, --interactive run in interactive mode\n");
  575. fprintf(stdout, " --interactive-first run in interactive mode and wait for input right away\n");
  576. fprintf(stdout, " -ins, --instruct run in instruction mode (use with Alpaca models)\n");
  577. fprintf(stdout, " --multiline-input allows you to write or paste multiple lines without ending each in '\\'\n");
  578. fprintf(stdout, " -r PROMPT, --reverse-prompt PROMPT\n");
  579. fprintf(stdout, " halt generation at PROMPT, return control in interactive mode\n");
  580. fprintf(stdout, " (can be specified more than once for multiple prompts).\n");
  581. fprintf(stdout, " --color colorise output to distinguish prompt and user input from generations\n");
  582. fprintf(stdout, " -s SEED, --seed SEED RNG seed (default: -1, use random seed for < 0)\n");
  583. fprintf(stdout, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
  584. fprintf(stdout, " -p PROMPT, --prompt PROMPT\n");
  585. fprintf(stdout, " prompt to start generation with (default: empty)\n");
  586. fprintf(stdout, " -e, --escape process prompt escapes sequences (\\n, \\r, \\t, \\', \\\", \\\\)\n");
  587. fprintf(stdout, " --prompt-cache FNAME file to cache prompt state for faster startup (default: none)\n");
  588. fprintf(stdout, " --prompt-cache-all if specified, saves user input and generations to cache as well.\n");
  589. fprintf(stdout, " not supported with --interactive or other interactive options\n");
  590. fprintf(stdout, " --prompt-cache-ro if specified, uses the prompt cache but does not update it.\n");
  591. fprintf(stdout, " --random-prompt start with a randomized prompt.\n");
  592. fprintf(stdout, " --in-prefix-bos prefix BOS to user inputs, preceding the `--in-prefix` string\n");
  593. fprintf(stdout, " --in-prefix STRING string to prefix user inputs with (default: empty)\n");
  594. fprintf(stdout, " --in-suffix STRING string to suffix after user inputs with (default: empty)\n");
  595. fprintf(stdout, " -f FNAME, --file FNAME\n");
  596. fprintf(stdout, " prompt file to start generation.\n");
  597. fprintf(stdout, " -n N, --n-predict N number of tokens to predict (default: %d, -1 = infinity, -2 = until context filled)\n", params.n_predict);
  598. fprintf(stdout, " -c N, --ctx-size N size of the prompt context (default: %d)\n", params.n_ctx);
  599. fprintf(stdout, " -b N, --batch-size N batch size for prompt processing (default: %d)\n", params.n_batch);
  600. fprintf(stdout, " --top-k N top-k sampling (default: %d, 0 = disabled)\n", params.top_k);
  601. fprintf(stdout, " --top-p N top-p sampling (default: %.1f, 1.0 = disabled)\n", (double)params.top_p);
  602. fprintf(stdout, " --tfs N tail free sampling, parameter z (default: %.1f, 1.0 = disabled)\n", (double)params.tfs_z);
  603. fprintf(stdout, " --typical N locally typical sampling, parameter p (default: %.1f, 1.0 = disabled)\n", (double)params.typical_p);
  604. fprintf(stdout, " --repeat-last-n N last n tokens to consider for penalize (default: %d, 0 = disabled, -1 = ctx_size)\n", params.repeat_last_n);
  605. fprintf(stdout, " --repeat-penalty N penalize repeat sequence of tokens (default: %.1f, 1.0 = disabled)\n", (double)params.repeat_penalty);
  606. fprintf(stdout, " --presence-penalty N repeat alpha presence penalty (default: %.1f, 0.0 = disabled)\n", (double)params.presence_penalty);
  607. fprintf(stdout, " --frequency-penalty N repeat alpha frequency penalty (default: %.1f, 0.0 = disabled)\n", (double)params.frequency_penalty);
  608. fprintf(stdout, " --mirostat N use Mirostat sampling.\n");
  609. fprintf(stdout, " Top K, Nucleus, Tail Free and Locally Typical samplers are ignored if used.\n");
  610. fprintf(stdout, " (default: %d, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)\n", params.mirostat);
  611. fprintf(stdout, " --mirostat-lr N Mirostat learning rate, parameter eta (default: %.1f)\n", (double)params.mirostat_eta);
  612. fprintf(stdout, " --mirostat-ent N Mirostat target entropy, parameter tau (default: %.1f)\n", (double)params.mirostat_tau);
  613. fprintf(stdout, " -l TOKEN_ID(+/-)BIAS, --logit-bias TOKEN_ID(+/-)BIAS\n");
  614. fprintf(stdout, " modifies the likelihood of token appearing in the completion,\n");
  615. fprintf(stdout, " i.e. `--logit-bias 15043+1` to increase likelihood of token ' Hello',\n");
  616. fprintf(stdout, " or `--logit-bias 15043-1` to decrease likelihood of token ' Hello'\n");
  617. fprintf(stdout, " --grammar GRAMMAR BNF-like grammar to constrain generations (see samples in grammars/ dir)\n");
  618. fprintf(stdout, " --grammar-file FNAME file to read grammar from\n");
  619. fprintf(stdout, " --cfg-negative-prompt PROMPT\n");
  620. fprintf(stdout, " negative prompt to use for guidance. (default: empty)\n");
  621. fprintf(stdout, " --cfg-negative-prompt-file FNAME\n");
  622. fprintf(stdout, " negative prompt file to use for guidance. (default: empty)\n");
  623. fprintf(stdout, " --cfg-scale N strength of guidance (default: %f, 1.0 = disable)\n", params.cfg_scale);
  624. fprintf(stdout, " --rope-scale N RoPE context linear scaling factor, inverse of --rope-freq-scale (default: %g)\n", 1.0f/params.rope_freq_scale);
  625. fprintf(stdout, " --rope-freq-base N RoPE base frequency, used by NTK-aware scaling (default: %.1f)\n", params.rope_freq_base);
  626. fprintf(stdout, " --rope-freq-scale N RoPE frequency linear scaling factor, inverse of --rope-scale (default: %g)\n", params.rope_freq_scale);
  627. fprintf(stdout, " --ignore-eos ignore end of stream token and continue generating (implies --logit-bias 2-inf)\n");
  628. fprintf(stdout, " --no-penalize-nl do not penalize newline token\n");
  629. fprintf(stdout, " --memory-f32 use f32 instead of f16 for memory key+value (default: disabled)\n");
  630. fprintf(stdout, " not recommended: doubles context memory required and no measurable increase in quality\n");
  631. fprintf(stdout, " --temp N temperature (default: %.1f)\n", (double)params.temp);
  632. fprintf(stdout, " --perplexity compute perplexity over each ctx window of the prompt\n");
  633. fprintf(stdout, " --hellaswag compute HellaSwag score over random tasks from datafile supplied with -f\n");
  634. fprintf(stdout, " --hellaswag-tasks N number of tasks to use when computing the HellaSwag score (default: %zu)\n", params.hellaswag_tasks);
  635. fprintf(stdout, " --keep N number of tokens to keep from the initial prompt (default: %d, -1 = all)\n", params.n_keep);
  636. fprintf(stdout, " --draft N number of tokens to draft for speculative decoding (default: %d)\n", params.n_draft);
  637. fprintf(stdout, " --chunks N max number of chunks to process (default: %d, -1 = all)\n", params.n_chunks);
  638. if (llama_mlock_supported()) {
  639. fprintf(stdout, " --mlock force system to keep model in RAM rather than swapping or compressing\n");
  640. }
  641. if (llama_mmap_supported()) {
  642. fprintf(stdout, " --no-mmap do not memory-map model (slower load but may reduce pageouts if not using mlock)\n");
  643. }
  644. fprintf(stdout, " --numa attempt optimizations that help on some NUMA systems\n");
  645. fprintf(stdout, " if run without this previously, it is recommended to drop the system page cache before using this\n");
  646. fprintf(stdout, " see https://github.com/ggerganov/llama.cpp/issues/1437\n");
  647. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  648. fprintf(stdout, " -ngl N, --n-gpu-layers N\n");
  649. fprintf(stdout, " number of layers to store in VRAM\n");
  650. fprintf(stdout, " -ts SPLIT --tensor-split SPLIT\n");
  651. fprintf(stdout, " how to split tensors across multiple GPUs, comma-separated list of proportions, e.g. 3,1\n");
  652. fprintf(stdout, " -mg i, --main-gpu i the GPU to use for scratch and small tensors\n");
  653. fprintf(stdout, " -lv, --low-vram don't allocate VRAM scratch buffer\n");
  654. #ifdef GGML_USE_CUBLAS
  655. fprintf(stdout, " -nommq, --no-mul-mat-q\n");
  656. fprintf(stdout, " use " GGML_CUBLAS_NAME " instead of custom mul_mat_q " GGML_CUDA_NAME " kernels.\n");
  657. fprintf(stdout, " Not recommended since this is both slower and uses more VRAM.\n");
  658. #endif // GGML_USE_CUBLAS
  659. #endif
  660. fprintf(stdout, " --mtest compute maximum memory usage\n");
  661. fprintf(stdout, " --export export the computation graph to 'llama.ggml'\n");
  662. fprintf(stdout, " --verbose-prompt print prompt before generation\n");
  663. fprintf(stderr, " --simple-io use basic IO for better compatibility in subprocesses and limited consoles\n");
  664. fprintf(stdout, " --lora FNAME apply LoRA adapter (implies --no-mmap)\n");
  665. fprintf(stdout, " --lora-base FNAME optional model to use as a base for the layers modified by the LoRA adapter\n");
  666. fprintf(stdout, " -m FNAME, --model FNAME\n");
  667. fprintf(stdout, " model path (default: %s)\n", params.model.c_str());
  668. fprintf(stdout, " -md FNAME, --model-draft FNAME\n");
  669. fprintf(stdout, " draft model for speculative decoding (default: %s)\n", params.model.c_str());
  670. fprintf(stdout, " -ld LOGDIR, --logdir LOGDIR\n");
  671. fprintf(stdout, " path under which to save YAML logs (no logging if unset)\n");
  672. fprintf(stdout, "\n");
  673. }
  674. std::string gpt_random_prompt(std::mt19937 & rng) {
  675. const int r = rng() % 10;
  676. switch (r) {
  677. case 0: return "So";
  678. case 1: return "Once upon a time";
  679. case 2: return "When";
  680. case 3: return "The";
  681. case 4: return "After";
  682. case 5: return "If";
  683. case 6: return "import";
  684. case 7: return "He";
  685. case 8: return "She";
  686. case 9: return "They";
  687. default: return "To";
  688. }
  689. return "The";
  690. }
  691. //
  692. // Model utils
  693. //
  694. struct llama_context_params llama_context_params_from_gpt_params(const gpt_params & params) {
  695. auto lparams = llama_context_default_params();
  696. lparams.n_ctx = params.n_ctx;
  697. lparams.n_batch = params.n_batch;
  698. if (params.n_gpu_layers != -1) {
  699. lparams.n_gpu_layers = params.n_gpu_layers;
  700. }
  701. lparams.main_gpu = params.main_gpu;
  702. lparams.tensor_split = params.tensor_split;
  703. lparams.low_vram = params.low_vram;
  704. lparams.mul_mat_q = params.mul_mat_q;
  705. lparams.seed = params.seed;
  706. lparams.f16_kv = params.memory_f16;
  707. lparams.use_mmap = params.use_mmap;
  708. lparams.use_mlock = params.use_mlock;
  709. lparams.logits_all = params.perplexity;
  710. lparams.embedding = params.embedding;
  711. lparams.rope_freq_base = params.rope_freq_base;
  712. lparams.rope_freq_scale = params.rope_freq_scale;
  713. return lparams;
  714. }
  715. std::tuple<struct llama_model *, struct llama_context *> llama_init_from_gpt_params(gpt_params & params) {
  716. auto lparams = llama_context_params_from_gpt_params(params);
  717. llama_model * model = llama_load_model_from_file(params.model.c_str(), lparams);
  718. if (model == NULL) {
  719. fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, params.model.c_str());
  720. return std::make_tuple(nullptr, nullptr);
  721. }
  722. llama_context * lctx = llama_new_context_with_model(model, lparams);
  723. if (lctx == NULL) {
  724. fprintf(stderr, "%s: error: failed to create context with model '%s'\n", __func__, params.model.c_str());
  725. llama_free_model(model);
  726. return std::make_tuple(nullptr, nullptr);
  727. }
  728. if (!params.lora_adapter.empty()) {
  729. int err = llama_model_apply_lora_from_file(model,
  730. params.lora_adapter.c_str(),
  731. params.lora_base.empty() ? NULL : params.lora_base.c_str(),
  732. params.n_threads);
  733. if (err != 0) {
  734. fprintf(stderr, "%s: error: failed to apply lora adapter\n", __func__);
  735. llama_free(lctx);
  736. llama_free_model(model);
  737. return std::make_tuple(nullptr, nullptr);
  738. }
  739. }
  740. if (params.ignore_eos) {
  741. params.logit_bias[llama_token_eos(lctx)] = -INFINITY;
  742. }
  743. {
  744. LOG("warming up the model with an empty run\n");
  745. const std::vector<llama_token> tmp = { llama_token_bos(lctx), };
  746. llama_eval(lctx, tmp.data(), tmp.size(), 0, params.n_threads);
  747. llama_reset_timings(lctx);
  748. }
  749. return std::make_tuple(model, lctx);
  750. }
  751. //
  752. // Vocab utils
  753. //
  754. std::vector<llama_token> llama_tokenize(
  755. struct llama_context * ctx,
  756. const std::string & text,
  757. bool add_bos) {
  758. // upper limit for the number of tokens
  759. int n_tokens = text.length() + add_bos;
  760. std::vector<llama_token> result(n_tokens);
  761. n_tokens = llama_tokenize(ctx, text.c_str(), result.data(), result.size(), add_bos);
  762. if (n_tokens < 0) {
  763. result.resize(-n_tokens);
  764. int check = llama_tokenize(ctx, text.c_str(), result.data(), result.size(), add_bos);
  765. GGML_ASSERT(check == -n_tokens);
  766. } else {
  767. result.resize(n_tokens);
  768. }
  769. return result;
  770. }
  771. std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  772. std::vector<char> result(8, 0);
  773. const int n_tokens = llama_token_to_piece(ctx, token, result.data(), result.size());
  774. if (n_tokens < 0) {
  775. result.resize(-n_tokens);
  776. int check = llama_token_to_piece(ctx, token, result.data(), result.size());
  777. GGML_ASSERT(check == -n_tokens);
  778. } else {
  779. result.resize(n_tokens);
  780. }
  781. return std::string(result.data(), result.size());
  782. }
  783. std::string llama_detokenize_spm(llama_context * ctx, const std::vector<llama_token> & tokens) {
  784. const llama_token bos_id = llama_token_bos(ctx);
  785. std::string piece;
  786. std::string result;
  787. for (size_t i = 0; i < tokens.size(); ++i) {
  788. piece = llama_token_to_piece(ctx, tokens[i]);
  789. // remove the leading space of the first non-BOS token
  790. if (((tokens[0] == bos_id && i == 1) || (tokens[0] != bos_id && i == 0)) && piece[0] == ' ') {
  791. piece = piece.substr(1);
  792. }
  793. result += piece;
  794. }
  795. return result;
  796. }
  797. std::string llama_detokenize_bpe(llama_context * ctx, const std::vector<llama_token> & tokens) {
  798. std::string piece;
  799. std::string result;
  800. for (size_t i = 0; i < tokens.size(); ++i) {
  801. piece = llama_token_to_piece(ctx, tokens[i]);
  802. result += piece;
  803. }
  804. return result;
  805. }
  806. //
  807. // Sampling utils
  808. //
  809. llama_token llama_sample_token(
  810. struct llama_context * ctx,
  811. struct llama_context * ctx_guidance,
  812. struct llama_grammar * grammar,
  813. const struct gpt_params & params,
  814. const std::vector<llama_token> & last_tokens,
  815. std::vector<llama_token_data> & candidates,
  816. int idx) {
  817. const int n_ctx = llama_n_ctx(ctx);
  818. const int n_vocab = llama_n_vocab(ctx);
  819. const float temp = params.temp;
  820. const int32_t top_k = params.top_k <= 0 ? n_vocab : params.top_k;
  821. const float top_p = params.top_p;
  822. const float tfs_z = params.tfs_z;
  823. const float typical_p = params.typical_p;
  824. const int32_t repeat_last_n = params.repeat_last_n < 0 ? n_ctx : params.repeat_last_n;
  825. const float repeat_penalty = params.repeat_penalty;
  826. const float alpha_presence = params.presence_penalty;
  827. const float alpha_frequency = params.frequency_penalty;
  828. const int mirostat = params.mirostat;
  829. const float mirostat_tau = params.mirostat_tau;
  830. const float mirostat_eta = params.mirostat_eta;
  831. const bool penalize_nl = params.penalize_nl;
  832. llama_token id = 0;
  833. float * logits = llama_get_logits(ctx) + idx * n_vocab;
  834. // Apply params.logit_bias map
  835. for (auto it = params.logit_bias.begin(); it != params.logit_bias.end(); it++) {
  836. logits[it->first] += it->second;
  837. }
  838. candidates.clear();
  839. for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
  840. candidates.emplace_back(llama_token_data{token_id, logits[token_id], 0.0f});
  841. }
  842. llama_token_data_array cur_p = { candidates.data(), candidates.size(), false };
  843. if (ctx_guidance) {
  844. llama_sample_classifier_free_guidance(ctx, &cur_p, ctx_guidance, params.cfg_scale);
  845. }
  846. // apply penalties
  847. if (!last_tokens.empty()) {
  848. const float nl_logit = logits[llama_token_nl(ctx)];
  849. const int last_n_repeat = std::min(std::min((int)last_tokens.size(), repeat_last_n), n_ctx);
  850. llama_sample_repetition_penalty(ctx, &cur_p,
  851. last_tokens.data() + last_tokens.size() - last_n_repeat,
  852. last_n_repeat, repeat_penalty);
  853. llama_sample_frequency_and_presence_penalties(ctx, &cur_p,
  854. last_tokens.data() + last_tokens.size() - last_n_repeat,
  855. last_n_repeat, alpha_frequency, alpha_presence);
  856. if (!penalize_nl) {
  857. for (size_t idx = 0; idx < cur_p.size; idx++) {
  858. if (cur_p.data[idx].id == llama_token_nl(ctx)) {
  859. cur_p.data[idx].logit = nl_logit;
  860. break;
  861. }
  862. }
  863. }
  864. }
  865. if (grammar != NULL) {
  866. llama_sample_grammar(ctx, &cur_p, grammar);
  867. }
  868. if (temp <= 0) {
  869. // Greedy sampling
  870. id = llama_sample_token_greedy(ctx, &cur_p);
  871. } else {
  872. if (mirostat == 1) {
  873. static float mirostat_mu = 2.0f * mirostat_tau;
  874. const int mirostat_m = 100;
  875. llama_sample_temperature(ctx, &cur_p, temp);
  876. id = llama_sample_token_mirostat(ctx, &cur_p, mirostat_tau, mirostat_eta, mirostat_m, &mirostat_mu);
  877. } else if (mirostat == 2) {
  878. static float mirostat_mu = 2.0f * mirostat_tau;
  879. llama_sample_temperature(ctx, &cur_p, temp);
  880. id = llama_sample_token_mirostat_v2(ctx, &cur_p, mirostat_tau, mirostat_eta, &mirostat_mu);
  881. } else {
  882. // Temperature sampling
  883. llama_sample_top_k (ctx, &cur_p, top_k, 1);
  884. llama_sample_tail_free (ctx, &cur_p, tfs_z, 1);
  885. llama_sample_typical (ctx, &cur_p, typical_p, 1);
  886. llama_sample_top_p (ctx, &cur_p, top_p, 1);
  887. llama_sample_temperature(ctx, &cur_p, temp);
  888. {
  889. const int n_top = 10;
  890. LOG("top %d candidates:\n", n_top);
  891. for (int i = 0; i < n_top; i++) {
  892. const llama_token id = cur_p.data[i].id;
  893. LOG(" - %5d: '%12s' (%.3f)\n", id, llama_token_to_piece(ctx, id).c_str(), cur_p.data[i].p);
  894. }
  895. }
  896. id = llama_sample_token(ctx, &cur_p);
  897. LOG("sampled token: %5d: '%s'\n", id, llama_token_to_piece(ctx, id).c_str());
  898. }
  899. }
  900. // printf("`%d`", candidates_p.size);
  901. if (grammar != NULL) {
  902. llama_grammar_accept_token(ctx, grammar, id);
  903. }
  904. return id;
  905. }
  906. //
  907. // YAML utils
  908. //
  909. // returns true if successful, false otherwise
  910. bool create_directory_with_parents(const std::string & path) {
  911. #ifdef _WIN32
  912. std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
  913. std::wstring wpath = converter.from_bytes(path);
  914. // if the path already exists, check whether it's a directory
  915. const DWORD attributes = GetFileAttributesW(wpath.c_str());
  916. if ((attributes != INVALID_FILE_ATTRIBUTES) && (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  917. return true;
  918. }
  919. size_t pos_slash = 0;
  920. // process path from front to back, procedurally creating directories
  921. while ((pos_slash = path.find('\\', pos_slash)) != std::string::npos) {
  922. const std::wstring subpath = wpath.substr(0, pos_slash);
  923. const wchar_t * test = subpath.c_str();
  924. const bool success = CreateDirectoryW(test, NULL);
  925. if (!success) {
  926. const DWORD error = GetLastError();
  927. // if the path already exists, ensure that it's a directory
  928. if (error == ERROR_ALREADY_EXISTS) {
  929. const DWORD attributes = GetFileAttributesW(subpath.c_str());
  930. if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  931. return false;
  932. }
  933. } else {
  934. return false;
  935. }
  936. }
  937. pos_slash += 1;
  938. }
  939. return true;
  940. #else
  941. // if the path already exists, check whether it's a directory
  942. struct stat info;
  943. if (stat(path.c_str(), &info) == 0) {
  944. return S_ISDIR(info.st_mode);
  945. }
  946. size_t pos_slash = 1; // skip leading slashes for directory creation
  947. // process path from front to back, procedurally creating directories
  948. while ((pos_slash = path.find('/', pos_slash)) != std::string::npos) {
  949. const std::string subpath = path.substr(0, pos_slash);
  950. struct stat info;
  951. // if the path already exists, ensure that it's a directory
  952. if (stat(subpath.c_str(), &info) == 0) {
  953. if (!S_ISDIR(info.st_mode)) {
  954. return false;
  955. }
  956. } else {
  957. // create parent directories
  958. const int ret = mkdir(subpath.c_str(), 0755);
  959. if (ret != 0) {
  960. return false;
  961. }
  962. }
  963. pos_slash += 1;
  964. }
  965. return true;
  966. #endif // _WIN32
  967. }
  968. void dump_vector_float_yaml(FILE * stream, const char * prop_name, const std::vector<float> & data) {
  969. if (data.empty()) {
  970. fprintf(stream, "%s:\n", prop_name);
  971. return;
  972. }
  973. fprintf(stream, "%s: [", prop_name);
  974. for (size_t i = 0; i < data.size() - 1; ++i) {
  975. fprintf(stream, "%e, ", data[i]);
  976. }
  977. fprintf(stream, "%e]\n", data.back());
  978. }
  979. void dump_vector_int_yaml(FILE * stream, const char * prop_name, const std::vector<int> & data) {
  980. if (data.empty()) {
  981. fprintf(stream, "%s:\n", prop_name);
  982. return;
  983. }
  984. fprintf(stream, "%s: [", prop_name);
  985. for (size_t i = 0; i < data.size() - 1; ++i) {
  986. fprintf(stream, "%d, ", data[i]);
  987. }
  988. fprintf(stream, "%d]\n", data.back());
  989. }
  990. void dump_string_yaml_multiline(FILE * stream, const char * prop_name, const char * data) {
  991. std::string data_str(data == NULL ? "" : data);
  992. if (data_str.empty()) {
  993. fprintf(stream, "%s:\n", prop_name);
  994. return;
  995. }
  996. size_t pos_start = 0;
  997. size_t pos_found = 0;
  998. if (!data_str.empty() && (std::isspace(data_str[0]) || std::isspace(data_str.back()))) {
  999. data_str = std::regex_replace(data_str, std::regex("\n"), "\\n");
  1000. data_str = std::regex_replace(data_str, std::regex("\""), "\\\"");
  1001. data_str = "\"" + data_str + "\"";
  1002. fprintf(stream, "%s: %s\n", prop_name, data_str.c_str());
  1003. return;
  1004. }
  1005. if (data_str.find('\n') == std::string::npos) {
  1006. fprintf(stream, "%s: %s\n", prop_name, data_str.c_str());
  1007. return;
  1008. }
  1009. fprintf(stream, "%s: |\n", prop_name);
  1010. while ((pos_found = data_str.find('\n', pos_start)) != std::string::npos) {
  1011. fprintf(stream, " %s\n", data_str.substr(pos_start, pos_found-pos_start).c_str());
  1012. pos_start = pos_found + 1;
  1013. }
  1014. }
  1015. std::string get_sortable_timestamp() {
  1016. using clock = std::chrono::system_clock;
  1017. const clock::time_point current_time = clock::now();
  1018. const time_t as_time_t = clock::to_time_t(current_time);
  1019. char timestamp_no_ns[100];
  1020. std::strftime(timestamp_no_ns, 100, "%Y_%m_%d-%H_%M_%S", std::localtime(&as_time_t));
  1021. const int64_t ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
  1022. current_time.time_since_epoch() % 1000000000).count();
  1023. char timestamp_ns[11];
  1024. snprintf(timestamp_ns, 11, "%09" PRId64, ns);
  1025. return std::string(timestamp_no_ns) + "." + std::string(timestamp_ns);
  1026. }
  1027. void dump_non_result_info_yaml(FILE * stream, const gpt_params & params, const llama_context * lctx,
  1028. const std::string & timestamp, const std::vector<int> & prompt_tokens, const char * model_desc) {
  1029. fprintf(stream, "build_commit: %s\n", BUILD_COMMIT);
  1030. fprintf(stream, "build_number: %d\n", BUILD_NUMBER);
  1031. fprintf(stream, "cpu_has_arm_fma: %s\n", ggml_cpu_has_arm_fma() ? "true" : "false");
  1032. fprintf(stream, "cpu_has_avx: %s\n", ggml_cpu_has_avx() ? "true" : "false");
  1033. fprintf(stream, "cpu_has_avx2: %s\n", ggml_cpu_has_avx2() ? "true" : "false");
  1034. fprintf(stream, "cpu_has_avx512: %s\n", ggml_cpu_has_avx512() ? "true" : "false");
  1035. fprintf(stream, "cpu_has_avx512_vbmi: %s\n", ggml_cpu_has_avx512_vbmi() ? "true" : "false");
  1036. fprintf(stream, "cpu_has_avx512_vnni: %s\n", ggml_cpu_has_avx512_vnni() ? "true" : "false");
  1037. fprintf(stream, "cpu_has_blas: %s\n", ggml_cpu_has_blas() ? "true" : "false");
  1038. fprintf(stream, "cpu_has_cublas: %s\n", ggml_cpu_has_cublas() ? "true" : "false");
  1039. fprintf(stream, "cpu_has_clblast: %s\n", ggml_cpu_has_clblast() ? "true" : "false");
  1040. fprintf(stream, "cpu_has_fma: %s\n", ggml_cpu_has_fma() ? "true" : "false");
  1041. fprintf(stream, "cpu_has_gpublas: %s\n", ggml_cpu_has_gpublas() ? "true" : "false");
  1042. fprintf(stream, "cpu_has_neon: %s\n", ggml_cpu_has_neon() ? "true" : "false");
  1043. fprintf(stream, "cpu_has_f16c: %s\n", ggml_cpu_has_f16c() ? "true" : "false");
  1044. fprintf(stream, "cpu_has_fp16_va: %s\n", ggml_cpu_has_fp16_va() ? "true" : "false");
  1045. fprintf(stream, "cpu_has_wasm_simd: %s\n", ggml_cpu_has_wasm_simd() ? "true" : "false");
  1046. fprintf(stream, "cpu_has_blas: %s\n", ggml_cpu_has_blas() ? "true" : "false");
  1047. fprintf(stream, "cpu_has_sse3: %s\n", ggml_cpu_has_sse3() ? "true" : "false");
  1048. fprintf(stream, "cpu_has_vsx: %s\n", ggml_cpu_has_vsx() ? "true" : "false");
  1049. #ifdef NDEBUG
  1050. fprintf(stream, "debug: false\n");
  1051. #else
  1052. fprintf(stream, "debug: true\n");
  1053. #endif // NDEBUG
  1054. fprintf(stream, "model_desc: %s\n", model_desc);
  1055. fprintf(stream, "n_vocab: %d # output size of the final layer, 32001 for some models\n", llama_n_vocab(lctx));
  1056. #ifdef __OPTIMIZE__
  1057. fprintf(stream, "optimize: true\n");
  1058. #else
  1059. fprintf(stream, "optimize: false\n");
  1060. #endif // __OPTIMIZE__
  1061. fprintf(stream, "time: %s\n", timestamp.c_str());
  1062. fprintf(stream, "\n");
  1063. fprintf(stream, "###############\n");
  1064. fprintf(stream, "# User Inputs #\n");
  1065. fprintf(stream, "###############\n");
  1066. fprintf(stream, "\n");
  1067. fprintf(stream, "alias: %s # default: unknown\n", params.model_alias.c_str());
  1068. fprintf(stream, "batch_size: %d # default: 512\n", params.n_batch);
  1069. dump_string_yaml_multiline(stream, "cfg_negative_prompt", params.cfg_negative_prompt.c_str());
  1070. fprintf(stream, "cfg_scale: %f # default: 1.0\n", params.cfg_scale);
  1071. fprintf(stream, "chunks: %d # default: -1 (unlimited)\n", params.n_chunks);
  1072. fprintf(stream, "color: %s # default: false\n", params.use_color ? "true" : "false");
  1073. fprintf(stream, "ctx_size: %d # default: 512\n", params.n_ctx);
  1074. fprintf(stream, "escape: %s # default: false\n", params.escape ? "true" : "false");
  1075. fprintf(stream, "export: %s # default: false\n", params.export_cgraph ? "true" : "false");
  1076. fprintf(stream, "file: # never logged, see prompt instead. Can still be specified for input.\n");
  1077. fprintf(stream, "frequency_penalty: %f # default: 0.0 \n", params.frequency_penalty);
  1078. dump_string_yaml_multiline(stream, "grammar", params.grammar.c_str());
  1079. fprintf(stream, "grammar-file: # never logged, see grammar instead. Can still be specified for input.\n");
  1080. fprintf(stream, "hellaswag: %s # default: false\n", params.hellaswag ? "true" : "false");
  1081. fprintf(stream, "hellaswag_tasks: %zu # default: 400\n", params.hellaswag_tasks);
  1082. const auto logit_bias_eos = params.logit_bias.find(llama_token_eos(lctx));
  1083. const bool ignore_eos = logit_bias_eos != params.logit_bias.end() && logit_bias_eos->second == -INFINITY;
  1084. fprintf(stream, "ignore_eos: %s # default: false\n", ignore_eos ? "true" : "false");
  1085. dump_string_yaml_multiline(stream, "in_prefix", params.input_prefix.c_str());
  1086. fprintf(stream, "in_prefix_bos: %s # default: false\n", params.input_prefix_bos ? "true" : "false");
  1087. dump_string_yaml_multiline(stream, "in_suffix", params.input_prefix.c_str());
  1088. fprintf(stream, "instruct: %s # default: false\n", params.instruct ? "true" : "false");
  1089. fprintf(stream, "interactive: %s # default: false\n", params.interactive ? "true" : "false");
  1090. fprintf(stream, "interactive_first: %s # default: false\n", params.interactive_first ? "true" : "false");
  1091. fprintf(stream, "keep: %d # default: 0\n", params.n_keep);
  1092. fprintf(stream, "logdir: %s # default: unset (no logging)\n", params.logdir.c_str());
  1093. fprintf(stream, "logit_bias:\n");
  1094. for (std::pair<llama_token, float> lb : params.logit_bias) {
  1095. if (ignore_eos && lb.first == logit_bias_eos->first) {
  1096. continue;
  1097. }
  1098. fprintf(stream, " %d: %f", lb.first, lb.second);
  1099. }
  1100. fprintf(stream, "lora: %s\n", params.lora_adapter.c_str());
  1101. fprintf(stream, "lora_base: %s\n", params.lora_base.c_str());
  1102. fprintf(stream, "low_vram: %s # default: false\n", params.low_vram ? "true" : "false");
  1103. fprintf(stream, "main_gpu: %d # default: 0\n", params.main_gpu);
  1104. fprintf(stream, "memory_f32: %s # default: false\n", !params.memory_f16 ? "true" : "false");
  1105. fprintf(stream, "mirostat: %d # default: 0 (disabled)\n", params.mirostat);
  1106. fprintf(stream, "mirostat_ent: %f # default: 5.0\n", params.mirostat_tau);
  1107. fprintf(stream, "mirostat_lr: %f # default: 0.1\n", params.mirostat_eta);
  1108. fprintf(stream, "mlock: %s # default: false\n", params.use_mlock ? "true" : "false");
  1109. fprintf(stream, "model: %s # default: models/7B/ggml-model.bin\n", params.model.c_str());
  1110. fprintf(stream, "model_draft: %s # default:\n", params.model_draft.c_str());
  1111. fprintf(stream, "mtest: %s # default: false\n", params.mem_test ? "true" : "false");
  1112. fprintf(stream, "multiline_input: %s # default: false\n", params.multiline_input ? "true" : "false");
  1113. fprintf(stream, "n_gpu_layers: %d # default: -1\n", params.n_gpu_layers);
  1114. fprintf(stream, "n_predict: %d # default: -1 (unlimited)\n", params.n_predict);
  1115. fprintf(stream, "n_probs: %d # only used by server binary, default: 0\n", params.n_probs);
  1116. fprintf(stream, "no_mmap: %s # default: false\n", !params.use_mmap ? "true" : "false");
  1117. fprintf(stream, "no_mul_mat_q: %s # default: false\n", !params.mul_mat_q ? "true" : "false");
  1118. fprintf(stream, "no_penalize_nl: %s # default: false\n", !params.penalize_nl ? "true" : "false");
  1119. fprintf(stream, "numa: %s # default: false\n", params.numa ? "true" : "false");
  1120. fprintf(stream, "ppl_output_type: %d # default: 0\n", params.ppl_output_type);
  1121. fprintf(stream, "ppl_stride: %d # default: 0\n", params.ppl_stride);
  1122. fprintf(stream, "presence_penalty: %f # default: 0.0\n", params.presence_penalty);
  1123. dump_string_yaml_multiline(stream, "prompt", params.prompt.c_str());
  1124. fprintf(stream, "prompt_cache: %s\n", params.path_prompt_cache.c_str());
  1125. fprintf(stream, "prompt_cache_all: %s # default: false\n", params.prompt_cache_all ? "true" : "false");
  1126. fprintf(stream, "prompt_cache_ro: %s # default: false\n", params.prompt_cache_ro ? "true" : "false");
  1127. dump_vector_int_yaml(stream, "prompt_tokens", prompt_tokens);
  1128. fprintf(stream, "random_prompt: %s # default: false\n", params.random_prompt ? "true" : "false");
  1129. fprintf(stream, "repeat_penalty: %f # default: 1.1\n", params.repeat_penalty);
  1130. fprintf(stream, "reverse_prompt:\n");
  1131. for (std::string ap : params.antiprompt) {
  1132. size_t pos = 0;
  1133. while ((pos = ap.find('\n', pos)) != std::string::npos) {
  1134. ap.replace(pos, 1, "\\n");
  1135. pos += 1;
  1136. }
  1137. fprintf(stream, " - %s\n", ap.c_str());
  1138. }
  1139. fprintf(stream, "rope_freq_base: %f # default: 10000.0\n", params.rope_freq_base);
  1140. fprintf(stream, "rope_freq_scale: %f # default: 1.0\n", params.rope_freq_scale);
  1141. fprintf(stream, "seed: %d # default: -1 (random seed)\n", params.seed);
  1142. fprintf(stream, "simple_io: %s # default: false\n", params.simple_io ? "true" : "false");
  1143. fprintf(stream, "temp: %f # default: 0.8\n", params.temp);
  1144. const std::vector<float> tensor_split_vector(params.tensor_split, params.tensor_split + LLAMA_MAX_DEVICES);
  1145. dump_vector_float_yaml(stream, "tensor_split", tensor_split_vector);
  1146. fprintf(stream, "tfs: %f # default: 1.0\n", params.tfs_z);
  1147. fprintf(stream, "threads: %d # default: %d\n", params.n_threads, std::thread::hardware_concurrency());
  1148. fprintf(stream, "top_k: %d # default: 40\n", params.top_k);
  1149. fprintf(stream, "top_p: %f # default: 0.95\n", params.top_p);
  1150. fprintf(stream, "typical_p: %f # default: 1.0\n", params.typical_p);
  1151. fprintf(stream, "verbose_prompt: %s # default: false\n", params.verbose_prompt ? "true" : "false");
  1152. }